Update app.py
Browse files
app.py
CHANGED
|
@@ -4,95 +4,292 @@ import os
|
|
| 4 |
import base64
|
| 5 |
from PIL import Image
|
| 6 |
import io
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
if image is None:
|
| 12 |
# Text-only query
|
| 13 |
-
|
| 14 |
else:
|
| 15 |
# Image + text query
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
def ask_llm(message):
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
"
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
def ask_llm_with_image(message, image):
|
|
|
|
| 35 |
# Convert image to base64
|
| 36 |
buffered = io.BytesIO()
|
| 37 |
image.save(buffered, format="PNG")
|
| 38 |
img_base64 = base64.b64encode(buffered.getvalue()).decode()
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
"
|
|
|
|
|
|
|
| 60 |
}
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
# Gradio Interface
|
| 72 |
-
with gr.Blocks() as ui:
|
| 73 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
with gr.Row():
|
| 76 |
-
with gr.Column():
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
with gr.Column():
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
#
|
| 85 |
submit_btn.click(
|
| 86 |
fn=process_input,
|
| 87 |
-
inputs=[text_input, image_input],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
outputs=output
|
| 89 |
)
|
| 90 |
|
| 91 |
-
# Also allow pressing Enter in textbox to submit
|
| 92 |
text_input.submit(
|
| 93 |
fn=process_input,
|
| 94 |
-
inputs=[text_input, image_input],
|
| 95 |
outputs=output
|
| 96 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
|
|
|
|
|
|
| 4 |
import base64
|
| 5 |
from PIL import Image
|
| 6 |
import io
|
| 7 |
+
import datetime
|
| 8 |
+
import resend
|
| 9 |
|
| 10 |
+
# Configuration from environment variables
|
| 11 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 12 |
+
REPORT_EMAIL = os.getenv("REPORT_EMAIL")
|
| 13 |
+
RESEND_API_KEY = os.getenv("RESEND_API_KEY")
|
| 14 |
|
| 15 |
+
# Initialize Resend
|
| 16 |
+
resend.api_key = RESEND_API_KEY
|
| 17 |
+
|
| 18 |
+
# Store conversation history
|
| 19 |
+
conversation_history = []
|
| 20 |
+
|
| 21 |
+
def send_email_report(conversation_data):
|
| 22 |
+
"""Send conversation report directly via Resend"""
|
| 23 |
+
if not RESEND_API_KEY or not REPORT_EMAIL:
|
| 24 |
+
return "Email reporting not configured - missing Resend API key or report email"
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
# Format email content
|
| 28 |
+
subject = f"Chat Conversation Report - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
|
| 29 |
+
|
| 30 |
+
# Create HTML email content
|
| 31 |
+
html_content = f"""
|
| 32 |
+
<html>
|
| 33 |
+
<head>
|
| 34 |
+
<style>
|
| 35 |
+
body {{ font-family: Arial, sans-serif; margin: 20px; }}
|
| 36 |
+
.header {{ background-color: #f4f4f4; padding: 20px; border-radius: 8px; margin-bottom: 20px; }}
|
| 37 |
+
.exchange {{ border: 1px solid #e0e0e0; margin: 15px 0; padding: 15px; border-radius: 8px; background-color: #fafafa; }}
|
| 38 |
+
.user {{ color: #2563eb; font-weight: 600; }}
|
| 39 |
+
.ai {{ color: #059669; }}
|
| 40 |
+
.timestamp {{ color: #6b7280; font-size: 0.8em; font-style: italic; }}
|
| 41 |
+
.image-info {{ background-color: #fef3c7; padding: 5px 10px; border-radius: 4px; display: inline-block; margin: 5px 0; }}
|
| 42 |
+
</style>
|
| 43 |
+
</head>
|
| 44 |
+
<body>
|
| 45 |
+
<div class="header">
|
| 46 |
+
<h1 style="margin: 0; color: #1f2937;">π€ Chat Conversation Report</h1>
|
| 47 |
+
<p style="margin: 5px 0;"><strong>Date:</strong> {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
|
| 48 |
+
<p style="margin: 5px 0;"><strong>Total Exchanges:</strong> {len(conversation_data)}</p>
|
| 49 |
+
</div>
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
for i, entry in enumerate(conversation_data, 1):
|
| 53 |
+
html_content += f"""
|
| 54 |
+
<div class="exchange">
|
| 55 |
+
<h3 style="margin-top: 0; color: #374151;">Exchange #{i}</h3>
|
| 56 |
+
<p class="user"><strong>π€ User:</strong> {entry['user_input']}</p>
|
| 57 |
+
{f"<p class='image-info'>π· Image: {entry.get('image_filename', 'Uploaded image')}</p>" if entry.get('image_uploaded') else ""}
|
| 58 |
+
<p class="ai"><strong>π€ AI:</strong> {entry['ai_response']}</p>
|
| 59 |
+
<p class="timestamp">{entry['timestamp']}</p>
|
| 60 |
+
</div>
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
html_content += "</body></html>"
|
| 64 |
+
|
| 65 |
+
# Send email directly using Resend
|
| 66 |
+
params = {
|
| 67 |
+
"from": "Chat App <onboarding@resend.dev>",
|
| 68 |
+
"to": [REPORT_EMAIL],
|
| 69 |
+
"subject": subject,
|
| 70 |
+
"html": html_content,
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
email = resend.Emails.send(params)
|
| 74 |
+
|
| 75 |
+
return f"π§ Report sent successfully to {REPORT_EMAIL}"
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return f"Failed to send email: {str(e)}"
|
| 79 |
+
|
| 80 |
+
def add_to_conversation_history(user_input, image, ai_response):
|
| 81 |
+
"""Add current exchange to conversation history"""
|
| 82 |
+
image_filename = getattr(image, 'filename', 'uploaded_image') if image else None
|
| 83 |
+
|
| 84 |
+
entry = {
|
| 85 |
+
'timestamp': datetime.datetime.now().isoformat(),
|
| 86 |
+
'user_input': user_input,
|
| 87 |
+
'image_uploaded': image is not None,
|
| 88 |
+
'image_filename': image_filename,
|
| 89 |
+
'ai_response': ai_response
|
| 90 |
+
}
|
| 91 |
+
conversation_history.append(entry)
|
| 92 |
+
|
| 93 |
+
# Keep only last 50 exchanges to prevent memory issues
|
| 94 |
+
if len(conversation_history) > 50:
|
| 95 |
+
conversation_history.pop(0)
|
| 96 |
+
|
| 97 |
+
def process_input(message, image, send_report=False):
|
| 98 |
+
if not message.strip():
|
| 99 |
+
return "Please enter a message."
|
| 100 |
+
|
| 101 |
if image is None:
|
| 102 |
# Text-only query
|
| 103 |
+
ai_response = ask_llm(message)
|
| 104 |
else:
|
| 105 |
# Image + text query
|
| 106 |
+
ai_response = ask_llm_with_image(message, image)
|
| 107 |
+
|
| 108 |
+
# Add to conversation history
|
| 109 |
+
add_to_conversation_history(message, image, ai_response)
|
| 110 |
+
|
| 111 |
+
# Send email report if requested
|
| 112 |
+
if send_report and conversation_history:
|
| 113 |
+
email_status = send_email_report(conversation_history)
|
| 114 |
+
return f"{ai_response}\n\n---\nπ§ Email Status: {email_status}"
|
| 115 |
+
|
| 116 |
+
return ai_response
|
| 117 |
|
| 118 |
def ask_llm(message):
|
| 119 |
+
"""Text-only query to OpenRouter"""
|
| 120 |
+
try:
|
| 121 |
+
response = requests.post(
|
| 122 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 123 |
+
headers={
|
| 124 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 125 |
+
"Content-Type": "application/json",
|
| 126 |
+
},
|
| 127 |
+
json={
|
| 128 |
+
"model": "google/gemma-3-27b-it:free",
|
| 129 |
+
"messages": [{"role": "user", "content": message}]
|
| 130 |
+
},
|
| 131 |
+
timeout=30
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
if response.status_code == 200:
|
| 135 |
+
data = response.json()
|
| 136 |
+
return data["choices"][0]["message"]["content"]
|
| 137 |
+
else:
|
| 138 |
+
return f"API Error: {response.status_code} - {response.text}"
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
return f"Error: {str(e)}"
|
| 142 |
|
| 143 |
def ask_llm_with_image(message, image):
|
| 144 |
+
"""Image + text query to OpenRouter"""
|
| 145 |
# Convert image to base64
|
| 146 |
buffered = io.BytesIO()
|
| 147 |
image.save(buffered, format="PNG")
|
| 148 |
img_base64 = base64.b64encode(buffered.getvalue()).decode()
|
| 149 |
|
| 150 |
+
try:
|
| 151 |
+
response = requests.post(
|
| 152 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 153 |
+
headers={
|
| 154 |
+
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
| 155 |
+
"Content-Type": "application/json",
|
| 156 |
+
},
|
| 157 |
+
json={
|
| 158 |
+
"model": "google/gemini-flash-1.5:free", # Vision model
|
| 159 |
+
"messages": [
|
| 160 |
+
{
|
| 161 |
+
"role": "user",
|
| 162 |
+
"content": [
|
| 163 |
+
{
|
| 164 |
+
"type": "text",
|
| 165 |
+
"text": message
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"type": "image_url",
|
| 169 |
+
"image_url": {
|
| 170 |
+
"url": f"data:image/png;base64,{img_base64}"
|
| 171 |
+
}
|
| 172 |
}
|
| 173 |
+
]
|
| 174 |
+
}
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
timeout=30
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
if response.status_code == 200:
|
| 181 |
+
data = response.json()
|
| 182 |
+
return data["choices"][0]["message"]["content"]
|
| 183 |
+
else:
|
| 184 |
+
return f"API Error: {response.status_code} - {response.text}"
|
| 185 |
+
|
| 186 |
+
except Exception as e:
|
| 187 |
+
return f"Error processing image: {str(e)}"
|
| 188 |
|
| 189 |
+
def clear_conversation():
|
| 190 |
+
"""Clear the conversation history"""
|
| 191 |
+
global conversation_history
|
| 192 |
+
conversation_history = []
|
| 193 |
+
return "Conversation history cleared!"
|
| 194 |
+
|
| 195 |
+
def get_conversation_stats():
|
| 196 |
+
"""Get statistics about current conversation"""
|
| 197 |
+
if not conversation_history:
|
| 198 |
+
return "No conversations yet"
|
| 199 |
+
|
| 200 |
+
total_exchanges = len(conversation_history)
|
| 201 |
+
image_uploads = sum(1 for entry in conversation_history if entry['image_uploaded'])
|
| 202 |
+
last_time = conversation_history[-1]['timestamp'] if conversation_history else "N/A"
|
| 203 |
+
|
| 204 |
+
return f"Exchanges: {total_exchanges} | Images: {image_uploads} | Last: {last_time}"
|
| 205 |
|
| 206 |
+
# Gradio Interface
|
| 207 |
+
with gr.Blocks(theme=gr.themes.Soft()) as ui:
|
| 208 |
+
gr.Markdown("""
|
| 209 |
+
# π€ OpenRouter Chat with Email Reports
|
| 210 |
+
*Powered by OpenRouter API + Resend Email*
|
| 211 |
+
""")
|
| 212 |
|
| 213 |
with gr.Row():
|
| 214 |
+
with gr.Column(scale=1):
|
| 215 |
+
gr.Markdown("### π¬ Chat Input")
|
| 216 |
+
text_input = gr.Textbox(
|
| 217 |
+
label="Your message:",
|
| 218 |
+
lines=3,
|
| 219 |
+
placeholder="Type your message here...",
|
| 220 |
+
max_lines=5
|
| 221 |
+
)
|
| 222 |
+
image_input = gr.Image(
|
| 223 |
+
label="π· Upload an image (optional)",
|
| 224 |
+
type="pil",
|
| 225 |
+
height=200
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
with gr.Row():
|
| 229 |
+
submit_btn = gr.Button("π Submit", variant="primary", size="lg")
|
| 230 |
+
report_btn = gr.Button("π§ Submit & Email Report", variant="secondary")
|
| 231 |
+
|
| 232 |
+
with gr.Row():
|
| 233 |
+
clear_btn = gr.Button("ποΈ Clear History", variant="stop")
|
| 234 |
+
stats_btn = gr.Button("π Get Stats")
|
| 235 |
+
|
| 236 |
+
status_display = gr.Textbox(
|
| 237 |
+
label="Status",
|
| 238 |
+
interactive=False,
|
| 239 |
+
max_lines=2
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
stats_display = gr.Textbox(
|
| 243 |
+
label="Conversation Statistics",
|
| 244 |
+
interactive=False,
|
| 245 |
+
max_lines=2
|
| 246 |
+
)
|
| 247 |
|
| 248 |
+
with gr.Column(scale=2):
|
| 249 |
+
gr.Markdown("### π€ AI Response")
|
| 250 |
+
output = gr.Textbox(
|
| 251 |
+
label="Response",
|
| 252 |
+
lines=12,
|
| 253 |
+
show_copy_button=True
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
with gr.Accordion("π Conversation History (Last 10)", open=False):
|
| 257 |
+
history_display = gr.JSON(
|
| 258 |
+
label="Recent History",
|
| 259 |
+
value=conversation_history[-10:] if conversation_history else [],
|
| 260 |
+
every=2
|
| 261 |
+
)
|
| 262 |
|
| 263 |
+
# Event handlers
|
| 264 |
submit_btn.click(
|
| 265 |
fn=process_input,
|
| 266 |
+
inputs=[text_input, image_input, gr.Checkbox(value=False, visible=False)],
|
| 267 |
+
outputs=output
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
report_btn.click(
|
| 271 |
+
fn=process_input,
|
| 272 |
+
inputs=[text_input, image_input, gr.Checkbox(value=True, visible=False)],
|
| 273 |
outputs=output
|
| 274 |
)
|
| 275 |
|
|
|
|
| 276 |
text_input.submit(
|
| 277 |
fn=process_input,
|
| 278 |
+
inputs=[text_input, image_input, gr.Checkbox(value=False, visible=False)],
|
| 279 |
outputs=output
|
| 280 |
)
|
| 281 |
+
|
| 282 |
+
clear_btn.click(
|
| 283 |
+
fn=clear_conversation,
|
| 284 |
+
inputs=[],
|
| 285 |
+
outputs=status_display
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
stats_btn.click(
|
| 289 |
+
fn=get_conversation_stats,
|
| 290 |
+
inputs=[],
|
| 291 |
+
outputs=stats_display
|
| 292 |
+
)
|
| 293 |
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
ui.launch(share=False)
|