Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,54 +1,72 @@
|
|
| 1 |
-
"""Gradio
|
| 2 |
|
| 3 |
import gradio as gr
|
|
|
|
| 4 |
import os
|
| 5 |
import json
|
| 6 |
-
from datetime import datetime
|
| 7 |
|
| 8 |
from model import VedaProgrammingLLM
|
| 9 |
from tokenizer import VedaTokenizer
|
| 10 |
-
from data_collector import collector
|
| 11 |
-
from continuous_trainer import trainer
|
| 12 |
from database import db
|
| 13 |
-
from train import VedaTrainer
|
| 14 |
-
from config import
|
| 15 |
-
MODEL_DIR, DEFAULT_TEMPERATURE, DEFAULT_MAX_TOKENS,
|
| 16 |
-
DEFAULT_REPETITION_PENALTY, DEFAULT_TOP_K
|
| 17 |
-
)
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def initialize():
|
| 23 |
-
"""Initialize the
|
| 24 |
-
|
| 25 |
-
print("=" * 50)
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
)
|
| 39 |
-
initial_trainer.train(epochs=10, save_path=MODEL_DIR)
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
print("β
System ready!")
|
| 49 |
-
|
| 50 |
-
def clean_output(text: str) -> str:
|
| 51 |
-
"""Clean generated output"""
|
| 52 |
lines = text.split('\n')
|
| 53 |
cleaned = []
|
| 54 |
empty_count = 0
|
|
@@ -62,410 +80,209 @@ def clean_output(text: str) -> str:
|
|
| 62 |
empty_count = 0
|
| 63 |
cleaned.append(line)
|
| 64 |
|
| 65 |
-
return '\n'.join(cleaned)
|
| 66 |
|
| 67 |
-
def
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
repetition_penalty: float,
|
| 72 |
-
top_k: int
|
| 73 |
-
) -> tuple:
|
| 74 |
-
"""Generate code and track interaction"""
|
| 75 |
-
global current_interaction_id
|
| 76 |
|
| 77 |
-
if
|
| 78 |
-
return "β³ Model loading..."
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
-
prompt=prompt,
|
| 87 |
-
max_tokens=int(max_tokens),
|
| 88 |
-
temperature=float(temperature),
|
| 89 |
-
repetition_penalty=float(repetition_penalty),
|
| 90 |
-
top_k=int(top_k)
|
| 91 |
-
)
|
| 92 |
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
-
#
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
temperature=temperature,
|
| 100 |
-
|
|
|
|
|
|
|
| 101 |
)
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
except Exception as e:
|
| 106 |
import traceback
|
| 107 |
traceback.print_exc()
|
| 108 |
-
return f"β Error: {str(e)}"
|
| 109 |
|
| 110 |
-
def
|
| 111 |
-
"""
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
collector.record_feedback(
|
| 116 |
-
interaction_id=interaction_id,
|
| 117 |
-
is_positive=is_positive,
|
| 118 |
-
edited_code=edited_code if edited_code and edited_code.strip() else None
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
emoji = "π" if is_positive else "π"
|
| 122 |
-
pending = collector.get_pending_count()
|
| 123 |
-
|
| 124 |
-
msg = f"{emoji} Feedback recorded! Thank you for helping improve the model.\n"
|
| 125 |
-
msg += f"π Approved samples pending training: {pending}"
|
| 126 |
-
|
| 127 |
-
if trainer.should_retrain():
|
| 128 |
-
msg += "\nπ Enough samples collected - model will be retrained soon!"
|
| 129 |
-
|
| 130 |
-
return msg
|
| 131 |
|
| 132 |
-
def
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
def
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
def
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
result = trainer.train(epochs=int(epochs))
|
| 144 |
-
|
| 145 |
-
if result['status'] == 'success':
|
| 146 |
-
return f"""β
Training Complete!
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
- Accuracy: {result['accuracy']:.4f}
|
| 152 |
-
- Samples Used: {result['samples_used']}
|
| 153 |
-
"""
|
| 154 |
-
else:
|
| 155 |
-
return f"β Training Error: {result['message']}"
|
| 156 |
-
|
| 157 |
-
def add_training_code(code: str, category: str):
|
| 158 |
-
"""Add code directly to training data"""
|
| 159 |
-
if not code.strip():
|
| 160 |
-
return "β οΈ Please enter some code"
|
| 161 |
|
| 162 |
-
|
| 163 |
-
return f"β
Code added to training data!\nCategory: {category}"
|
| 164 |
-
|
| 165 |
-
def get_statistics():
|
| 166 |
-
"""Get system statistics"""
|
| 167 |
-
stats = collector.get_statistics()
|
| 168 |
-
status = trainer.get_status()
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
### Model Status
|
| 173 |
-
| Property | Value |
|
| 174 |
-
|----------|-------|
|
| 175 |
-
| π€ Model Version | {status['model_version']} |
|
| 176 |
-
| π Currently Training | {'Yes' if status['is_training'] else 'No'} |
|
| 177 |
-
| π Training Progress | {status['training_progress']:.0f}% |
|
| 178 |
-
| β° Last Training | {status['last_training'] or 'Never'} |
|
| 179 |
-
|
| 180 |
-
### Learning Data
|
| 181 |
-
| Metric | Count |
|
| 182 |
-
|--------|-------|
|
| 183 |
-
| π¬ Total Interactions | {stats['total_interactions']} |
|
| 184 |
-
| π Positive Feedback | {stats['positive_feedback']} |
|
| 185 |
-
| π Negative Feedback | {stats['negative_feedback']} |
|
| 186 |
-
| β
Approved Samples | {stats['approved_samples']} |
|
| 187 |
-
| π Pending for Training | {status['pending_samples']} |
|
| 188 |
-
| π― Min Samples to Retrain | {status['min_samples_for_training']} |
|
| 189 |
-
|
| 190 |
-
### Training History
|
| 191 |
-
| Metric | Value |
|
| 192 |
-
|--------|-------|
|
| 193 |
-
| π Total Training Runs | {stats['training_runs']} |
|
| 194 |
-
| π Code Samples | {stats['code_samples']} |
|
| 195 |
-
|
| 196 |
-
### Last 7 Days
|
| 197 |
-
| Metric | Count |
|
| 198 |
-
|--------|-------|
|
| 199 |
-
| π’ Generations | {stats['recent_generations']} |
|
| 200 |
-
| π Positive | {stats['recent_positive']} |
|
| 201 |
-
| π Negative | {stats['recent_negative']} |
|
| 202 |
-
| π Approval Rate | {stats['approval_rate']:.1f}% |
|
| 203 |
-
"""
|
| 204 |
-
|
| 205 |
-
def get_recent_interactions():
|
| 206 |
-
"""Get recent interactions for review"""
|
| 207 |
-
interactions = db.get_recent_interactions(limit=10)
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
|
|
|
|
|
|
| 211 |
|
| 212 |
-
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
md += f"""### {item['timestamp']}
|
| 217 |
-
**Prompt:** `{item['prompt'][:50]}...`
|
| 218 |
-
**Feedback:** {feedback}
|
| 219 |
-
|
| 220 |
-
---
|
| 221 |
-
"""
|
| 222 |
|
| 223 |
-
|
|
|
|
| 224 |
|
| 225 |
-
def
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
if not history:
|
| 230 |
-
return "No training history yet."
|
| 231 |
-
|
| 232 |
-
md = "## Training History\n\n"
|
| 233 |
-
md += "| Date | Version | Samples | Loss | Accuracy |\n"
|
| 234 |
-
md += "|------|---------|---------|------|----------|\n"
|
| 235 |
-
|
| 236 |
-
for item in history:
|
| 237 |
-
md += f"| {item['timestamp'][:10]} | {item['model_version']} | "
|
| 238 |
-
md += f"{item['samples_used']} | {item['final_loss']:.4f} | {item['final_accuracy']:.4f} |\n"
|
| 239 |
-
|
| 240 |
-
return md
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
config = trainer.model.get_config()
|
| 248 |
-
params = trainer.model.count_params()
|
| 249 |
-
|
| 250 |
-
return f"""## ποΈ Veda Programming LLM
|
| 251 |
-
|
| 252 |
-
### Architecture
|
| 253 |
-
|
| 254 |
-
| Property | Value |
|
| 255 |
-
|----------|-------|
|
| 256 |
-
| π Vocabulary Size | {config['vocab_size']:,} |
|
| 257 |
-
| π Max Sequence Length | {config['max_length']} |
|
| 258 |
-
| π§ Model Dimension | {config['d_model']} |
|
| 259 |
-
| ποΈ Attention Heads | {config['num_heads']} |
|
| 260 |
-
| π¦ Transformer Layers | {config['num_layers']} |
|
| 261 |
-
| π§ FFN Dimension | {config['ff_dim']} |
|
| 262 |
-
| β‘ **Total Parameters** | **{params:,}** |
|
| 263 |
-
|
| 264 |
-
### Features
|
| 265 |
-
- β
Continuous Learning from User Feedback
|
| 266 |
-
- β
Automatic Retraining
|
| 267 |
-
- β
Repetition Penalty
|
| 268 |
-
- β
Top-K & Top-P Sampling
|
| 269 |
-
- β
Temperature Control
|
| 270 |
-
- β
Model Versioning
|
| 271 |
"""
|
| 272 |
|
| 273 |
-
# Create
|
| 274 |
def create_app():
|
| 275 |
-
with gr.Blocks(
|
| 276 |
-
title="Veda Programming LLM",
|
| 277 |
-
theme=gr.themes.Soft(),
|
| 278 |
-
css="""
|
| 279 |
-
.feedback-btn { min-width: 100px; }
|
| 280 |
-
.positive { background-color: #4CAF50 !important; }
|
| 281 |
-
.negative { background-color: #f44336 !important; }
|
| 282 |
-
"""
|
| 283 |
-
) as app:
|
| 284 |
-
|
| 285 |
-
# Hidden state for interaction tracking
|
| 286 |
-
interaction_id = gr.State(value=-1)
|
| 287 |
|
| 288 |
gr.Markdown("""
|
| 289 |
-
# ποΈ Veda Programming
|
| 290 |
-
### AI Code Generation with Continuous Learning
|
| 291 |
|
| 292 |
-
|
| 293 |
""")
|
| 294 |
|
| 295 |
with gr.Tabs():
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
| 298 |
with gr.Row():
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
with gr.Row():
|
| 308 |
-
max_tokens = gr.Slider(
|
| 309 |
-
10, 300, value=DEFAULT_MAX_TOKENS,
|
| 310 |
-
step=10, label="π Max Tokens"
|
| 311 |
-
)
|
| 312 |
-
temperature = gr.Slider(
|
| 313 |
-
0.1, 1.5, value=DEFAULT_TEMPERATURE,
|
| 314 |
-
step=0.1, label="π‘οΈ Temperature"
|
| 315 |
-
)
|
| 316 |
-
|
| 317 |
-
with gr.Row():
|
| 318 |
-
repetition_penalty = gr.Slider(
|
| 319 |
-
1.0, 2.0, value=DEFAULT_REPETITION_PENALTY,
|
| 320 |
-
step=0.1, label="π Repetition Penalty"
|
| 321 |
-
)
|
| 322 |
-
top_k = gr.Slider(
|
| 323 |
-
10, 100, value=DEFAULT_TOP_K,
|
| 324 |
-
step=5, label="π― Top-K"
|
| 325 |
-
)
|
| 326 |
-
|
| 327 |
-
gen_btn = gr.Button("π Generate Code", variant="primary", size="lg")
|
| 328 |
-
|
| 329 |
-
with gr.Column(scale=1):
|
| 330 |
-
output = gr.Code(
|
| 331 |
-
label="π Generated Code (Edit if needed before rating)",
|
| 332 |
-
language="python",
|
| 333 |
-
lines=15,
|
| 334 |
-
interactive=True
|
| 335 |
-
)
|
| 336 |
-
|
| 337 |
-
gr.Markdown("### π Rate this output to help improve the model:")
|
| 338 |
-
|
| 339 |
-
with gr.Row():
|
| 340 |
-
good_btn = gr.Button("π Good", variant="primary", elem_classes=["feedback-btn", "positive"])
|
| 341 |
-
bad_btn = gr.Button("π Bad", variant="secondary", elem_classes=["feedback-btn", "negative"])
|
| 342 |
-
|
| 343 |
-
feedback_output = gr.Textbox(label="Feedback Status", lines=2)
|
| 344 |
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
inputs=[prompt, max_tokens, temperature, repetition_penalty, top_k],
|
| 349 |
-
outputs=[output, interaction_id]
|
| 350 |
-
)
|
| 351 |
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
outputs=feedback_output
|
| 357 |
-
)
|
| 358 |
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
)
|
|
|
|
|
|
|
|
|
|
| 364 |
|
| 365 |
-
|
| 366 |
-
gr.Markdown("### π‘ Example Prompts")
|
| 367 |
gr.Examples(
|
| 368 |
examples=[
|
| 369 |
-
["
|
| 370 |
-
["
|
| 371 |
-
["
|
| 372 |
-
["
|
|
|
|
|
|
|
|
|
|
| 373 |
],
|
| 374 |
-
inputs=
|
| 375 |
)
|
| 376 |
|
| 377 |
-
#
|
| 378 |
with gr.TabItem("π Training"):
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
train_epochs = gr.Slider(1, 20, value=5, step=1, label="Epochs")
|
| 385 |
-
train_btn = gr.Button("π― Start Training", variant="primary")
|
| 386 |
-
train_output = gr.Textbox(label="Training Output", lines=8)
|
| 387 |
-
|
| 388 |
-
train_btn.click(manual_train, inputs=[train_epochs], outputs=train_output)
|
| 389 |
-
|
| 390 |
-
with gr.Column():
|
| 391 |
-
gr.Markdown("### π Add Training Code")
|
| 392 |
-
gr.Markdown("Contribute code directly to the training dataset.")
|
| 393 |
-
|
| 394 |
-
code_input = gr.Textbox(
|
| 395 |
-
label="Code",
|
| 396 |
-
placeholder="Paste your Python code here...",
|
| 397 |
-
lines=10
|
| 398 |
-
)
|
| 399 |
-
|
| 400 |
-
category = gr.Dropdown(
|
| 401 |
-
choices=["function", "class", "algorithm", "utility", "other"],
|
| 402 |
-
value="function",
|
| 403 |
-
label="Category"
|
| 404 |
-
)
|
| 405 |
-
|
| 406 |
-
add_btn = gr.Button("β Add to Training Data")
|
| 407 |
-
add_output = gr.Textbox(label="Status")
|
| 408 |
-
|
| 409 |
-
add_btn.click(add_training_code, inputs=[code_input, category], outputs=add_output)
|
| 410 |
|
| 411 |
-
#
|
| 412 |
-
with gr.TabItem("π
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
gr.Markdown("---")
|
| 418 |
-
|
| 419 |
-
with gr.Row():
|
| 420 |
-
with gr.Column():
|
| 421 |
-
interactions_output = gr.Markdown()
|
| 422 |
-
refresh_interactions = gr.Button("π Refresh Interactions")
|
| 423 |
-
refresh_interactions.click(get_recent_interactions, outputs=interactions_output)
|
| 424 |
-
|
| 425 |
-
with gr.Column():
|
| 426 |
-
history_output = gr.Markdown()
|
| 427 |
-
refresh_history = gr.Button("π Refresh History")
|
| 428 |
-
refresh_history.click(get_training_history, outputs=history_output)
|
| 429 |
-
|
| 430 |
-
# ============ Model Info Tab ============
|
| 431 |
-
with gr.TabItem("βΉοΈ Model Info"):
|
| 432 |
-
info_output = gr.Markdown()
|
| 433 |
-
refresh_info = gr.Button("π Refresh Info")
|
| 434 |
-
refresh_info.click(get_model_info, outputs=info_output)
|
| 435 |
-
|
| 436 |
-
gr.Markdown("""
|
| 437 |
-
### π§ How Continuous Learning Works
|
| 438 |
-
|
| 439 |
-
1. **You generate code** using the model
|
| 440 |
-
2. **You rate the output** (π or π)
|
| 441 |
-
3. **Good outputs are saved** for training
|
| 442 |
-
4. **When enough samples collect**, the model retrains
|
| 443 |
-
5. **The model improves** based on your feedback!
|
| 444 |
-
|
| 445 |
-
### π‘ Tips
|
| 446 |
-
|
| 447 |
-
- Rate outputs honestly to help the model learn
|
| 448 |
-
- Edit code before rating if it's close but not perfect
|
| 449 |
-
- The more you use it, the better it gets!
|
| 450 |
-
- Contribute your own code samples for faster learning
|
| 451 |
-
""")
|
| 452 |
|
| 453 |
-
gr.Markdown(""
|
| 454 |
-
---
|
| 455 |
-
**ποΈ Veda Programming LLM** | Continuous Learning System |
|
| 456 |
-
Built with TensorFlow & Gradio
|
| 457 |
-
""")
|
| 458 |
|
| 459 |
return app
|
| 460 |
|
| 461 |
-
# Main
|
| 462 |
if __name__ == "__main__":
|
| 463 |
initialize()
|
| 464 |
-
|
| 465 |
-
print("\nπ Starting Gradio Interface...")
|
| 466 |
app = create_app()
|
| 467 |
-
app.launch(
|
| 468 |
-
server_name="0.0.0.0",
|
| 469 |
-
server_port=7860,
|
| 470 |
-
show_error=True
|
| 471 |
-
)
|
|
|
|
| 1 |
+
"""Gradio App - REPLACED with chat interface"""
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
+
import tensorflow as tf
|
| 5 |
import os
|
| 6 |
import json
|
|
|
|
| 7 |
|
| 8 |
from model import VedaProgrammingLLM
|
| 9 |
from tokenizer import VedaTokenizer
|
|
|
|
|
|
|
| 10 |
from database import db
|
| 11 |
+
from train import VedaTrainer
|
| 12 |
+
from config import MODEL_DIR
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Global state
|
| 15 |
+
model = None
|
| 16 |
+
tokenizer = None
|
| 17 |
+
conversation_history = []
|
| 18 |
+
current_conv_id = -1
|
| 19 |
|
| 20 |
def initialize():
|
| 21 |
+
"""Initialize the assistant"""
|
| 22 |
+
global model, tokenizer
|
|
|
|
| 23 |
|
| 24 |
+
print("ποΈ Initializing Veda Programming Assistant...")
|
| 25 |
+
|
| 26 |
+
config_path = os.path.join(MODEL_DIR, "config.json")
|
| 27 |
+
|
| 28 |
+
if os.path.exists(config_path):
|
| 29 |
+
print("Loading existing model...")
|
| 30 |
+
|
| 31 |
+
with open(config_path, 'r') as f:
|
| 32 |
+
config = json.load(f)
|
| 33 |
+
|
| 34 |
+
tokenizer = VedaTokenizer()
|
| 35 |
+
tokenizer.load(os.path.join(MODEL_DIR, "tokenizer.json"))
|
| 36 |
+
|
| 37 |
+
model = VedaProgrammingLLM(
|
| 38 |
+
vocab_size=config['vocab_size'],
|
| 39 |
+
max_length=config['max_length'],
|
| 40 |
+
d_model=config['d_model'],
|
| 41 |
+
num_heads=config['num_heads'],
|
| 42 |
+
num_layers=config['num_layers'],
|
| 43 |
+
ff_dim=config['ff_dim']
|
| 44 |
)
|
|
|
|
| 45 |
|
| 46 |
+
dummy = tf.zeros((1, config['max_length']), dtype=tf.int32)
|
| 47 |
+
model(dummy)
|
| 48 |
+
model.load_weights(os.path.join(MODEL_DIR, "weights.h5"))
|
| 49 |
+
|
| 50 |
+
print("β
Model loaded!")
|
| 51 |
+
else:
|
| 52 |
+
print("Training new model (this takes a few minutes)...")
|
| 53 |
+
trainer = VedaTrainer()
|
| 54 |
+
trainer.train(epochs=15)
|
| 55 |
+
model = trainer.model
|
| 56 |
+
tokenizer = trainer.tokenizer
|
| 57 |
+
print("β
Model trained!")
|
| 58 |
+
|
| 59 |
+
def clean_response(text: str) -> str:
|
| 60 |
+
"""Clean the response"""
|
| 61 |
+
# Handle code blocks
|
| 62 |
+
text = text.replace("<CODE>", "\n```python\n")
|
| 63 |
+
text = text.replace("<ENDCODE>", "\n```\n")
|
| 64 |
|
| 65 |
+
# Remove special tokens
|
| 66 |
+
for token in ["<PAD>", "<UNK>", "<START>", "<END>", "<USER>", "<ASSISTANT>"]:
|
| 67 |
+
text = text.replace(token, "")
|
| 68 |
|
| 69 |
+
# Clean whitespace
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
lines = text.split('\n')
|
| 71 |
cleaned = []
|
| 72 |
empty_count = 0
|
|
|
|
| 80 |
empty_count = 0
|
| 81 |
cleaned.append(line)
|
| 82 |
|
| 83 |
+
return '\n'.join(cleaned).strip()
|
| 84 |
|
| 85 |
+
def generate_response(user_input: str, temperature: float = 0.7,
|
| 86 |
+
max_tokens: int = 200) -> str:
|
| 87 |
+
"""Generate a response"""
|
| 88 |
+
global current_conv_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
if model is None:
|
| 91 |
+
return "β³ Model is loading..."
|
| 92 |
+
|
| 93 |
+
if not user_input.strip():
|
| 94 |
+
return "Please type a message!"
|
| 95 |
|
| 96 |
try:
|
| 97 |
+
# Build context from history (last 3 exchanges)
|
| 98 |
+
context = ""
|
| 99 |
+
for msg in conversation_history[-3:]:
|
| 100 |
+
context += f"<USER> {msg['user']}\n<ASSISTANT> {msg['assistant']}\n"
|
| 101 |
|
| 102 |
+
# Add current input
|
| 103 |
+
prompt = context + f"<USER> {user_input}\n<ASSISTANT>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Encode
|
| 106 |
+
tokens = tokenizer.encode(prompt)
|
| 107 |
|
| 108 |
+
# Truncate if too long
|
| 109 |
+
if len(tokens) > model.max_length - max_tokens:
|
| 110 |
+
tokens = tokens[-(model.max_length - max_tokens):]
|
| 111 |
+
|
| 112 |
+
# Generate
|
| 113 |
+
generated = model.generate(
|
| 114 |
+
tokens,
|
| 115 |
+
max_new_tokens=max_tokens,
|
| 116 |
temperature=temperature,
|
| 117 |
+
top_k=50,
|
| 118 |
+
top_p=0.9,
|
| 119 |
+
repetition_penalty=1.2
|
| 120 |
)
|
| 121 |
|
| 122 |
+
# Decode
|
| 123 |
+
response = tokenizer.decode(generated)
|
| 124 |
+
|
| 125 |
+
# Extract assistant's response
|
| 126 |
+
if "<ASSISTANT>" in response:
|
| 127 |
+
parts = response.split("<ASSISTANT>")
|
| 128 |
+
response = parts[-1].strip()
|
| 129 |
+
|
| 130 |
+
if "<USER>" in response:
|
| 131 |
+
response = response.split("<USER>")[0].strip()
|
| 132 |
+
|
| 133 |
+
response = clean_response(response)
|
| 134 |
+
|
| 135 |
+
# Save to history
|
| 136 |
+
conversation_history.append({
|
| 137 |
+
'user': user_input,
|
| 138 |
+
'assistant': response
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
# Save to database
|
| 142 |
+
current_conv_id = db.save_conversation(user_input, response)
|
| 143 |
+
|
| 144 |
+
return response
|
| 145 |
|
| 146 |
except Exception as e:
|
| 147 |
import traceback
|
| 148 |
traceback.print_exc()
|
| 149 |
+
return f"β Error: {str(e)}"
|
| 150 |
|
| 151 |
+
def chat(user_input, history, temperature, max_tokens):
|
| 152 |
+
"""Chat function for Gradio"""
|
| 153 |
+
response = generate_response(user_input, temperature, max_tokens)
|
| 154 |
+
history.append((user_input, response))
|
| 155 |
+
return "", history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
def feedback_good():
|
| 158 |
+
if current_conv_id > 0:
|
| 159 |
+
db.update_feedback(current_conv_id, 1)
|
| 160 |
+
return "π Thanks! This helps me improve."
|
| 161 |
+
return ""
|
| 162 |
|
| 163 |
+
def feedback_bad():
|
| 164 |
+
if current_conv_id > 0:
|
| 165 |
+
db.update_feedback(current_conv_id, -1)
|
| 166 |
+
return "π Thanks for the feedback. I'll try to do better."
|
| 167 |
+
return ""
|
| 168 |
|
| 169 |
+
def clear_conversation():
|
| 170 |
+
global conversation_history
|
| 171 |
+
conversation_history = []
|
| 172 |
+
return [], ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
+
def retrain(epochs):
|
| 175 |
+
"""Retrain with good conversations"""
|
| 176 |
+
global model, tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
good_convs = db.get_good_conversations()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
+
if not good_convs:
|
| 181 |
+
return "No approved conversations yet. Rate some responses first!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
extra_data = ""
|
| 184 |
+
for conv in good_convs:
|
| 185 |
+
extra_data += f"<USER> {conv['user_input']}\n"
|
| 186 |
+
extra_data += f"<ASSISTANT> {conv['assistant_response']}\n\n"
|
| 187 |
|
| 188 |
+
trainer = VedaTrainer()
|
| 189 |
+
history = trainer.train(epochs=int(epochs), extra_data=extra_data)
|
| 190 |
|
| 191 |
+
model = trainer.model
|
| 192 |
+
tokenizer = trainer.tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
loss = history.history['loss'][-1]
|
| 195 |
+
return f"β
Training done! Loss: {loss:.4f}, Used {len(good_convs)} conversations"
|
| 196 |
|
| 197 |
+
def get_stats():
|
| 198 |
+
stats = db.get_stats()
|
| 199 |
+
return f"""## π Statistics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
| Metric | Count |
|
| 202 |
+
|--------|-------|
|
| 203 |
+
| π¬ Conversations | {stats['total']} |
|
| 204 |
+
| π Positive | {stats['positive']} |
|
| 205 |
+
| π Negative | {stats['negative']} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
"""
|
| 207 |
|
| 208 |
+
# Create interface
|
| 209 |
def create_app():
|
| 210 |
+
with gr.Blocks(title="Veda Programming Assistant", theme=gr.themes.Soft()) as app:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
gr.Markdown("""
|
| 213 |
+
# ποΈ Veda Programming Assistant
|
|
|
|
| 214 |
|
| 215 |
+
I can **chat**, **write code**, **explain concepts**, and **answer questions**!
|
| 216 |
""")
|
| 217 |
|
| 218 |
with gr.Tabs():
|
| 219 |
+
|
| 220 |
+
# Chat Tab
|
| 221 |
+
with gr.TabItem("π¬ Chat"):
|
| 222 |
+
chatbot = gr.Chatbot(label="Conversation", height=400)
|
| 223 |
+
|
| 224 |
with gr.Row():
|
| 225 |
+
msg = gr.Textbox(
|
| 226 |
+
label="Your message",
|
| 227 |
+
placeholder="Ask me anything about programming...",
|
| 228 |
+
lines=2,
|
| 229 |
+
scale=4
|
| 230 |
+
)
|
| 231 |
+
send_btn = gr.Button("Send π€", variant="primary", scale=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
with gr.Row():
|
| 234 |
+
temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Creativity")
|
| 235 |
+
max_tokens = gr.Slider(50, 400, value=200, step=50, label="Response length")
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
with gr.Row():
|
| 238 |
+
good_btn = gr.Button("π Good", variant="secondary")
|
| 239 |
+
bad_btn = gr.Button("π Bad", variant="secondary")
|
| 240 |
+
clear_btn = gr.Button("ποΈ Clear", variant="secondary")
|
|
|
|
|
|
|
| 241 |
|
| 242 |
+
feedback_msg = gr.Textbox(label="", lines=1)
|
| 243 |
+
|
| 244 |
+
# Events
|
| 245 |
+
send_btn.click(chat, [msg, chatbot, temperature, max_tokens], [msg, chatbot])
|
| 246 |
+
msg.submit(chat, [msg, chatbot, temperature, max_tokens], [msg, chatbot])
|
| 247 |
+
good_btn.click(feedback_good, outputs=feedback_msg)
|
| 248 |
+
bad_btn.click(feedback_bad, outputs=feedback_msg)
|
| 249 |
+
clear_btn.click(clear_conversation, outputs=[chatbot, feedback_msg])
|
| 250 |
|
| 251 |
+
gr.Markdown("### π‘ Try these:")
|
|
|
|
| 252 |
gr.Examples(
|
| 253 |
examples=[
|
| 254 |
+
["Hello! What can you do?"],
|
| 255 |
+
["What is Python?"],
|
| 256 |
+
["Write a function to calculate factorial"],
|
| 257 |
+
["Explain what recursion is"],
|
| 258 |
+
["How do I read a file in Python?"],
|
| 259 |
+
["Write a bubble sort algorithm"],
|
| 260 |
+
["What's the difference between list and tuple?"],
|
| 261 |
],
|
| 262 |
+
inputs=msg
|
| 263 |
)
|
| 264 |
|
| 265 |
+
# Training Tab
|
| 266 |
with gr.TabItem("π Training"):
|
| 267 |
+
gr.Markdown("### Train on your approved conversations")
|
| 268 |
+
train_epochs = gr.Slider(5, 20, value=10, step=1, label="Epochs")
|
| 269 |
+
train_btn = gr.Button("π Retrain", variant="primary")
|
| 270 |
+
train_output = gr.Markdown()
|
| 271 |
+
train_btn.click(retrain, [train_epochs], train_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
+
# Stats Tab
|
| 274 |
+
with gr.TabItem("π Stats"):
|
| 275 |
+
stats_out = gr.Markdown()
|
| 276 |
+
refresh_btn = gr.Button("π Refresh")
|
| 277 |
+
refresh_btn.click(get_stats, outputs=stats_out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
+
gr.Markdown("---\n**Veda Programming Assistant** | Learning from every conversation!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
return app
|
| 282 |
|
| 283 |
+
# Main
|
| 284 |
if __name__ == "__main__":
|
| 285 |
initialize()
|
| 286 |
+
print("\nπ Starting...")
|
|
|
|
| 287 |
app = create_app()
|
| 288 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|