RockyBai commited on
Commit
78bff30
·
verified ·
1 Parent(s): 0558908

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +130 -68
api.py CHANGED
@@ -298,12 +298,93 @@ import requests
298
  from email.mime.text import MIMEText
299
  from email.mime.multipart import MIMEMultipart
300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  # --- BREVO (HTTP) CONFIG ---
302
  # HARDCODE YOUR KEY HERE AS REQUESTED
303
  BREVO_API_KEY = "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" # <--- PASTE YOUR KEY HERE INSIDE QUOTES
304
 
305
- def send_email_via_brevo(to_email: str, subject: str, body: str, is_html: bool = True):
306
- """Sends email via Brevo HTTP API (Bypasses SMTP ports)."""
307
  if not BREVO_API_KEY or "xkeysib" not in BREVO_API_KEY:
308
  logger.warning("BREVO_API_KEY not set or invalid. Skipping HTTP email.")
309
  return False
@@ -322,6 +403,11 @@ def send_email_via_brevo(to_email: str, subject: str, body: str, is_html: bool =
322
  "htmlContent": body if is_html else f"<p>{body}</p>"
323
  }
324
 
 
 
 
 
 
325
  try:
326
  response = requests.post(url, json=payload, headers=headers, timeout=10)
327
  if response.status_code in [200, 201, 202]:
@@ -334,11 +420,11 @@ def send_email_via_brevo(to_email: str, subject: str, body: str, is_html: bool =
334
  logger.error(f"Brevo Request Failed: {e}")
335
  return False
336
 
337
- def send_email_helper(to_email: str, subject: str, body: str, is_html: bool = False):
338
  """Sends an email using Brevo (HTTP) first, falls back to Gmail SMTP."""
339
 
340
  # 1. Try Brevo (HTTP) - Preferred for HF Spaces
341
- if send_email_via_brevo(to_email, subject, body, is_html):
342
  return True
343
 
344
  # 2. Fallback to SMTP (Gmail)
@@ -395,65 +481,23 @@ async def notify_status_endpoint(req: NotifyStatusRequest, background_tasks: Bac
395
  """
396
  subject = f"Arise Update: {req.issue_type} - {req.status.capitalize()}"
397
 
398
- # Status Colors
399
- color_map = {
400
- "approved": "#10b981", # Green
401
- "resolved": "#10b981", # Green
402
- "rejected": "#ef4444", # Red
403
- "inProgress": "#3b82f6", # Blue
404
- "pending": "#eab308" # Yellow
405
  }
406
- status_color = color_map.get(req.status, "#6b7280")
407
 
408
- # Construct HTML Body
409
- html_body = f"""
410
- <html>
411
- <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
412
- <div style="text-align: center; margin-bottom: 20px;">
413
- <h2 style="color: #2563eb;">Arise Civic Report Update</h2>
414
- </div>
415
-
416
- <div style="background-color: #f9fafb; border-radius: 8px; padding: 20px; border: 1px solid #e5e7eb;">
417
- <div style="margin-bottom: 20px; text-align: center;">
418
- <span style="background-color: {status_color}; color: white; padding: 8px 16px; border-radius: 20px; font-weight: bold; text-transform: uppercase; font-size: 14px;">
419
- {req.status}
420
- </span>
421
- </div>
422
-
423
- <p>Hello,</p>
424
- <p>Your report has been updated. Here are the latest details:</p>
425
-
426
- <table style="width: 100%; margin-bottom: 20px; border-collapse: collapse;">
427
- <tr>
428
- <td style="padding: 8px; border-bottom: 1px solid #eee; color: #666;"><strong>Issue Type:</strong></td>
429
- <td style="padding: 8px; border-bottom: 1px solid #eee;">{req.issue_type}</td>
430
- </tr>
431
- <tr>
432
- <td style="padding: 8px; border-bottom: 1px solid #eee; color: #666;"><strong>Department:</strong></td>
433
- <td style="padding: 8px; border-bottom: 1px solid #eee;">{req.department}</td>
434
- </tr>
435
- <tr>
436
- <td style="padding: 8px; border-bottom: 1px solid #eee; color: #666;"><strong>Severity:</strong></td>
437
- <td style="padding: 8px; border-bottom: 1px solid #eee;">{req.severity}</td>
438
- </tr>
439
- <tr>
440
- <td style="padding: 8px; border-bottom: 1px solid #eee; color: #666;"><strong>Location:</strong></td>
441
- <td style="padding: 8px; border-bottom: 1px solid #eee;">{req.location or "Provided"}</td>
442
- </tr>
443
- </table>
444
-
445
- {f'<div style="text-align: center; margin: 20px 0;"><img src="{req.imageUrl}" style="max-width: 100%; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" alt="Report Image"></div>' if req.imageUrl else ''}
446
-
447
- <p style="margin-top: 20px;">
448
- Thank you for contributing to a better community.
449
- </p>
450
- <p style="font-size: 12px; color: #999; text-align: center; margin-top: 30px;">
451
- Sent via Arise AI System
452
- </p>
453
- </div>
454
- </body>
455
- </html>
456
- """
457
 
458
  background_tasks.add_task(send_email_helper, req.user_email, subject, html_body, True)
459
  return {"status": "success", "message": "Notification queued"}
@@ -673,18 +717,36 @@ async def analyze_endpoint(
673
  if max_conf > 0.8:
674
  # Auto-Approve -> Send to Dept
675
  auto_status = "inProgress"
676
- subject = f"Auto-Approved: High Confidence {primary_issue} Detected"
677
- body = f"A new report has been auto-approved (Confidence: {int(max_conf*100)}%).\nIssue: {primary_issue}\nLocation: {lat}, {lon}\nDepartment: {department}\n\nPlease verify and resolve."
 
 
 
 
 
 
 
 
 
678
 
679
  logger.info("Queuing email to admin (Auto-Approve)...")
680
- background_tasks.add_task(send_email_helper, "rockybai8234@gmail.com", subject, body)
681
  else:
682
  # Pending -> Send to Admin
683
- subject = f"New Report Pending Review: {primary_issue}"
684
- body = f"A new report requires manual review (Confidence: {int(max_conf*100)}%).\nIssue: {primary_issue}\n\nPlease check the admin dashboard."
 
 
 
 
 
 
 
 
 
685
 
686
  logger.info("Queuing email to admin (Pending Review)...")
687
- background_tasks.add_task(send_email_helper, "shivarajmani2005@gmail.com", subject, body)
688
 
689
  response_data = {
690
  "status": "Success",
@@ -728,4 +790,4 @@ async def analyze_endpoint(
728
  raise HTTPException(status_code=500, detail=str(e))
729
 
730
  if __name__ == "__main__":
731
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
298
  from email.mime.text import MIMEText
299
  from email.mime.multipart import MIMEMultipart
300
 
301
+ # --- EMAIL TEMPLATE GENERATOR ---
302
+ def generate_html_email(title: str, status: str, details: dict, image_url: str = None):
303
+ """
304
+ Generates a standardized, branded HTML email for Arise.
305
+ """
306
+ # Status Colors
307
+ color_map = {
308
+ "approved": "#10b981", # Green
309
+ "resolved": "#10b981", # Green
310
+ "rejected": "#ef4444", # Red
311
+ "inprogress": "#3b82f6", # Blue
312
+ "pending": "#eab308", # Yellow
313
+ "auto-approved": "#8b5cf6" # Violet for Auto
314
+ }
315
+ status_key = status.lower().replace(" ", "")
316
+ status_color = color_map.get(status_key, "#6b7280")
317
+
318
+ # Build Details Table
319
+ rows = ""
320
+ for key, value in details.items():
321
+ rows += f"""
322
+ <tr>
323
+ <td style="padding: 12px; border-bottom: 1px solid #eee; color: #666; width: 40%;"><strong>{key}:</strong></td>
324
+ <td style="padding: 12px; border-bottom: 1px solid #eee; color: #333;">{value}</td>
325
+ </tr>
326
+ """
327
+
328
+ # Image Section (If URL provided, show it. If attachment only, the client shows attachment)
329
+ # Since we are attaching the image file directly in Brevo/SMTP, we might not need an <img> tag pointing to a URL
330
+ # unless we have a public URL.
331
+ # For now, we'll strip the inline image if no URL is passed (we rely on attachment).
332
+ image_html = ""
333
+ if image_url and image_url.startswith("http"):
334
+ image_html = f'<div style="text-align: center; margin: 20px 0;"><img src="{image_url}" style="max-width: 100%; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" alt="Report Image"></div>'
335
+
336
+ html_body = f"""
337
+ <html>
338
+ <body style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 0; background-color: #f4f4f5;">
339
+ <div style="background-color: #ffffff; border-radius: 12px; margin: 20px auto; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
340
+
341
+ <!-- Header -->
342
+ <div style="background-color: #2563eb; padding: 24px; text-align: center;">
343
+ <h1 style="color: #ffffff; margin: 0; font-size: 24px;">{title}</h1>
344
+ </div>
345
+
346
+ <div style="padding: 32px;">
347
+ <!-- Status Badge -->
348
+ <div style="margin-bottom: 24px; text-align: center;">
349
+ <span style="background-color: {status_color}; color: white; padding: 8px 16px; border-radius: 20px; font-weight: bold; text-transform: uppercase; font-size: 14px; letter-spacing: 1px;">
350
+ {status}
351
+ </span>
352
+ </div>
353
+
354
+ <p style="font-size: 16px; margin-bottom: 24px;">Hello,</p>
355
+ <p style="font-size: 16px; margin-bottom: 24px;">Here are the latest details regarding the report:</p>
356
+
357
+ <table style="width: 100%; margin-bottom: 24px; border-collapse: collapse; background-color: #f8fafc; border-radius: 8px; overflow: hidden;">
358
+ {rows}
359
+ </table>
360
+
361
+ {image_html}
362
+
363
+ <p style="margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px;">
364
+ Thank you for contributing to a safer community.
365
+ </p>
366
+
367
+ <div style="margin-top: 16px; font-weight: bold; color: #2563eb;">
368
+ Team Arise
369
+ </div>
370
+ </div>
371
+
372
+ <!-- Footer -->
373
+ <div style="background-color: #f1f5f9; padding: 16px; text-align: center; font-size: 12px; color: #94a3b8;">
374
+ &copy; {datetime.now().year} Arise Civic AI. All rights reserved.
375
+ </div>
376
+ </div>
377
+ </body>
378
+ </html>
379
+ """
380
+ return html_body
381
+
382
  # --- BREVO (HTTP) CONFIG ---
383
  # HARDCODE YOUR KEY HERE AS REQUESTED
384
  BREVO_API_KEY = "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" # <--- PASTE YOUR KEY HERE INSIDE QUOTES
385
 
386
+ def send_email_via_brevo(to_email: str, subject: str, body: str, is_html: bool = True, attachment_base64: str = None):
387
+ """Sends email via Brevo HTTP API (Bypasses SMTP ports). Includes optional Base64 attachment."""
388
  if not BREVO_API_KEY or "xkeysib" not in BREVO_API_KEY:
389
  logger.warning("BREVO_API_KEY not set or invalid. Skipping HTTP email.")
390
  return False
 
403
  "htmlContent": body if is_html else f"<p>{body}</p>"
404
  }
405
 
406
+ if attachment_base64:
407
+ # Brevo expects: {"content": "BASE64...", "name": "filename.ext"}
408
+ payload["attachment"] = [{"content": attachment_base64, "name": "report_image.jpg"}]
409
+
410
+
411
  try:
412
  response = requests.post(url, json=payload, headers=headers, timeout=10)
413
  if response.status_code in [200, 201, 202]:
 
420
  logger.error(f"Brevo Request Failed: {e}")
421
  return False
422
 
423
+ def send_email_helper(to_email: str, subject: str, body: str, is_html: bool = False, attachment_base64: str = None):
424
  """Sends an email using Brevo (HTTP) first, falls back to Gmail SMTP."""
425
 
426
  # 1. Try Brevo (HTTP) - Preferred for HF Spaces
427
+ if send_email_via_brevo(to_email, subject, body, is_html, attachment_base64):
428
  return True
429
 
430
  # 2. Fallback to SMTP (Gmail)
 
481
  """
482
  subject = f"Arise Update: {req.issue_type} - {req.status.capitalize()}"
483
 
484
+ details = {
485
+ "Issue Type": req.issue_type,
486
+ "Department": req.department,
487
+ "Severity": req.severity,
488
+ "Location": req.location or "Provided",
489
+ "Status Description": f"Your report has been marked as {req.status}. We will keep you updated."
 
490
  }
 
491
 
492
+ html_body = generate_html_email(
493
+ "Civic Report Update",
494
+ req.status,
495
+ details,
496
+ req.imageUrl
497
+ )
498
+
499
+ # If imageUrl is base64, we could parse it, but usually standard URLs are passed here from Cloudinary/etc.
500
+ # If the frontend passes a base64 string in imageUrl, we might want to handle it (but typically it's a URL).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
 
502
  background_tasks.add_task(send_email_helper, req.user_email, subject, html_body, True)
503
  return {"status": "success", "message": "Notification queued"}
 
717
  if max_conf > 0.8:
718
  # Auto-Approve -> Send to Dept
719
  auto_status = "inProgress"
720
+ subject = f"Auto-Approved: High Confidence {primary_issue}"
721
+
722
+ details = {
723
+ "Issue Type": primary_issue,
724
+ "Confidence": f"{int(max_conf*100)}%",
725
+ "Department": department,
726
+ "Location": f"{lat}, {lon}",
727
+ "Action": "Auto-Approved by AI"
728
+ }
729
+
730
+ html_body = generate_html_email("New Priority Report", "Auto-Approved", details)
731
 
732
  logger.info("Queuing email to admin (Auto-Approve)...")
733
+ background_tasks.add_task(send_email_helper, "rockybai8234@gmail.com", subject, html_body, True, processed_image_base64)
734
  else:
735
  # Pending -> Send to Admin
736
+ subject = f"Pending Review: {primary_issue}"
737
+
738
+ details = {
739
+ "Issue Type": primary_issue,
740
+ "Confidence": f"{int(max_conf*100)}%",
741
+ "Department": department,
742
+ "Location": f"{lat}, {lon}",
743
+ "Action": "Waiting for Admin Verification"
744
+ }
745
+
746
+ html_body = generate_html_email("New Report Received", "Pending Review", details)
747
 
748
  logger.info("Queuing email to admin (Pending Review)...")
749
+ background_tasks.add_task(send_email_helper, "shivarajmani2005@gmail.com", subject, html_body, True, processed_image_base64)
750
 
751
  response_data = {
752
  "status": "Success",
 
790
  raise HTTPException(status_code=500, detail=str(e))
791
 
792
  if __name__ == "__main__":
793
+ uvicorn.run(app, host="0.0.0.0", port=7860)