Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Gradio App
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
import tensorflow as tf
|
|
@@ -11,17 +11,18 @@ from database import db
|
|
| 11 |
from train import VedaTrainer
|
| 12 |
from config import MODEL_DIR
|
| 13 |
|
| 14 |
-
|
| 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("
|
| 25 |
|
| 26 |
config_path = os.path.join(MODEL_DIR, "config.json")
|
| 27 |
|
|
@@ -47,26 +48,24 @@ def initialize():
|
|
| 47 |
model(dummy)
|
| 48 |
model.load_weights(os.path.join(MODEL_DIR, "weights.h5"))
|
| 49 |
|
| 50 |
-
print("
|
| 51 |
else:
|
| 52 |
-
print("Training new model
|
| 53 |
trainer = VedaTrainer()
|
| 54 |
trainer.train(epochs=15)
|
| 55 |
model = trainer.model
|
| 56 |
tokenizer = trainer.tokenizer
|
| 57 |
-
print("
|
|
|
|
| 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
|
|
@@ -82,34 +81,29 @@ def clean_response(text: str) -> str:
|
|
| 82 |
|
| 83 |
return '\n'.join(cleaned).strip()
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
"""Generate a response"""
|
| 88 |
global current_conv_id
|
| 89 |
|
| 90 |
if model is None:
|
| 91 |
-
return "
|
| 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,
|
|
@@ -119,10 +113,8 @@ def generate_response(user_input: str, temperature: float = 0.7,
|
|
| 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()
|
|
@@ -132,13 +124,11 @@ def generate_response(user_input: str, temperature: float = 0.7,
|
|
| 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
|
|
@@ -146,30 +136,38 @@ def generate_response(user_input: str, temperature: float = 0.7,
|
|
| 146 |
except Exception as e:
|
| 147 |
import traceback
|
| 148 |
traceback.print_exc()
|
| 149 |
-
return f"
|
|
|
|
| 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
|
| 155 |
return "", history
|
| 156 |
|
|
|
|
| 157 |
def feedback_good():
|
| 158 |
if current_conv_id > 0:
|
| 159 |
db.update_feedback(current_conv_id, 1)
|
| 160 |
-
return "
|
| 161 |
-
return ""
|
|
|
|
| 162 |
|
| 163 |
def feedback_bad():
|
| 164 |
if current_conv_id > 0:
|
| 165 |
db.update_feedback(current_conv_id, -1)
|
| 166 |
-
return "
|
| 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"""
|
|
@@ -192,97 +190,150 @@ def retrain(epochs):
|
|
| 192 |
tokenizer = trainer.tokenizer
|
| 193 |
|
| 194 |
loss = history.history['loss'][-1]
|
| 195 |
-
return f"
|
|
|
|
| 196 |
|
| 197 |
def get_stats():
|
| 198 |
stats = db.get_stats()
|
| 199 |
-
return f"""##
|
| 200 |
|
| 201 |
| Metric | Count |
|
| 202 |
|--------|-------|
|
| 203 |
-
|
|
| 204 |
-
|
|
| 205 |
-
|
|
| 206 |
"""
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
-
with gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
-
|
| 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 |
-
|
|
|
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
bad_btn.click(feedback_bad, outputs=feedback_msg)
|
| 249 |
-
clear_btn.click(clear_conversation, outputs=[chatbot, feedback_msg])
|
| 250 |
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 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 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
-
#
|
| 284 |
if __name__ == "__main__":
|
| 285 |
-
|
| 286 |
-
print("\n🚀 Starting...")
|
| 287 |
-
app = create_app()
|
| 288 |
-
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
"""Gradio App for Veda Programming Assistant - Gradio 6.2.0"""
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
import tensorflow as tf
|
|
|
|
| 11 |
from train import VedaTrainer
|
| 12 |
from config import MODEL_DIR
|
| 13 |
|
| 14 |
+
|
| 15 |
model = None
|
| 16 |
tokenizer = None
|
| 17 |
conversation_history = []
|
| 18 |
current_conv_id = -1
|
| 19 |
|
| 20 |
+
|
| 21 |
def initialize():
|
| 22 |
"""Initialize the assistant"""
|
| 23 |
global model, tokenizer
|
| 24 |
|
| 25 |
+
print("Initializing Veda Programming Assistant...")
|
| 26 |
|
| 27 |
config_path = os.path.join(MODEL_DIR, "config.json")
|
| 28 |
|
|
|
|
| 48 |
model(dummy)
|
| 49 |
model.load_weights(os.path.join(MODEL_DIR, "weights.h5"))
|
| 50 |
|
| 51 |
+
print("Model loaded!")
|
| 52 |
else:
|
| 53 |
+
print("Training new model...")
|
| 54 |
trainer = VedaTrainer()
|
| 55 |
trainer.train(epochs=15)
|
| 56 |
model = trainer.model
|
| 57 |
tokenizer = trainer.tokenizer
|
| 58 |
+
print("Model trained!")
|
| 59 |
+
|
| 60 |
|
| 61 |
def clean_response(text: str) -> str:
|
| 62 |
"""Clean the response"""
|
|
|
|
| 63 |
text = text.replace("<CODE>", "\n```python\n")
|
| 64 |
text = text.replace("<ENDCODE>", "\n```\n")
|
| 65 |
|
|
|
|
| 66 |
for token in ["<PAD>", "<UNK>", "<START>", "<END>", "<USER>", "<ASSISTANT>"]:
|
| 67 |
text = text.replace(token, "")
|
| 68 |
|
|
|
|
| 69 |
lines = text.split('\n')
|
| 70 |
cleaned = []
|
| 71 |
empty_count = 0
|
|
|
|
| 81 |
|
| 82 |
return '\n'.join(cleaned).strip()
|
| 83 |
|
| 84 |
+
|
| 85 |
+
def generate_response(user_input: str, temperature: float = 0.7, max_tokens: int = 200) -> str:
|
| 86 |
"""Generate a response"""
|
| 87 |
global current_conv_id
|
| 88 |
|
| 89 |
if model is None:
|
| 90 |
+
return "Model is loading, please wait..."
|
| 91 |
|
| 92 |
if not user_input.strip():
|
| 93 |
return "Please type a message!"
|
| 94 |
|
| 95 |
try:
|
|
|
|
| 96 |
context = ""
|
| 97 |
for msg in conversation_history[-3:]:
|
| 98 |
context += f"<USER> {msg['user']}\n<ASSISTANT> {msg['assistant']}\n"
|
| 99 |
|
|
|
|
| 100 |
prompt = context + f"<USER> {user_input}\n<ASSISTANT>"
|
| 101 |
|
|
|
|
| 102 |
tokens = tokenizer.encode(prompt)
|
| 103 |
|
|
|
|
| 104 |
if len(tokens) > model.max_length - max_tokens:
|
| 105 |
tokens = tokens[-(model.max_length - max_tokens):]
|
| 106 |
|
|
|
|
| 107 |
generated = model.generate(
|
| 108 |
tokens,
|
| 109 |
max_new_tokens=max_tokens,
|
|
|
|
| 113 |
repetition_penalty=1.2
|
| 114 |
)
|
| 115 |
|
|
|
|
| 116 |
response = tokenizer.decode(generated)
|
| 117 |
|
|
|
|
| 118 |
if "<ASSISTANT>" in response:
|
| 119 |
parts = response.split("<ASSISTANT>")
|
| 120 |
response = parts[-1].strip()
|
|
|
|
| 124 |
|
| 125 |
response = clean_response(response)
|
| 126 |
|
|
|
|
| 127 |
conversation_history.append({
|
| 128 |
'user': user_input,
|
| 129 |
'assistant': response
|
| 130 |
})
|
| 131 |
|
|
|
|
| 132 |
current_conv_id = db.save_conversation(user_input, response)
|
| 133 |
|
| 134 |
return response
|
|
|
|
| 136 |
except Exception as e:
|
| 137 |
import traceback
|
| 138 |
traceback.print_exc()
|
| 139 |
+
return f"Error: {str(e)}"
|
| 140 |
+
|
| 141 |
|
| 142 |
def chat(user_input, history, temperature, max_tokens):
|
| 143 |
"""Chat function for Gradio"""
|
| 144 |
+
if not user_input.strip():
|
| 145 |
+
return "", history
|
| 146 |
+
|
| 147 |
response = generate_response(user_input, temperature, max_tokens)
|
| 148 |
+
history = history + [[user_input, response]]
|
| 149 |
return "", history
|
| 150 |
|
| 151 |
+
|
| 152 |
def feedback_good():
|
| 153 |
if current_conv_id > 0:
|
| 154 |
db.update_feedback(current_conv_id, 1)
|
| 155 |
+
return "Thanks for the positive feedback!"
|
| 156 |
+
return "No conversation to rate yet."
|
| 157 |
+
|
| 158 |
|
| 159 |
def feedback_bad():
|
| 160 |
if current_conv_id > 0:
|
| 161 |
db.update_feedback(current_conv_id, -1)
|
| 162 |
+
return "Thanks for the feedback. I will try to improve."
|
| 163 |
+
return "No conversation to rate yet."
|
| 164 |
+
|
| 165 |
|
| 166 |
def clear_conversation():
|
| 167 |
global conversation_history
|
| 168 |
conversation_history = []
|
| 169 |
+
return [], "Conversation cleared."
|
| 170 |
+
|
| 171 |
|
| 172 |
def retrain(epochs):
|
| 173 |
"""Retrain with good conversations"""
|
|
|
|
| 190 |
tokenizer = trainer.tokenizer
|
| 191 |
|
| 192 |
loss = history.history['loss'][-1]
|
| 193 |
+
return f"Training done! Loss: {loss:.4f}, Used {len(good_convs)} conversations"
|
| 194 |
+
|
| 195 |
|
| 196 |
def get_stats():
|
| 197 |
stats = db.get_stats()
|
| 198 |
+
return f"""## Statistics
|
| 199 |
|
| 200 |
| Metric | Count |
|
| 201 |
|--------|-------|
|
| 202 |
+
| Conversations | {stats['total']} |
|
| 203 |
+
| Positive | {stats['positive']} |
|
| 204 |
+
| Negative | {stats['negative']} |
|
| 205 |
"""
|
| 206 |
|
| 207 |
+
|
| 208 |
+
# Initialize model
|
| 209 |
+
print("Starting initialization...")
|
| 210 |
+
initialize()
|
| 211 |
+
print("Initialization complete!")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
# Create Gradio interface
|
| 215 |
+
with gr.Blocks(title="Veda Programming Assistant", theme=gr.themes.Soft()) as demo:
|
| 216 |
+
|
| 217 |
+
gr.Markdown("""
|
| 218 |
+
# Veda Programming Assistant
|
| 219 |
+
|
| 220 |
+
I can chat, write code, explain concepts, and answer programming questions!
|
| 221 |
+
""")
|
| 222 |
+
|
| 223 |
+
with gr.Tabs():
|
| 224 |
|
| 225 |
+
with gr.TabItem("Chat"):
|
| 226 |
+
chatbot = gr.Chatbot(
|
| 227 |
+
label="Conversation",
|
| 228 |
+
height=400,
|
| 229 |
+
type="messages"
|
| 230 |
+
)
|
| 231 |
|
| 232 |
+
with gr.Row():
|
| 233 |
+
msg = gr.Textbox(
|
| 234 |
+
label="Your message",
|
| 235 |
+
placeholder="Ask me anything about programming...",
|
| 236 |
+
lines=2,
|
| 237 |
+
scale=4
|
| 238 |
+
)
|
| 239 |
+
send_btn = gr.Button("Send", variant="primary", scale=1)
|
| 240 |
+
|
| 241 |
+
with gr.Row():
|
| 242 |
+
temperature = gr.Slider(
|
| 243 |
+
minimum=0.1,
|
| 244 |
+
maximum=1.5,
|
| 245 |
+
value=0.7,
|
| 246 |
+
step=0.1,
|
| 247 |
+
label="Creativity"
|
| 248 |
+
)
|
| 249 |
+
max_tokens = gr.Slider(
|
| 250 |
+
minimum=50,
|
| 251 |
+
maximum=400,
|
| 252 |
+
value=200,
|
| 253 |
+
step=50,
|
| 254 |
+
label="Response length"
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
with gr.Row():
|
| 258 |
+
good_btn = gr.Button("Good Response", variant="secondary")
|
| 259 |
+
bad_btn = gr.Button("Bad Response", variant="secondary")
|
| 260 |
+
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
| 261 |
+
|
| 262 |
+
feedback_msg = gr.Textbox(label="Status", lines=1, interactive=False)
|
| 263 |
+
|
| 264 |
+
# Updated chat function for new Gradio format
|
| 265 |
+
def chat_fn(user_input, history, temperature, max_tokens):
|
| 266 |
+
if not user_input.strip():
|
| 267 |
+
return "", history
|
| 268 |
|
| 269 |
+
response = generate_response(user_input, temperature, max_tokens)
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
+
if history is None:
|
| 272 |
+
history = []
|
| 273 |
|
| 274 |
+
history = history + [
|
| 275 |
+
{"role": "user", "content": user_input},
|
| 276 |
+
{"role": "assistant", "content": response}
|
| 277 |
+
]
|
|
|
|
|
|
|
| 278 |
|
| 279 |
+
return "", history
|
| 280 |
+
|
| 281 |
+
send_btn.click(
|
| 282 |
+
chat_fn,
|
| 283 |
+
inputs=[msg, chatbot, temperature, max_tokens],
|
| 284 |
+
outputs=[msg, chatbot]
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
msg.submit(
|
| 288 |
+
chat_fn,
|
| 289 |
+
inputs=[msg, chatbot, temperature, max_tokens],
|
| 290 |
+
outputs=[msg, chatbot]
|
| 291 |
+
)
|
| 292 |
|
| 293 |
+
good_btn.click(feedback_good, outputs=feedback_msg)
|
| 294 |
+
bad_btn.click(feedback_bad, outputs=feedback_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
+
def clear_fn():
|
| 297 |
+
global conversation_history
|
| 298 |
+
conversation_history = []
|
| 299 |
+
return [], "Conversation cleared."
|
| 300 |
+
|
| 301 |
+
clear_btn.click(clear_fn, outputs=[chatbot, feedback_msg])
|
| 302 |
+
|
| 303 |
+
gr.Markdown("### Examples")
|
| 304 |
+
gr.Examples(
|
| 305 |
+
examples=[
|
| 306 |
+
"Hello! What can you do?",
|
| 307 |
+
"What is Python?",
|
| 308 |
+
"Write a function to calculate factorial",
|
| 309 |
+
"Explain what recursion is",
|
| 310 |
+
"How do I read a file in Python?",
|
| 311 |
+
"Write a bubble sort algorithm",
|
| 312 |
+
],
|
| 313 |
+
inputs=msg
|
| 314 |
+
)
|
| 315 |
|
| 316 |
+
with gr.TabItem("Training"):
|
| 317 |
+
gr.Markdown("### Train on approved conversations")
|
| 318 |
+
train_epochs = gr.Slider(
|
| 319 |
+
minimum=5,
|
| 320 |
+
maximum=20,
|
| 321 |
+
value=10,
|
| 322 |
+
step=1,
|
| 323 |
+
label="Epochs"
|
| 324 |
+
)
|
| 325 |
+
train_btn = gr.Button("Retrain Model", variant="primary")
|
| 326 |
+
train_output = gr.Markdown()
|
| 327 |
+
train_btn.click(retrain, inputs=[train_epochs], outputs=train_output)
|
| 328 |
+
|
| 329 |
+
with gr.TabItem("Statistics"):
|
| 330 |
+
stats_out = gr.Markdown()
|
| 331 |
+
refresh_btn = gr.Button("Refresh Statistics")
|
| 332 |
+
refresh_btn.click(get_stats, outputs=stats_out)
|
| 333 |
|
| 334 |
+
gr.Markdown("---\nVeda Programming Assistant - Learning from conversations!")
|
| 335 |
+
|
| 336 |
|
| 337 |
+
# Launch the app
|
| 338 |
if __name__ == "__main__":
|
| 339 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|