geekydraco commited on
Commit
17032cb
·
verified ·
1 Parent(s): 492cab8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -48
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import spaces # must be imported before torch/other CUDA-touching modules (ZeroGPU requirement)
2
  import time
3
  from pathlib import Path
4
  import sys
@@ -6,7 +6,7 @@ import os
6
  import logging
7
 
8
  # ==========================================
9
- # 0. Fix sys.path BEFORE importing anything from src/
10
  # ==========================================
11
  project_root = Path(__file__).parent.resolve()
12
  sys.path.insert(0, str(project_root))
@@ -18,7 +18,7 @@ from config import load_config
18
  from src.models.load_model import ModelLoader
19
  from src.generators.program_generator import GenerationPipeline
20
  from src.generators.text_to_mongo_generator import TextToMongoGenerator
21
- from src.generators.doc_generator import DocGenerator
22
  from src.vectorDB.index_manager import IndexManager
23
  from src.rag.rag_pipeline import RAGPipeline
24
 
@@ -26,7 +26,6 @@ from src.rag.rag_pipeline import RAGPipeline
26
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
27
  logger = logging.getLogger(__name__)
28
 
29
- # Environment variables to suppress warnings
30
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
31
  os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
32
  os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
@@ -42,7 +41,6 @@ model_loader = ModelLoader(config)
42
  tokenizer = model_loader.load_tokenizer()
43
  base_model = model_loader.load_base_model()
44
 
45
- # Try to load the Fine-Tuned (LoRA) model if it exists
46
  lora_path = Path(config.lora.output_dir)
47
  if lora_path.exists() and (lora_path / "adapter_config.json").exists():
48
  logger.info(f"✅ Found LoRA adapter at {lora_path}. Loading Fine-Tuned model...")
@@ -58,18 +56,18 @@ logger.info("Setting up generation pipelines...")
58
  base_pipeline = GenerationPipeline(base_model, tokenizer, config.generation)
59
  finetuned_pipeline = GenerationPipeline(finetuned_model, tokenizer, config.generation)
60
 
61
- # Text-to-MongoDB Generators
62
- base_generator = TextToMongoGenerator(base_pipeline, config)
63
- finetuned_generator = TextToMongoGenerator(finetuned_pipeline, config)
64
 
65
- # Documentation Generators
66
  base_doc_generator = DocGenerator(base_pipeline)
67
  finetuned_doc_generator = DocGenerator(finetuned_pipeline)
68
 
69
  # ==========================================
70
- # 3. Setup RAG Pipeline (Optional)
71
  # ==========================================
 
72
  rag_pipeline = None
 
73
  try:
74
  index_manager = IndexManager(
75
  embedding_model=config.embedding.external_model,
@@ -98,10 +96,12 @@ except Exception as e:
98
  def generate_output(task, input_text, model_choice, use_rag, top_k):
99
  if not input_text.strip():
100
  return "Please enter a valid input.", "Latency: N/A"
101
-
102
  start_time = time.time()
103
-
 
104
  if task == "Text-to-MongoDB":
 
105
  if use_rag and rag_pipeline is not None:
106
  generated_query, context_metadata = rag_pipeline.generate_with_rag(input_text, top_k=int(top_k))
107
  latency = (time.time() - start_time) * 1000
@@ -110,36 +110,64 @@ def generate_output(task, input_text, model_choice, use_rag, top_k):
110
  q = ctx.get('question', 'N/A')
111
  mql = ctx.get('generated_mongodb_query', ctx.get('mongodb_query', 'N/A'))
112
  context_str += f"[{i + 1}] Q: {q}\n MQL: {mql}\n\n"
113
- return generated_query, f"⏱️ Latency: {latency:.2f} ms\n\n{context_str}"
 
 
114
  else:
115
  if model_choice == "Fine-Tuned (LoRA)":
116
- result = finetuned_generator.generate_single(input_text)
117
  else:
118
- result = base_generator.generate_single(input_text)
119
- latency = result['latency_ms']
120
- info_text = f"⏱️ Latency: {latency:.2f} ms\nModel: {model_choice}\nTask: Text-to-MongoDB"
121
- return result['generated_query'], info_text
122
-
123
  elif task == "Documentation Generation":
124
- if model_choice == "Fine-Tuned (LoRA)":
125
- generated_doc = finetuned_doc_generator.generate_docstring(input_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  else:
127
- generated_doc = base_doc_generator.generate_docstring(input_text)
128
- latency = (time.time() - start_time) * 1000
129
- info_text = f"⏱️ Latency: {latency:.2f} ms\nModel: {model_choice}\nTask: Documentation Generation"
130
- return generated_doc, info_text
 
 
 
131
 
132
  def update_ui(task):
133
- """Dynamically updates input placeholders and output syntax highlighting based on the selected task."""
134
  if task == "Text-to-MongoDB":
135
  return (
136
  gr.update(placeholder="e.g., How many singers do we have?", label="Natural Language Question"),
137
- gr.update(language="javascript")
 
138
  )
139
  else:
140
  return (
141
  gr.update(placeholder="e.g., def add(a, b):\n return a + b", label="Code Snippet"),
142
- gr.update(language="python")
 
143
  )
144
 
145
  # ==========================================
@@ -148,11 +176,11 @@ def update_ui(task):
148
  with gr.Blocks(title="CodeGen", theme=gr.themes.Soft()) as demo:
149
  gr.Markdown(
150
  """
151
- # 🚀 CodeGen
152
  Generate **MongoDB queries** or **Code Documentation** using Base, Fine-Tuned, or RAG-enhanced models.
153
  """
154
  )
155
-
156
  with gr.Row():
157
  # Left Column: Controls
158
  with gr.Column(scale=1):
@@ -166,20 +194,20 @@ with gr.Blocks(title="CodeGen", theme=gr.themes.Soft()) as demo:
166
  value="Fine-Tuned (LoRA)",
167
  label="Model Selection"
168
  )
169
-
170
  with gr.Accordion("⚙️ Advanced Settings", open=False):
171
  use_rag = gr.Checkbox(
172
- label="🧠 Use RAG (Text-to-MongoDB only)",
173
  value=False,
174
  info="Requires pre-built indices"
175
  )
176
  top_k_slider = gr.Slider(
177
- minimum=1, maximum=10, value=3, step=1,
178
  label="Top-K Retrieved Contexts"
179
  )
180
-
181
  generate_btn = gr.Button("Generate", variant="primary", size="lg")
182
-
183
  # Right Column: Inputs & Outputs
184
  with gr.Column(scale=2):
185
  input_box = gr.Textbox(
@@ -189,14 +217,14 @@ with gr.Blocks(title="CodeGen", theme=gr.themes.Soft()) as demo:
189
  info="Type your question or paste your code snippet here."
190
  )
191
  output_box = gr.Code(
192
- label="Generated Output",
193
- language="javascript",
194
  lines=10,
195
  interactive=False
196
  )
197
  info_output = gr.Textbox(
198
- label="Generation Info",
199
- lines=4,
200
  interactive=False
201
  )
202
 
@@ -213,9 +241,12 @@ with gr.Blocks(title="CodeGen", theme=gr.themes.Soft()) as demo:
213
  cache_examples=False
214
  )
215
 
216
- # Link events
217
- task_selector.change(fn=update_ui, inputs=task_selector, outputs=[input_box, output_box])
218
-
 
 
 
219
  generate_btn.click(
220
  fn=generate_output,
221
  inputs=[task_selector, input_box, model_choice, use_rag, top_k_slider],
@@ -226,9 +257,4 @@ with gr.Blocks(title="CodeGen", theme=gr.themes.Soft()) as demo:
226
  # 6. Launch the App
227
  # ==========================================
228
  if __name__ == "__main__":
229
- demo.launch(
230
- server_name="0.0.0.0",
231
- server_port=7860,
232
- share=False,
233
- show_error=True
234
- )
 
1
+ import spaces
2
  import time
3
  from pathlib import Path
4
  import sys
 
6
  import logging
7
 
8
  # ==========================================
9
+ # 0. Fix sys.path BEFORE importing src/
10
  # ==========================================
11
  project_root = Path(__file__).parent.resolve()
12
  sys.path.insert(0, str(project_root))
 
18
  from src.models.load_model import ModelLoader
19
  from src.generators.program_generator import GenerationPipeline
20
  from src.generators.text_to_mongo_generator import TextToMongoGenerator
21
+ from src.generators.doc_generator import DocGenerator
22
  from src.vectorDB.index_manager import IndexManager
23
  from src.rag.rag_pipeline import RAGPipeline
24
 
 
26
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
27
  logger = logging.getLogger(__name__)
28
 
 
29
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
30
  os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
31
  os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
 
41
  tokenizer = model_loader.load_tokenizer()
42
  base_model = model_loader.load_base_model()
43
 
 
44
  lora_path = Path(config.lora.output_dir)
45
  if lora_path.exists() and (lora_path / "adapter_config.json").exists():
46
  logger.info(f"✅ Found LoRA adapter at {lora_path}. Loading Fine-Tuned model...")
 
56
  base_pipeline = GenerationPipeline(base_model, tokenizer, config.generation)
57
  finetuned_pipeline = GenerationPipeline(finetuned_model, tokenizer, config.generation)
58
 
59
+ base_mongo_generator = TextToMongoGenerator(base_pipeline, config)
60
+ finetuned_mongo_generator = TextToMongoGenerator(finetuned_pipeline, config)
 
61
 
 
62
  base_doc_generator = DocGenerator(base_pipeline)
63
  finetuned_doc_generator = DocGenerator(finetuned_pipeline)
64
 
65
  # ==========================================
66
+ # 3. Setup RAG Pipeline & Index Manager
67
  # ==========================================
68
+ index_manager = None
69
  rag_pipeline = None
70
+
71
  try:
72
  index_manager = IndexManager(
73
  embedding_model=config.embedding.external_model,
 
96
  def generate_output(task, input_text, model_choice, use_rag, top_k):
97
  if not input_text.strip():
98
  return "Please enter a valid input.", "Latency: N/A"
99
+
100
  start_time = time.time()
101
+
102
+ # ==================== TEXT-TO-MONGODB ====================
103
  if task == "Text-to-MongoDB":
104
+ # With RAG
105
  if use_rag and rag_pipeline is not None:
106
  generated_query, context_metadata = rag_pipeline.generate_with_rag(input_text, top_k=int(top_k))
107
  latency = (time.time() - start_time) * 1000
 
110
  q = ctx.get('question', 'N/A')
111
  mql = ctx.get('generated_mongodb_query', ctx.get('mongodb_query', 'N/A'))
112
  context_str += f"[{i + 1}] Q: {q}\n MQL: {mql}\n\n"
113
+ info = f"⏱️ Latency: {latency:.2f} ms\nModel: Fine-Tuned (LoRA) + RAG\nTask: Text-to-MongoDB\n\n{context_str}"
114
+ return generated_query, info
115
+ # Without RAG
116
  else:
117
  if model_choice == "Fine-Tuned (LoRA)":
118
+ result = finetuned_mongo_generator.generate_single(input_text)
119
  else:
120
+ result = base_mongo_generator.generate_single(input_text)
121
+ info = f"⏱️ Latency: {result['latency_ms']:.2f} ms\nModel: {model_choice}\nTask: Text-to-MongoDB"
122
+ return result['generated_query'], info
123
+
124
+ # ==================== DOCUMENTATION GENERATION ====================
125
  elif task == "Documentation Generation":
126
+ # With RAG
127
+ if use_rag and index_manager is not None:
128
+ # Retrieve similar code snippets from the vector index
129
+ context_metadata = index_manager.search(input_text, top_k=int(top_k))
130
+ context_str = "Retrieved Context:\n" + "-" * 30 + "\n"
131
+ for i, ctx in enumerate(context_metadata[:int(top_k)]):
132
+ code = ctx.get('code', ctx.get('text', ctx.get('question', 'N/A')))
133
+ context_str += f"[{i + 1}] {code}\n\n"
134
+
135
+ # Enrich the input with retrieved context for better doc generation
136
+ enriched_input = (
137
+ f"Reference examples:\n{context_str}\n"
138
+ f"Now generate documentation for the following code:\n{input_text}"
139
+ )
140
+
141
+ if model_choice == "Fine-Tuned (LoRA)":
142
+ generated_doc = finetuned_doc_generator.generate_docstring(enriched_input)
143
+ else:
144
+ generated_doc = base_doc_generator.generate_docstring(enriched_input)
145
+
146
+ latency = (time.time() - start_time) * 1000
147
+ info = f"⏱️ Latency: {latency:.2f} ms\nModel: {model_choice} + RAG\nTask: Documentation Generation\n\n{context_str}"
148
+ return generated_doc, info
149
+ # Without RAG
150
  else:
151
+ if model_choice == "Fine-Tuned (LoRA)":
152
+ generated_doc = finetuned_doc_generator.generate_docstring(input_text)
153
+ else:
154
+ generated_doc = base_doc_generator.generate_docstring(input_text)
155
+ latency = (time.time() - start_time) * 1000
156
+ info = f"⏱️ Latency: {latency:.2f} ms\nModel: {model_choice}\nTask: Documentation Generation"
157
+ return generated_doc, info
158
 
159
  def update_ui(task):
 
160
  if task == "Text-to-MongoDB":
161
  return (
162
  gr.update(placeholder="e.g., How many singers do we have?", label="Natural Language Question"),
163
+ gr.update(language="javascript"),
164
+ gr.update(label="🧠 Use RAG (Text-to-MongoDB only)")
165
  )
166
  else:
167
  return (
168
  gr.update(placeholder="e.g., def add(a, b):\n return a + b", label="Code Snippet"),
169
+ gr.update(language="python"),
170
+ gr.update(label="🧠 Use RAG (Documentation only)")
171
  )
172
 
173
  # ==========================================
 
176
  with gr.Blocks(title="CodeGen", theme=gr.themes.Soft()) as demo:
177
  gr.Markdown(
178
  """
179
+ # 🤖 CodeGen
180
  Generate **MongoDB queries** or **Code Documentation** using Base, Fine-Tuned, or RAG-enhanced models.
181
  """
182
  )
183
+
184
  with gr.Row():
185
  # Left Column: Controls
186
  with gr.Column(scale=1):
 
194
  value="Fine-Tuned (LoRA)",
195
  label="Model Selection"
196
  )
197
+
198
  with gr.Accordion("⚙️ Advanced Settings", open=False):
199
  use_rag = gr.Checkbox(
200
+ label="🧠 Use RAG (Text-to-MongoDB only)",
201
  value=False,
202
  info="Requires pre-built indices"
203
  )
204
  top_k_slider = gr.Slider(
205
+ minimum=1, maximum=10, value=3, step=1,
206
  label="Top-K Retrieved Contexts"
207
  )
208
+
209
  generate_btn = gr.Button("Generate", variant="primary", size="lg")
210
+
211
  # Right Column: Inputs & Outputs
212
  with gr.Column(scale=2):
213
  input_box = gr.Textbox(
 
217
  info="Type your question or paste your code snippet here."
218
  )
219
  output_box = gr.Code(
220
+ label="Generated Output",
221
+ language="javascript",
222
  lines=10,
223
  interactive=False
224
  )
225
  info_output = gr.Textbox(
226
+ label="Generation Info",
227
+ lines=4,
228
  interactive=False
229
  )
230
 
 
241
  cache_examples=False
242
  )
243
 
244
+ task_selector.change(
245
+ fn=update_ui,
246
+ inputs=task_selector,
247
+ outputs=[input_box, output_box, use_rag]
248
+ )
249
+
250
  generate_btn.click(
251
  fn=generate_output,
252
  inputs=[task_selector, input_box, model_choice, use_rag, top_k_slider],
 
257
  # 6. Launch the App
258
  # ==========================================
259
  if __name__ == "__main__":
260
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False, show_error=True)