[31388f42] Implement Expert Response Generator with Gemini & CE integration

This commit is contained in:
2026-03-02 08:46:22 +00:00
parent adce4773da
commit 7b979652f4
5 changed files with 293 additions and 14 deletions

View File

@@ -2,7 +2,8 @@ import streamlit as st
import pandas as pd
from db import get_leads, init_db
import json
from enrich import run_sync # Import our sync function
from enrich import run_sync, refresh_ce_data
from generate_reply import generate_email_draft
st.set_page_config(page_title="TradingTwins Lead Engine", layout="wide")
@@ -18,7 +19,20 @@ if st.sidebar.button("1. Ingest Emails (Mock)"):
st.sidebar.success(f"Ingested {count} new leads.")
st.rerun()
if st.sidebar.button("2. Sync to Company Explorer"):
if st.sidebar.button("2. Ingest Real Emails (Graph API)"):
try:
from trading_twins_ingest import process_leads
with st.spinner("Fetching emails from Microsoft Graph..."):
count = process_leads()
if count > 0:
st.sidebar.success(f"Successfully ingested {count} new leads form inbox!")
else:
st.sidebar.info("No new leads found in inbox.")
st.rerun()
except Exception as e:
st.sidebar.error(f"Ingest failed: {e}")
if st.sidebar.button("3. Sync to Company Explorer"):
with st.spinner("Syncing with Company Explorer API..."):
# Capture output for debugging
try:
@@ -52,24 +66,76 @@ if not df.empty:
for index, row in df.iterrows():
with st.expander(f"{row['company_name']} ({row['status']})"):
c1, c2 = st.columns(2)
# --- Left Column: Lead Data ---
c1.write(f"**Contact:** {row['contact_name']}")
c1.write(f"**Email:** {row['email']}")
c1.text(row['raw_body'][:200] + "...")
# Metadata Display
meta = {}
if row.get('lead_metadata'):
try:
meta = json.loads(row['lead_metadata'])
except:
pass
if meta:
c1.write("---")
c1.write(f"**Area:** {meta.get('area', '-')}")
c1.write(f"**Purpose:** {meta.get('purpose', '-')}")
c1.write(f"**Location:** {meta.get('zip', '')} {meta.get('city', '')}")
with c1.expander("Show Original Email Body"):
st.code(row['raw_body'], language="html")
# --- Right Column: Enrichment & Response ---
enrichment = json.loads(row['enrichment_data']) if row['enrichment_data'] else {}
if enrichment:
c2.write("--- Integration Status ---")
if enrichment.get('ce_id'):
c2.success(f"✅ Linked to Company Explorer (ID: {enrichment['ce_id']})")
c2.write(f"**CE Status:** {enrichment.get('ce_status')}")
ce_id = enrichment.get('ce_id')
if ce_id:
c2.success(f"✅ Linked to Company Explorer (ID: {ce_id})")
# CE Data Display
ce_data = enrichment.get('ce_data', {})
vertical = ce_data.get('vertical')
summary = ce_data.get('summary')
if vertical:
c2.info(f"**Industry:** {vertical}")
else:
c2.warning("Industry Analysis pending...")
if summary:
with c2.expander("Show Analysis Summary"):
st.write(summary)
# Refresh Button
if c2.button("🔄 Refresh Analysis Data", key=f"refresh_{row['id']}"):
with st.spinner("Fetching latest data from Company Explorer..."):
new_data = refresh_ce_data(row['id'], ce_id)
st.toast("Data refreshed!")
st.rerun()
# Generate Reply Button (only if we have data)
c2.write("--- Response Generation ---")
if c2.button("✨ Generate Expert Reply", key=f"gen_{row['id']}"):
with st.spinner("Generating draft with Gemini..."):
# Prepare lead data dict from row
lead_dict = row.to_dict()
draft = generate_email_draft(lead_dict, ce_data)
# Store draft in session state to persist
st.session_state[f"draft_{row['id']}"] = draft
# Display Draft
if f"draft_{row['id']}" in st.session_state:
c2.text_area("Draft Email", value=st.session_state[f"draft_{row['id']}"], height=300)
else:
c2.warning("⚠️ Not yet synced or failed")
c2.info(f"Log: {enrichment.get('message')}")
if enrichment.get('ce_data'):
c2.json(enrichment['ce_data'])
c2.info(f"Log: {enrichment.get('message')}")
else:
st.info("No leads found. Click 'Ingest Emails' in the sidebar.")