-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.py
330 lines (276 loc) · 8.03 KB
/
template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import os
import shutil
import argparse
class RAGProjectGenerator:
def __init__(self, project_name='simple-rag-model'):
"""
Initialize RAG project generator
Args:
project_name (str): Name of the project to be created
"""
self.project_name = project_name
self.base_dir = os.path.abspath(project_name)
# Project structure
self.directories = [
'src',
'configs',
'data/raw',
'data/processed',
'tests',
'notebooks',
'scripts'
]
# Template files with their content and paths
self.files = [
{
'path': os.path.join('src', '__init__.py'),
'content': '# RAG Model Source Package\n'
},
{
'path': os.path.join('src', 'main.py'),
'content': self._get_main_py_template()
},
{
'path': os.path.join('src', 'data_processing.py'),
'content': self._get_data_processing_template()
},
{
'path': os.path.join('src', 'model.py'),
'content': self._get_model_py_template()
},
{
'path': os.path.join('src', 'retriever.py'),
'content': self._get_retriever_py_template()
},
{
'path': os.path.join('src', 'utils.py'),
'content': self._get_utils_py_template()
},
{
'path': os.path.join('configs', '__init__.py'),
'content': '# Configuration Package\n'
},
{
'path': os.path.join('configs', 'config.yaml'),
'content': self._get_config_yaml_template()
},
{
'path': os.path.join('tests', '__init__.py'),
'content': '# RAG Model Tests\n'
},
{
'path': 'README.md',
'content': self._get_readme_template()
},
{
'path': 'setup.py',
'content': self._get_setup_py_template()
},
{
'path': os.path.join('notebooks', 'exploration.ipynb'),
'content': self._get_notebook_template()
},
{
'path': os.path.join('scripts', 'train.py'),
'content': self._get_train_script_template()
},
{
'path': os.path.join('scripts', 'inference.py'),
'content': self._get_inference_script_template()
}
]
def generate(self):
"""
Generate the entire project structure
"""
# Create base directory
os.makedirs(self.base_dir, exist_ok=True)
# Create subdirectories
for directory in self.directories:
os.makedirs(os.path.join(self.base_dir, directory), exist_ok=True)
# Create files
for file_info in self.files:
full_path = os.path.join(self.base_dir, file_info['path'])
# Ensure directory exists
os.makedirs(os.path.dirname(full_path), exist_ok=True)
# Write file
with open(full_path, 'w') as f:
f.write(file_info['content'])
print(f"Project '{self.project_name}' generated successfully!")
# Template generation methods
def _get_main_py_template(self):
return '''import logging
import argparse
from typing import Dict, Any
def train(config_path: str):
"""Main training function"""
logging.info(f"Training with config: {config_path}")
def inference(config_path: str, query: str):
"""Inference function"""
logging.info(f"Inferencing query: {query}")
def main():
parser = argparse.ArgumentParser(description="RAG Model")
parser.add_argument('--mode', choices=['train', 'inference'], required=True)
parser.add_argument('--config', default='configs/config.yaml')
parser.add_argument('--query', help='Query for inference')
args = parser.parse_args()
# Configure logging
logging.basicConfig(level=logging.INFO)
if args.mode == 'train':
train(args.config)
elif args.mode == 'inference':
if not args.query:
parser.error("Query is required for inference")
inference(args.config, args.query)
if __name__ == '__main__':
main()
'''
def _get_data_processing_template(self):
return '''import pandas as pd
from typing import Dict, Any
class DataProcessor:
def __init__(self, config: Dict[str, Any]):
self.config = config
def load_data(self, split='train'):
"""Load and preprocess data"""
# Implement data loading logic
pass
def preprocess(self, data):
"""Preprocess data"""
# Implement preprocessing steps
return data
'''
def _get_model_py_template(self):
return '''class RAGModel:
def __init__(self, config):
self.config = config
def train(self, train_data, val_data):
"""Train the RAG model"""
pass
def generate(self, query, context):
"""Generate response for given query and context"""
pass
'''
def _get_retriever_py_template(self):
return '''class SemanticRetriever:
def __init__(self, config):
self.config = config
def retrieve(self, query, top_k=5):
"""Retrieve relevant context for a query"""
pass
'''
def _get_utils_py_template(self):
return '''import yaml
def load_config(config_path):
"""Load configuration from YAML file"""
with open(config_path, 'r') as f:
return yaml.safe_load(f)
'''
def _get_config_yaml_template(self):
return '''# RAG Model Configuration
data:
path: 'data/raw'
model:
type: 'transformer'
name: 'facebook/bart-base'
retrieval:
top_k: 5
training:
epochs: 10
batch_size: 16
learning_rate: 2e-5
'''
def _get_readme_template(self):
return '''# RAG Model Project
## Setup
```bash
pip install -e .
```
## Training
```bash
python src/main.py --mode train
```
## Inference
```bash
python src/main.py --mode inference --query "Your query here"
```
'''
def _get_setup_py_template(self):
return '''from setuptools import setup, find_packages
setup(
name='rag-model',
version='0.1.0',
packages=find_packages(where='src'),
package_dir={'': 'src'},
install_requires=[
'torch',
'transformers',
'pandas',
'pyyaml'
],
extras_require={
'dev': ['pytest', 'black']
}
)
'''
def _get_gitignore_template(self):
return '''# Python
__pycache__/
*.py[cod]
*$py.class
# Virtual environments
venv/
env/
.env/
# Jupyter
.ipynb_checkpoints/
# Model and data
*.pt
*.pth
data/processed/
# IDE
.vscode/
.idea/
'''
def _get_notebook_template(self):
return '''{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# RAG Model Exploration"]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": ["# Initial data and model exploration"]
}
]
}
'''
def _get_train_script_template(self):
return '''#!/usr/bin/env python
from src.main import train
if __name__ == '__main__':
train('configs/config.yaml')
'''
def _get_inference_script_template(self):
return '''#!/usr/bin/env python
from src.main import inference
if __name__ == '__main__':
inference('configs/config.yaml', "Sample query")
'''
def main():
parser = argparse.ArgumentParser(description="RAG Project Generator")
parser.add_argument(
'--name',
default='simple-rag-model',
help='Name of the project to generate'
)
args = parser.parse_args()
# Generate project
generator = RAGProjectGenerator(args.name)
generator.generate()
if __name__ == '__main__':
main()