geekydraco commited on
Commit
fae8722
·
verified ·
1 Parent(s): 4c914f9

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -210
app.py DELETED
@@ -1,210 +0,0 @@
1
- import gradio as gr
2
- import torch
3
- import time
4
- from pathlib import Path
5
- import sys
6
- import os
7
- import logging
8
- from src.config import load_config
9
- from src.models.load_model import ModelLoader
10
- from src.generators.program_generator import GenerationPipeline
11
- from src.generators.text_to_mongo_generator import TextToMongoGenerator
12
- from src.vectorDB.index_manager import IndexManager
13
- from src.rag.rag_pipeline import RAGPipeline
14
-
15
- # Configure logging
16
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
17
- logger = logging.getLogger(__name__)
18
-
19
- # Environment variables to suppress warnings
20
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
21
- os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
22
- os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
23
-
24
- # Add project root and src to path
25
- project_root = Path(__file__).parent.resolve()
26
- sys.path.append(str(project_root))
27
- sys.path.append(str(project_root / "src"))
28
-
29
- # ==========================================
30
- # 1. Load Configuration & Models
31
- # ==========================================
32
- logger.info("Loading configuration...")
33
- config = load_config("configs/config.yaml")
34
-
35
- logger.info("Initializing Model Loader...")
36
- model_loader = ModelLoader(config)
37
- tokenizer = model_loader.load_tokenizer()
38
- base_model = model_loader.load_base_model()
39
-
40
- # Try to load the Fine-Tuned (LoRA) model if it exists
41
- lora_path = Path(config.lora.output_dir)
42
- if lora_path.exists() and (lora_path / "adapter_config.json").exists():
43
- logger.info(f"✅ Found LoRA adapter at {lora_path}. Loading Fine-Tuned model...")
44
- finetuned_model = model_loader.autodetect_saved_model(str(lora_path))
45
- else:
46
- logger.warning("⚠️ No LoRA adapter found. Fine-Tuned model will fallback to Base model.")
47
- finetuned_model = base_model
48
-
49
- # ==========================================
50
- # 2. Setup Generation Pipelines
51
- # ==========================================
52
- logger.info("Setting up generation pipelines...")
53
- base_pipeline = GenerationPipeline(base_model, tokenizer, config.generation)
54
- finetuned_pipeline = GenerationPipeline(finetuned_model, tokenizer, config.generation)
55
-
56
- base_generator = TextToMongoGenerator(base_pipeline, config)
57
- finetuned_generator = TextToMongoGenerator(finetuned_pipeline, config)
58
-
59
- # ==========================================
60
- # 3. Setup RAG Pipeline (Optional)
61
- # ==========================================
62
- rag_pipeline = None
63
- try:
64
- index_manager = IndexManager(
65
- embedding_model=config.embedding.external_model,
66
- language=config.retrieval.structural_language,
67
- semantic_weight=1.0 - config.retrieval.structural_weight_alpha,
68
- ast_weight=config.retrieval.structural_weight_alpha,
69
- save_dir="data/indices"
70
- )
71
-
72
- if index_manager._indices_exist():
73
- index_manager.load_indices()
74
- rag_pipeline = RAGPipeline(
75
- retriever=index_manager,
76
- generator=finetuned_pipeline,
77
- config=config.generation
78
- )
79
- logger.info("✅ RAG Pipeline initialized successfully.")
80
- else:
81
- logger.warning("⚠️ RAG indices not found in 'data/indices'. RAG feature will be disabled.")
82
- except Exception as e:
83
- logger.error(f"⚠️ Could not initialize RAG pipeline: {e}")
84
-
85
-
86
- # ==========================================
87
- # 4. Gradio Generation Logic
88
- # ==========================================
89
- def generate_mongo_query(question: str, model_choice: str, use_rag: bool, top_k: int):
90
- if not question.strip():
91
- return "Please enter a valid question.", "Latency: N/A"
92
-
93
- start_time = time.time()
94
-
95
- # RAG Generation
96
- if use_rag and rag_pipeline is not None:
97
- generated_query, context_metadata = rag_pipeline.generate_with_rag(question, top_k=int(top_k))
98
- latency = (time.time() - start_time) * 1000
99
-
100
- # Format context for display
101
- context_str = "Retrieved Context:\n" + "-" * 30 + "\n"
102
- for i, ctx in enumerate(context_metadata[:int(top_k)]):
103
- q = ctx.get('question', 'N/A')
104
- mql = ctx.get('generated_mongodb_query', ctx.get('mongodb_query', 'N/A'))
105
- context_str += f"[{i + 1}] Q: {q}\n MQL: {mql}\n\n"
106
-
107
- return generated_query, f"⏱️ Latency: {latency:.2f} ms\n\n{context_str}"
108
-
109
- # Standard Generation (Base or Fine-Tuned)
110
- else:
111
- if model_choice == "Fine-Tuned (LoRA)":
112
- result = finetuned_generator.generate_single(question)
113
- else:
114
- result = base_generator.generate_single(question)
115
-
116
- latency = result['latency_ms']
117
- info_text = f"⏱️ Latency: {latency:.2f} ms\nModel: {model_choice}"
118
- return result['generated_query'], info_text
119
-
120
-
121
- # ==========================================
122
- # 5. Build Gradio UI
123
- # ==========================================
124
- with gr.Blocks(title="Text-to-MongoDB Generator", theme=gr.themes.Soft()) as demo:
125
- gr.Markdown(
126
- """
127
- # 🚀 Text-to-MongoDB Query Generator
128
- Convert natural language questions into executable MongoDB queries using **Base**, **Fine-Tuned**, or **RAG-enhanced** models.
129
- """
130
- )
131
-
132
- with gr.Row():
133
- # Left Column: Inputs
134
- with gr.Column(scale=3):
135
- question_input = gr.Textbox(
136
- label="Natural Language Question",
137
- placeholder="e.g., How many singers do we have?",
138
- lines=2,
139
- info="Type your question about the database here."
140
- )
141
-
142
- with gr.Row():
143
- model_choice = gr.Radio(
144
- choices=["Base Model", "Fine-Tuned (LoRA)"],
145
- value="Fine-Tuned (LoRA)",
146
- label="Model Selection"
147
- )
148
- use_rag = gr.Checkbox(
149
- label="🧠 Use RAG (Retrieval-Augmented Generation)",
150
- value=False,
151
- info="Requires pre-built indices"
152
- )
153
-
154
- with gr.Accordion("⚙️ RAG Settings", open=False):
155
- top_k_slider = gr.Slider(
156
- minimum=1, maximum=10, value=3, step=1,
157
- label="Top-K Retrieved Contexts",
158
- info="Number of similar examples to retrieve from the vector database."
159
- )
160
-
161
- generate_btn = gr.Button("Generate MongoDB Query", variant="primary", size="lg")
162
-
163
- # Right Column: Outputs
164
- with gr.Column(scale=2):
165
- query_output = gr.Code(
166
- label="Generated MongoDB Query",
167
- language="javascript",
168
- lines=6,
169
- interactive=False
170
- )
171
- info_output = gr.Textbox(
172
- label="Generation Info & Context",
173
- lines=8,
174
- interactive=False,
175
- max_lines=15
176
- )
177
-
178
- gr.Markdown("---")
179
- gr.Markdown("### 💡 Example Questions")
180
- gr.Examples(
181
- examples=[
182
- ["How many singers do we have?"],
183
- ["What is the average age of all singers from France?"],
184
- ["Show the name and release year of the song by the youngest singer."],
185
- ["Find the number of pets whose weight is heavier than 10."],
186
- ["What are the different countries with singers above age 20?"],
187
- ["List the name and date of each battle."],
188
- ],
189
- inputs=[question_input],
190
- cache_examples=False
191
- )
192
-
193
- # Link button to function
194
- generate_btn.click(
195
- fn=generate_mongo_query,
196
- inputs=[question_input, model_choice, use_rag, top_k_slider],
197
- outputs=[query_output, info_output]
198
- )
199
-
200
- # ==========================================
201
- # 6. Launch the App
202
- # ==========================================
203
- if __name__ == "__main__":
204
- # Launch locally on port 7860
205
- demo.launch(
206
- server_name="0.0.0.0", # Makes it accessible on your local network
207
- server_port=7860,
208
- share=False, # Set to True if you want a public temporary URL
209
- show_error=True
210
- )