vedaco commited on
Commit
108c40e
Β·
verified Β·
1 Parent(s): ed6fa70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -387
app.py CHANGED
@@ -1,54 +1,72 @@
1
- """Gradio interface for Veda Programming LLM with continuous learning"""
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, SAMPLE_CODE
14
- from config import (
15
- MODEL_DIR, DEFAULT_TEMPERATURE, DEFAULT_MAX_TOKENS,
16
- DEFAULT_REPETITION_PENALTY, DEFAULT_TOP_K
17
- )
18
 
19
- # Current interaction tracking
20
- current_interaction_id = None
 
 
 
21
 
22
  def initialize():
23
- """Initialize the system"""
24
- print("πŸ•‰οΈ Initializing Veda Programming LLM...")
25
- print("=" * 50)
26
 
27
- # Try to load existing model
28
- if trainer.load_model():
29
- print("βœ… Existing model loaded")
30
- else:
31
- print("πŸ“š Training initial model...")
32
- # Initial training
33
- initial_trainer = VedaTrainer(
34
- data_path="programming.txt",
35
- vocab_size=5000,
36
- max_length=256,
37
- batch_size=8
 
 
 
 
 
 
 
 
 
38
  )
39
- initial_trainer.train(epochs=10, save_path=MODEL_DIR)
40
 
41
- # Load the trained model into continuous trainer
42
- trainer.load_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # Start auto-training scheduler
45
- trainer.start_auto_training()
 
46
 
47
- print("=" * 50)
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 generate_code(
68
- prompt: str,
69
- max_tokens: int,
70
- temperature: float,
71
- repetition_penalty: float,
72
- top_k: int
73
- ) -> tuple:
74
- """Generate code and track interaction"""
75
- global current_interaction_id
76
 
77
- if trainer.model is None:
78
- return "⏳ Model loading...", -1
 
 
 
79
 
80
  try:
81
- if not prompt.strip():
82
- return "⚠️ Please enter a prompt.", -1
 
 
83
 
84
- # Generate
85
- result = trainer.generate(
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
- result = clean_output(result)
 
94
 
95
- # Save interaction
96
- current_interaction_id = collector.collect_interaction(
97
- prompt=prompt,
98
- generated_code=result,
 
 
 
 
99
  temperature=temperature,
100
- max_tokens=max_tokens
 
 
101
  )
102
 
103
- return result, current_interaction_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  except Exception as e:
106
  import traceback
107
  traceback.print_exc()
108
- return f"❌ Error: {str(e)}", -1
109
 
110
- def submit_feedback(interaction_id: int, is_positive: bool, edited_code: str = None):
111
- """Submit feedback for generated code"""
112
- if interaction_id < 0:
113
- return "⚠️ No interaction to rate"
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 positive_feedback(interaction_id, code):
133
- return submit_feedback(int(interaction_id), True, code)
 
 
 
134
 
135
- def negative_feedback(interaction_id, code):
136
- return submit_feedback(int(interaction_id), False, code)
 
 
 
137
 
138
- def manual_train(epochs: int):
139
- """Manually trigger training"""
140
- if trainer.is_training:
141
- return "⏳ Training already in progress..."
142
-
143
- result = trainer.train(epochs=int(epochs))
144
-
145
- if result['status'] == 'success':
146
- return f"""βœ… Training Complete!
147
 
148
- πŸ“Š Results:
149
- - Version: {result['version']}
150
- - Loss: {result['loss']:.4f}
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
- collector.add_training_sample(code, category)
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
- return f"""## πŸ“Š System Statistics
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
- if not interactions:
210
- return "No interactions yet."
 
 
211
 
212
- md = "## Recent Interactions\n\n"
 
213
 
214
- for item in interactions:
215
- feedback = "πŸ‘" if item['feedback'] > 0 else ("πŸ‘Ž" if item['feedback'] < 0 else "⏳")
216
- md += f"""### {item['timestamp']}
217
- **Prompt:** `{item['prompt'][:50]}...`
218
- **Feedback:** {feedback}
219
-
220
- ---
221
- """
222
 
223
- return md
 
224
 
225
- def get_training_history():
226
- """Get training history"""
227
- history = db.get_training_history(limit=10)
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
- def get_model_info():
243
- """Get model architecture info"""
244
- if trainer.model is None:
245
- return "⏳ Model not loaded"
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 the interface
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 LLM
290
- ### AI Code Generation with Continuous Learning
291
 
292
- This model learns from your feedback! Rate generated code to help improve it.
293
  """)
294
 
295
  with gr.Tabs():
296
- # ============ Generation Tab ============
297
- with gr.TabItem("πŸ’» Generate Code"):
 
 
 
298
  with gr.Row():
299
- with gr.Column(scale=1):
300
- prompt = gr.Textbox(
301
- label="πŸ“ Code Prompt",
302
- placeholder="Enter your code prompt...",
303
- lines=4,
304
- value="def fibonacci(n):"
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
- # Wire up generation
346
- gen_btn.click(
347
- generate_code,
348
- inputs=[prompt, max_tokens, temperature, repetition_penalty, top_k],
349
- outputs=[output, interaction_id]
350
- )
351
 
352
- # Wire up feedback
353
- good_btn.click(
354
- positive_feedback,
355
- inputs=[interaction_id, output],
356
- outputs=feedback_output
357
- )
358
 
359
- bad_btn.click(
360
- negative_feedback,
361
- inputs=[interaction_id, output],
362
- outputs=feedback_output
363
- )
 
 
 
364
 
365
- # Examples
366
- gr.Markdown("### πŸ’‘ Example Prompts")
367
  gr.Examples(
368
  examples=[
369
- ["def fibonacci(n):", 100, 0.7, 1.2, 50],
370
- ["def bubble_sort(arr):", 120, 0.7, 1.2, 50],
371
- ["class Calculator:", 150, 0.8, 1.3, 40],
372
- ["def binary_search(arr, target):", 100, 0.7, 1.2, 50],
 
 
 
373
  ],
374
- inputs=[prompt, max_tokens, temperature, repetition_penalty, top_k]
375
  )
376
 
377
- # ============ Training Tab ============
378
  with gr.TabItem("πŸŽ“ Training"):
379
- with gr.Row():
380
- with gr.Column():
381
- gr.Markdown("### πŸ”„ Manual Training")
382
- gr.Markdown("Trigger training on collected approved samples.")
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
- # ============ Statistics Tab ============
412
- with gr.TabItem("πŸ“Š Statistics"):
413
- stats_output = gr.Markdown()
414
- refresh_stats = gr.Button("πŸ”„ Refresh Statistics")
415
- refresh_stats.click(get_statistics, outputs=stats_output)
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 execution
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)