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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import re
|
| 5 |
+
import requests
|
| 6 |
+
import phonenumbers
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import urllib.parse
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from transformers import (
|
| 13 |
+
AutoTokenizer,
|
| 14 |
+
AutoModelForTokenClassification,
|
| 15 |
+
AutoModelForSeq2SeqLM,
|
| 16 |
+
pipeline
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
import gradio as gr
|
| 20 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 21 |
+
from email.message import EmailMessage
|
| 22 |
+
import smtplib
|
| 23 |
+
from email.mime.multipart import MIMEMultipart
|
| 24 |
+
from email.mime.text import MIMEText
|
| 25 |
+
|
| 26 |
+
# ============================
|
| 27 |
+
# CONFIG (ENV VARS recommended)
|
| 28 |
+
# ============================
|
| 29 |
+
# IMPORTANT: set these as Space "Secrets" (see README below)
|
| 30 |
+
API_KEY = os.environ.get("GOOGLE_API_KEY", "YOUR_GOOGLE_API_KEY")
|
| 31 |
+
CX = os.environ.get("GOOGLE_CSE_ID", "YOUR_CSE_ID")
|
| 32 |
+
DEFAULT_COUNTRY = "Ghana"
|
| 33 |
+
|
| 34 |
+
RESULTS_PER_QUERY = int(os.environ.get("RESULTS_PER_QUERY", 4))
|
| 35 |
+
MAX_SCRAPE_WORKERS = int(os.environ.get("MAX_SCRAPE_WORKERS", 6))
|
| 36 |
+
|
| 37 |
+
ALLY_AI_NAME = os.environ.get("ALLY_AI_NAME", "Ally AI Assistant")
|
| 38 |
+
ALLY_AI_LOGO_URL_DEFAULT = os.environ.get("ALLY_AI_LOGO_URL",
|
| 39 |
+
"https://i.ibb.co/7nZqz0H/ai-logo.png")
|
| 40 |
+
|
| 41 |
+
# Optional country maps for search bias & phone parsing
|
| 42 |
+
COUNTRY_TLD_MAP = {"Ghana":"gh","Nigeria":"ng","Kenya":"ke","South Africa":"za","USA":"us","United Kingdom":"uk"}
|
| 43 |
+
COUNTRY_REGION_MAP= {"Ghana":"GH","Nigeria":"NG","Kenya":"KE","South Africa":"ZA","USA":"US","United Kingdom":"GB"}
|
| 44 |
+
|
| 45 |
+
# HTTP + Regex
|
| 46 |
+
HEADERS = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64)"}
|
| 47 |
+
EMAIL_REGEX = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
|
| 48 |
+
|
| 49 |
+
# ============================
|
| 50 |
+
# MODELS (lightweight & CPU-friendly)
|
| 51 |
+
# ============================
|
| 52 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 53 |
+
print("Device set to use", DEVICE)
|
| 54 |
+
|
| 55 |
+
# NER model (people/orgs/locs)
|
| 56 |
+
ner_model_id = "dslim/bert-base-NER"
|
| 57 |
+
ner_tokenizer = AutoTokenizer.from_pretrained(ner_model_id)
|
| 58 |
+
ner_model = AutoModelForTokenClassification.from_pretrained(ner_model_id)
|
| 59 |
+
ner_pipe = pipeline("ner", model=ner_model, tokenizer=ner_tokenizer, aggregation_strategy="simple",
|
| 60 |
+
device=0 if DEVICE=="cuda" else -1)
|
| 61 |
+
|
| 62 |
+
# Summarizer / anonymizer
|
| 63 |
+
text_model_id = "google/flan-t5-large"
|
| 64 |
+
text_tokenizer = AutoTokenizer.from_pretrained(text_model_id)
|
| 65 |
+
text_model = AutoModelForSeq2SeqLM.from_pretrained(text_model_id).to(DEVICE)
|
| 66 |
+
|
| 67 |
+
# ============================
|
| 68 |
+
# TAXONOMY & HELPERS
|
| 69 |
+
# ============================
|
| 70 |
+
PROFESSION_KEYWORDS = ["lawyer","therapist","doctor","counselor","social worker",
|
| 71 |
+
"advocate","psychologist","psychiatrist","consultant","nurse","hotline","gbv"]
|
| 72 |
+
|
| 73 |
+
PROBLEM_PROFESSION_MAP = {
|
| 74 |
+
"rape": ["lawyer","therapist","counselor","doctor"],
|
| 75 |
+
"sexual assault": ["lawyer","therapist","counselor"],
|
| 76 |
+
"domestic violence": ["lawyer","social worker","therapist"],
|
| 77 |
+
"abuse": ["counselor","social worker","therapist","lawyer"],
|
| 78 |
+
"trauma": ["therapist","psychologist","psychiatrist"],
|
| 79 |
+
"depression": ["therapist","psychologist","doctor"],
|
| 80 |
+
"violence": ["lawyer","counselor","social worker"],
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
def get_region_for_country(country: str) -> str:
|
| 84 |
+
return COUNTRY_REGION_MAP.get(country, "GH")
|
| 85 |
+
|
| 86 |
+
def get_tld_for_country(country: str) -> str:
|
| 87 |
+
return COUNTRY_TLD_MAP.get(country, "")
|
| 88 |
+
|
| 89 |
+
def build_country_biased_query(core: str, country: str) -> str:
|
| 90 |
+
tld = get_tld_for_country(country)
|
| 91 |
+
suffix = f" in {country}"
|
| 92 |
+
if tld:
|
| 93 |
+
return f"{core}{suffix} site:.{tld} OR {country}"
|
| 94 |
+
return f"{core}{suffix}"
|
| 95 |
+
|
| 96 |
+
def dedup_by_url(items):
|
| 97 |
+
seen, out = set(), []
|
| 98 |
+
for it in items:
|
| 99 |
+
u = it.get("link") or it.get("url")
|
| 100 |
+
if u and u not in seen:
|
| 101 |
+
seen.add(u)
|
| 102 |
+
out.append(it)
|
| 103 |
+
return out
|
| 104 |
+
|
| 105 |
+
# ============================
|
| 106 |
+
# SEARCH & SCRAPING
|
| 107 |
+
# ============================
|
| 108 |
+
def google_search(query, num_results=5):
|
| 109 |
+
if not API_KEY or not CX or "YOUR_GOOGLE_API_KEY" in API_KEY or "YOUR_CSE_ID" in CX:
|
| 110 |
+
raise RuntimeError("Google API key and CSE ID must be set as environment variables.")
|
| 111 |
+
url = "https://www.googleapis.com/customsearch/v1"
|
| 112 |
+
params = {"q":query, "key":API_KEY, "cx":CX, "num":num_results}
|
| 113 |
+
r = requests.get(url, params=params, timeout=20)
|
| 114 |
+
r.raise_for_status()
|
| 115 |
+
items = r.json().get("items", []) or []
|
| 116 |
+
return [{"title":i.get("title",""), "link":i.get("link",""), "snippet":i.get("snippet","")} for i in items]
|
| 117 |
+
|
| 118 |
+
def extract_phones(text, region="GH"):
|
| 119 |
+
phones = []
|
| 120 |
+
for match in phonenumbers.PhoneNumberMatcher(text, region):
|
| 121 |
+
try:
|
| 122 |
+
phones.append(phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL))
|
| 123 |
+
except Exception:
|
| 124 |
+
pass
|
| 125 |
+
return list(set(phones))
|
| 126 |
+
|
| 127 |
+
def scrape_contacts(url, region="GH"):
|
| 128 |
+
try:
|
| 129 |
+
res = requests.get(url, headers=HEADERS, timeout=12)
|
| 130 |
+
if not res.ok or not res.text:
|
| 131 |
+
return {"emails": [], "phones": []}
|
| 132 |
+
text = BeautifulSoup(res.text, "html.parser").get_text(separator=" ")
|
| 133 |
+
text = " ".join(text.split())[:300000]
|
| 134 |
+
emails = list(set(EMAIL_REGEX.findall(text)))
|
| 135 |
+
phones = extract_phones(text, region)
|
| 136 |
+
return {"emails": emails, "phones": phones}
|
| 137 |
+
except Exception as e:
|
| 138 |
+
print(f"[scrape error] {url} -> {e}")
|
| 139 |
+
return {"emails": [], "phones": []}
|
| 140 |
+
|
| 141 |
+
# ============================
|
| 142 |
+
# NER + STORY β PROFESSIONS
|
| 143 |
+
# ============================
|
| 144 |
+
def extract_entities(text):
|
| 145 |
+
if not text:
|
| 146 |
+
return [],[],[]
|
| 147 |
+
try:
|
| 148 |
+
ner_results = ner_pipe(text)
|
| 149 |
+
except Exception as e:
|
| 150 |
+
print("[ner error]", e)
|
| 151 |
+
return [],[],[]
|
| 152 |
+
people = [e["word"] for e in ner_results if e.get("entity_group") == "PER"]
|
| 153 |
+
orgs = [e["word"] for e in ner_results if e.get("entity_group") == "ORG"]
|
| 154 |
+
locs = [e["word"] for e in ner_results if e.get("entity_group") == "LOC"]
|
| 155 |
+
return list(set(people)), list(set(orgs)), list(set(locs))
|
| 156 |
+
|
| 157 |
+
def professions_from_story(story: str):
|
| 158 |
+
s = (story or "").lower()
|
| 159 |
+
found = set([p for p in PROFESSION_KEYWORDS if p in s])
|
| 160 |
+
for prob, profs in PROBLEM_PROFESSION_MAP.items():
|
| 161 |
+
if prob in s:
|
| 162 |
+
found.update(profs)
|
| 163 |
+
if not found:
|
| 164 |
+
return ["gbv","counselor"]
|
| 165 |
+
order = ["lawyer","therapist","counselor","social worker","psychologist","psychiatrist","doctor","advocate","nurse","hotline","gbv"]
|
| 166 |
+
return [p for p in order if p in found]
|
| 167 |
+
|
| 168 |
+
def build_queries(story: str, country: str):
|
| 169 |
+
profs = professions_from_story(story)
|
| 170 |
+
cores = []
|
| 171 |
+
for p in profs:
|
| 172 |
+
if p == "gbv":
|
| 173 |
+
cores += ["GBV support organizations", "gender based violence help"]
|
| 174 |
+
else:
|
| 175 |
+
cores += [f"{p} for GBV", f"{p} for sexual assault"]
|
| 176 |
+
unique_cores, seen = [], set()
|
| 177 |
+
for c in cores:
|
| 178 |
+
if c not in seen:
|
| 179 |
+
unique_cores.append(c); seen.add(c)
|
| 180 |
+
return [build_country_biased_query(core, country) for core in unique_cores], profs
|
| 181 |
+
|
| 182 |
+
# ============================
|
| 183 |
+
# TEXT GEN: anonymize + result summary
|
| 184 |
+
# ============================
|
| 185 |
+
def anonymize_story(story: str, max_sentences: int = 2):
|
| 186 |
+
if not story or not story.strip():
|
| 187 |
+
return ""
|
| 188 |
+
prompt = (
|
| 189 |
+
"Anonymize and shorten the following personal story for contacting professionals. "
|
| 190 |
+
"Remove names, exact ages, dates, locations and any identifying details. "
|
| 191 |
+
f"Keep only the essential problem and the type of help requested. Output <= {max_sentences} sentences.\n\n"
|
| 192 |
+
f"Story: {story}\n\nSummary:"
|
| 193 |
+
)
|
| 194 |
+
inputs = text_tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 195 |
+
with torch.no_grad():
|
| 196 |
+
outputs = text_model.generate(**inputs, max_new_tokens=120, temperature=0.2)
|
| 197 |
+
return text_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 198 |
+
|
| 199 |
+
def generate_summary(query, people, orgs, locs):
|
| 200 |
+
prompt = (
|
| 201 |
+
"Write a short, empathetic summary of these search results for a person seeking GBV help.\n"
|
| 202 |
+
f"Query: {query}\nPeople: {', '.join(people) or 'β'}\nOrgs: {', '.join(orgs) or 'β'}\nLocations: {', '.join(locs) or 'β'}\n\n"
|
| 203 |
+
"Explain how the organizations/professionals can help in 3-4 sentences."
|
| 204 |
+
)
|
| 205 |
+
inputs = text_tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 206 |
+
with torch.no_grad():
|
| 207 |
+
outputs = text_model.generate(**inputs, max_new_tokens=150, temperature=0.7)
|
| 208 |
+
return text_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 209 |
+
|
| 210 |
+
# ============================
|
| 211 |
+
# MAIN PIPELINE
|
| 212 |
+
# ============================
|
| 213 |
+
def find_professionals_from_story(story, country=DEFAULT_COUNTRY, results_per_query=RESULTS_PER_QUERY):
|
| 214 |
+
region = get_region_for_country(country)
|
| 215 |
+
queries, profs = build_queries(story, country)
|
| 216 |
+
|
| 217 |
+
# Search
|
| 218 |
+
search_results = []
|
| 219 |
+
for q in queries:
|
| 220 |
+
try:
|
| 221 |
+
items = google_search(q, num_results=results_per_query)
|
| 222 |
+
for it in items:
|
| 223 |
+
it["query"] = q
|
| 224 |
+
search_results.extend(items)
|
| 225 |
+
except Exception as e:
|
| 226 |
+
print("[search error]", q, e)
|
| 227 |
+
|
| 228 |
+
search_results = dedup_by_url(search_results)
|
| 229 |
+
if not search_results:
|
| 230 |
+
return {"summary":"No results found. Try a different country or wording.",
|
| 231 |
+
"professionals":[], "queries_used":queries}
|
| 232 |
+
|
| 233 |
+
# NER on titles/snippets
|
| 234 |
+
all_people, all_orgs, all_locs = [], [], []
|
| 235 |
+
for r in search_results:
|
| 236 |
+
ctx = f"{r.get('title','')}. {r.get('snippet','')}"
|
| 237 |
+
p,o,l = extract_entities(ctx)
|
| 238 |
+
all_people += p; all_orgs += o; all_locs += l
|
| 239 |
+
|
| 240 |
+
# Scrape contacts concurrently
|
| 241 |
+
professionals = []
|
| 242 |
+
with ThreadPoolExecutor(max_workers=MAX_SCRAPE_WORKERS) as ex:
|
| 243 |
+
futures = {ex.submit(scrape_contacts, r["link"], region): r for r in search_results}
|
| 244 |
+
for fut in as_completed(futures):
|
| 245 |
+
r = futures[fut]
|
| 246 |
+
contacts = {"emails": [], "phones": []}
|
| 247 |
+
try:
|
| 248 |
+
contacts = fut.result()
|
| 249 |
+
except Exception as e:
|
| 250 |
+
print("[scrape future error]", r["link"], e)
|
| 251 |
+
professionals.append({
|
| 252 |
+
"title": r.get("title",""),
|
| 253 |
+
"url": r.get("link",""),
|
| 254 |
+
"email": contacts["emails"][0] if contacts["emails"] else "Not found",
|
| 255 |
+
"phone": contacts["phones"][0] if contacts["phones"] else "Not found",
|
| 256 |
+
"source_query": r.get("query","")
|
| 257 |
+
})
|
| 258 |
+
|
| 259 |
+
summary = generate_summary("; ".join(queries[:3]) + (" ..." if len(queries)>3 else ""),
|
| 260 |
+
list(set(all_people)), list(set(all_orgs)), list(set(all_locs)))
|
| 261 |
+
|
| 262 |
+
# Sort by availability of email/phone
|
| 263 |
+
professionals.sort(key=lambda it: (0 if it["email"]!="Not found" else 1,
|
| 264 |
+
0 if it["phone"]!="Not found" else 1))
|
| 265 |
+
return {"summary": summary, "professionals": professionals, "queries_used": queries}
|
| 266 |
+
|
| 267 |
+
# ============================
|
| 268 |
+
# DRAFT (mailto + .eml)
|
| 269 |
+
# ============================
|
| 270 |
+
def build_mailto_and_eml(recipient, subject, body, default_from="noreply@example.com"):
|
| 271 |
+
q_subject = urllib.parse.quote(subject or "")
|
| 272 |
+
q_body = urllib.parse.quote(body or "")
|
| 273 |
+
mailto = f"mailto:{recipient}?subject={q_subject}&body={q_body}"
|
| 274 |
+
|
| 275 |
+
msg = EmailMessage()
|
| 276 |
+
if recipient:
|
| 277 |
+
msg["To"] = recipient
|
| 278 |
+
msg["From"] = default_from
|
| 279 |
+
msg["Subject"] = subject or ""
|
| 280 |
+
msg.set_content(body or "")
|
| 281 |
+
|
| 282 |
+
timestamp = int(time.time())
|
| 283 |
+
fname = f"/content/email_draft_{timestamp}.eml"
|
| 284 |
+
with open(fname, "wb") as f:
|
| 285 |
+
f.write(bytes(msg.as_string(), "utf-8"))
|
| 286 |
+
return mailto, fname
|
| 287 |
+
|
| 288 |
+
# ============================
|
| 289 |
+
# SENDER (SMTP) β Ally AI branding
|
| 290 |
+
# ============================
|
| 291 |
+
def send_ally_ai_email(to_email, subject, body, user_email,
|
| 292 |
+
sender_email, sender_password,
|
| 293 |
+
ai_name=ALLY_AI_NAME,
|
| 294 |
+
logo_url=ALLY_AI_LOGO_URL_DEFAULT):
|
| 295 |
+
"""
|
| 296 |
+
Sends an HTML email branded as Ally AI.
|
| 297 |
+
to_email: recipient (organization)
|
| 298 |
+
subject: subject line
|
| 299 |
+
body: main message (already anonymized or full text)
|
| 300 |
+
user_email: survivor's email (included for reply inside body)
|
| 301 |
+
sender_email/sender_password: SMTP credentials (use Gmail App Password with Gmail)
|
| 302 |
+
"""
|
| 303 |
+
if not to_email or to_email == "Not found":
|
| 304 |
+
return "β No recipient email found β choose a contact with an email."
|
| 305 |
+
|
| 306 |
+
msg = MIMEMultipart("alternative")
|
| 307 |
+
msg["Subject"] = subject or "Request for support"
|
| 308 |
+
msg["From"] = f"{ai_name} <{sender_email}>"
|
| 309 |
+
msg["To"] = to_email
|
| 310 |
+
|
| 311 |
+
html_content = f"""
|
| 312 |
+
<html>
|
| 313 |
+
<body style="font-family: Arial, sans-serif; color: #333;">
|
| 314 |
+
<div style="padding: 20px; border: 1px solid #eee; border-radius: 10px; max-width: 640px; margin: auto;">
|
| 315 |
+
<div style="text-align: center;">
|
| 316 |
+
<img src="{logo_url}" alt="{ai_name} Logo" width="120" style="margin-bottom: 20px;" />
|
| 317 |
+
</div>
|
| 318 |
+
<p>{body}</p>
|
| 319 |
+
<p style="margin-top:20px;">
|
| 320 |
+
<b>Contact the survivor back at:</b> <a href="mailto:{user_email}">{user_email}</a>
|
| 321 |
+
</p>
|
| 322 |
+
<hr style="border:none;border-top:1px solid #eee;margin:24px 0;">
|
| 323 |
+
<p style="font-size: 12px; color: gray; text-align: center;">
|
| 324 |
+
This message was prepared with the help of <b>{ai_name}</b> β connecting survivors with help safely.
|
| 325 |
+
</p>
|
| 326 |
+
</div>
|
| 327 |
+
</body>
|
| 328 |
+
</html>
|
| 329 |
+
"""
|
| 330 |
+
msg.attach(MIMEText(html_content, "html"))
|
| 331 |
+
|
| 332 |
+
try:
|
| 333 |
+
server = smtplib.SMTP("smtp.gmail.com", 587)
|
| 334 |
+
server.starttls()
|
| 335 |
+
server.login(sender_email, sender_password) # Gmail App Password recommended
|
| 336 |
+
server.sendmail(sender_email, [to_email], msg.as_string())
|
| 337 |
+
server.quit()
|
| 338 |
+
return f"β
Email sent successfully to {to_email}"
|
| 339 |
+
except Exception as e:
|
| 340 |
+
return f"β Failed to send email: {str(e)}"
|
| 341 |
+
|
| 342 |
+
# ============================
|
| 343 |
+
# GRADIO UI
|
| 344 |
+
# ============================
|
| 345 |
+
def run_search(story, country):
|
| 346 |
+
out = find_professionals_from_story(story, country=country, results_per_query=RESULTS_PER_QUERY)
|
| 347 |
+
df = pd.DataFrame(out["professionals"])
|
| 348 |
+
# Build dropdown labels: "0 β Title (email/phone)"
|
| 349 |
+
options = []
|
| 350 |
+
for i, r in enumerate(out["professionals"]):
|
| 351 |
+
label_contact = r.get("email") if r.get("email") and r.get("email")!="Not found" else (r.get("phone","No contact"))
|
| 352 |
+
label = f"{i} β {r.get('title','(no title)')} ({label_contact})"
|
| 353 |
+
options.append(label)
|
| 354 |
+
# Anonymize the story
|
| 355 |
+
anon = anonymize_story(story) or "I am seeking confidential support regarding gender-based violence."
|
| 356 |
+
return out["summary"], df.to_dict(orient="records"), gr.update(choices=options, value=(options[0] if options else None)), anon
|
| 357 |
+
|
| 358 |
+
def make_body(anon_text, full_story, use_anon, user_email):
|
| 359 |
+
core = (anon_text or "").strip() if use_anon else (full_story or "").strip()
|
| 360 |
+
# polite template with user email included in body
|
| 361 |
+
lines = [
|
| 362 |
+
core,
|
| 363 |
+
"",
|
| 364 |
+
f"Reply contact: {user_email}",
|
| 365 |
+
"",
|
| 366 |
+
"Thank you."
|
| 367 |
+
]
|
| 368 |
+
return "\n".join([l for l in lines if l is not None])
|
| 369 |
+
|
| 370 |
+
def preview_contact(dropdown_value, df_json, subject, message_text):
|
| 371 |
+
if not dropdown_value:
|
| 372 |
+
return "No contact selected.", ""
|
| 373 |
+
try:
|
| 374 |
+
idx = int(str(dropdown_value).split(" β ")[0])
|
| 375 |
+
rows = pd.DataFrame(df_json)
|
| 376 |
+
contact = rows.iloc[idx].to_dict()
|
| 377 |
+
recipient = contact.get("email") if contact.get("email") and contact.get("email")!="Not found" else "[no email]"
|
| 378 |
+
html = f"""
|
| 379 |
+
<h3>Preview</h3>
|
| 380 |
+
<b>To:</b> {recipient}<br/>
|
| 381 |
+
<b>Organization:</b> <a href="{contact.get('url')}" target="_blank" rel="noopener">{contact.get('title')}</a><br/>
|
| 382 |
+
<b>Subject:</b> {subject}<br/>
|
| 383 |
+
<hr/>
|
| 384 |
+
<pre style="white-space:pre-wrap;">{message_text}</pre>
|
| 385 |
+
"""
|
| 386 |
+
text = f"To: {recipient}\nSubject: {subject}\n\n{message_text[:600]}{'...' if len(message_text)>600 else ''}"
|
| 387 |
+
return text, html
|
| 388 |
+
except Exception as e:
|
| 389 |
+
return f"Preview error: {e}", ""
|
| 390 |
+
|
| 391 |
+
def confirm_action(mode, dropdown_value, df_json, subject, message_text,
|
| 392 |
+
user_email, sender_email, sender_password, logo_url):
|
| 393 |
+
"""
|
| 394 |
+
mode: "Draft only" or "Send via SMTP (Gmail)"
|
| 395 |
+
"""
|
| 396 |
+
if not dropdown_value:
|
| 397 |
+
return "β No contact selected.", "", None
|
| 398 |
+
|
| 399 |
+
# locate contact
|
| 400 |
+
try:
|
| 401 |
+
idx = int(str(dropdown_value).split(" β ")[0])
|
| 402 |
+
rows = pd.DataFrame(df_json)
|
| 403 |
+
contact = rows.iloc[idx].to_dict()
|
| 404 |
+
except Exception as e:
|
| 405 |
+
return f"β Selection error: {e}", "", None
|
| 406 |
+
|
| 407 |
+
recipient = contact.get("email")
|
| 408 |
+
if mode.startswith("Send"):
|
| 409 |
+
# Validate required fields
|
| 410 |
+
if not recipient or recipient == "Not found":
|
| 411 |
+
return "β This contact has no email address. Choose another contact.", "", None
|
| 412 |
+
if not user_email or "@" not in user_email:
|
| 413 |
+
return "β Please enter your email (so the organisation can contact you).", "", None
|
| 414 |
+
if not sender_email or not sender_password:
|
| 415 |
+
return "β Sender email and app password are required for SMTP sending.", "", None
|
| 416 |
+
|
| 417 |
+
status = send_ally_ai_email(
|
| 418 |
+
to_email=recipient,
|
| 419 |
+
subject=subject,
|
| 420 |
+
body=message_text,
|
| 421 |
+
user_email=user_email,
|
| 422 |
+
sender_email=sender_email,
|
| 423 |
+
sender_password=sender_password,
|
| 424 |
+
ai_name=ALLY_AI_NAME,
|
| 425 |
+
logo_url=logo_url or ALLY_AI_LOGO_URL_DEFAULT
|
| 426 |
+
)
|
| 427 |
+
# also provide an .eml draft copy (optional)
|
| 428 |
+
_, eml_path = build_mailto_and_eml(recipient, subject, message_text, default_from=sender_email)
|
| 429 |
+
file_out = eml_path if eml_path and os.path.exists(eml_path) else None
|
| 430 |
+
return status, "", file_out
|
| 431 |
+
else:
|
| 432 |
+
# Draft-only path
|
| 433 |
+
recip_for_draft = recipient if (recipient and recipient!="Not found") else ""
|
| 434 |
+
mailto, eml_path = build_mailto_and_eml(recip_for_draft, subject, message_text, default_from="noreply@ally.ai")
|
| 435 |
+
html_link = f'<a href="{mailto}" target="_blank" rel="noopener">Open draft in email client</a>'
|
| 436 |
+
file_out = eml_path if eml_path and os.path.exists(eml_path) else None
|
| 437 |
+
return "β
Draft created (no email sent).", html_link, file_out
|
| 438 |
+
|
| 439 |
+
with gr.Blocks() as demo:
|
| 440 |
+
gr.Markdown("## Ally AI β GBV Help Finder & Email Assistant\n"
|
| 441 |
+
"This tool searches local organizations, lets you select a contact, and creates an email draft or sends a branded email via SMTP.\n"
|
| 442 |
+
"**Privacy tip:** Prefer anonymized summaries unless youβre comfortable sharing details.")
|
| 443 |
+
|
| 444 |
+
with gr.Row():
|
| 445 |
+
story_in = gr.Textbox(label="Your story (free text)", lines=6, placeholder="Describe your situation and the help you want...")
|
| 446 |
+
country_in = gr.Textbox(value=DEFAULT_COUNTRY, label="Country (to bias search)")
|
| 447 |
+
|
| 448 |
+
search_btn = gr.Button("Search for professionals")
|
| 449 |
+
summary_out = gr.Textbox(label="Search summary (AI)", interactive=False)
|
| 450 |
+
results_table = gr.Dataframe(headers=["title","url","email","phone","source_query"], label="Search results")
|
| 451 |
+
|
| 452 |
+
dropdown_sel = gr.Dropdown(label="Select organization (from results)", choices=[])
|
| 453 |
+
|
| 454 |
+
with gr.Row():
|
| 455 |
+
use_anon = gr.Checkbox(value=True, label="Use anonymized summary (recommended)")
|
| 456 |
+
anon_out = gr.Textbox(label="Anonymized summary", lines=3)
|
| 457 |
+
user_email_in = gr.Textbox(label="Your email (for the organisation to reply to you)")
|
| 458 |
+
|
| 459 |
+
gr.Markdown("### Compose message")
|
| 460 |
+
subject_in = gr.Textbox(value="Request for GBV support", label="Email subject")
|
| 461 |
+
message_in = gr.Textbox(label="Message body", lines=10)
|
| 462 |
+
|
| 463 |
+
with gr.Accordion("Sending options (for automatic sending via Ally AI SMTP)", open=False):
|
| 464 |
+
mode = gr.Radio(choices=["Draft only (mailto + .eml)", "Send via SMTP (Gmail)"], value="Draft only (mailto + .eml)", label="Delivery mode")
|
| 465 |
+
sender_email_in = gr.Textbox(label="Ally AI sender email (SMTP account)")
|
| 466 |
+
sender_pass_in = gr.Textbox(label="Ally AI sender app password", type="password")
|
| 467 |
+
logo_url_in = gr.Textbox(value=ALLY_AI_LOGO_URL_DEFAULT, label="Ally AI logo URL")
|
| 468 |
+
|
| 469 |
+
with gr.Row():
|
| 470 |
+
preview_btn = gr.Button("Preview")
|
| 471 |
+
confirm_btn = gr.Button("Confirm (Create Draft or Send)")
|
| 472 |
+
|
| 473 |
+
preview_text_out = gr.Textbox(label="Preview (text)", interactive=False)
|
| 474 |
+
preview_html_out = gr.HTML()
|
| 475 |
+
status_out = gr.Textbox(label="Status", interactive=False)
|
| 476 |
+
mailto_html_out = gr.HTML()
|
| 477 |
+
eml_file_out = gr.File(label="Download .eml")
|
| 478 |
+
|
| 479 |
+
# Wire: Search
|
| 480 |
+
def _on_search(story, country):
|
| 481 |
+
s, records, options, anon = run_search(story, country)
|
| 482 |
+
# set dropdown + anonymized text and prefill message
|
| 483 |
+
prefill = make_body(anon, story, True, "") # user email unknown yet
|
| 484 |
+
return s, records, gr.update(choices=options, value=(options[0] if options else None)), anon, prefill
|
| 485 |
+
|
| 486 |
+
search_btn.click(_on_search,
|
| 487 |
+
inputs=[story_in, country_in],
|
| 488 |
+
outputs=[summary_out, results_table, dropdown_sel, anon_out, message_in])
|
| 489 |
+
|
| 490 |
+
# When user toggles anonymized vs full story, refresh the message body
|
| 491 |
+
def _refresh_body(use_anon_flag, anon_text, story, user_email):
|
| 492 |
+
return make_body(anon_text, story, use_anon_flag, user_email)
|
| 493 |
+
|
| 494 |
+
use_anon.change(_refresh_body, inputs=[use_anon, anon_out, story_in, user_email_in], outputs=message_in)
|
| 495 |
+
user_email_in.change(_refresh_body, inputs=[use_anon, anon_out, story_in, user_email_in], outputs=message_in)
|
| 496 |
+
anon_out.change(_refresh_body, inputs=[use_anon, anon_out, story_in, user_email_in], outputs=message_in)
|
| 497 |
+
story_in.change(_refresh_body, inputs=[use_anon, anon_out, story_in, user_email_in], outputs=message_in)
|
| 498 |
+
|
| 499 |
+
# Preview
|
| 500 |
+
preview_btn.click(preview_contact,
|
| 501 |
+
inputs=[dropdown_sel, results_table, subject_in, message_in],
|
| 502 |
+
outputs=[preview_text_out, preview_html_out])
|
| 503 |
+
|
| 504 |
+
# Confirm (create draft or send)
|
| 505 |
+
confirm_btn.click(confirm_action,
|
| 506 |
+
inputs=[mode, dropdown_sel, results_table, subject_in, message_in,
|
| 507 |
+
user_email_in, sender_email_in, sender_pass_in, logo_url_in],
|
| 508 |
+
outputs=[status_out, mailto_html_out, eml_file_out])
|
| 509 |
+
|
| 510 |
+
demo.launch(share=False)
|