import csv
import html
import io
import json
import os
import re
import time
from pathlib import Path
import pandas as pd
import requests
import streamlit as st
BASE_DIR = Path(__file__).parent
DATA_PATH = BASE_DIR / "data" / "sample_documents.jsonl"
SCHEMA_PATH = BASE_DIR / "data" / "output_schema.json"
GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
RATE_LIMIT_COUNT = 8
RATE_LIMIT_WINDOW_SECONDS = 60
ENTITY_TYPES = ["person", "org", "date", "amount", "action"]
OUTPUT_FORMATS = ["JSON", "CSV", "Workflow YAML"]
TAB_LABELS = [
"1. Provide Content",
"2. Review Entities",
"3. Configure Schema",
"4. Structured Output",
]
def load_samples():
rows = []
with DATA_PATH.open("r", encoding="utf-8") as handle:
for line in handle:
clean = line.strip()
if clean:
rows.append(json.loads(clean))
return rows
def load_schema():
with SCHEMA_PATH.open("r", encoding="utf-8") as handle:
return json.load(handle)
def init_state() -> None:
defaults = {
"step_unlocked": 1,
"content_text": "",
"selected_sample_id": "",
"entities": [],
"workflow_steps": [],
"detected_type": "sop",
"summary": "",
"last_extraction_method": "",
"schema_rows": [],
"output_format": "JSON",
"final_outputs": {},
"final_payload": {},
"rate_limit_timestamps": [],
"last_stats": {"words": 0, "estimated_entities": 0, "content_type": "Unknown"},
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
if "sample_picker" not in st.session_state:
st.session_state.sample_picker = ""
if "step1_content_input" not in st.session_state:
st.session_state.step1_content_input = ""
def normalize_space(text: str) -> str:
return re.sub(r"\s+", " ", text).strip()
def word_count(text: str) -> int:
return len(re.findall(r"\b\w+\b", text))
def estimate_entities_count(text: str) -> int:
person_hits = len(re.findall(r"\b[A-Z][a-z]+\s+[A-Z][a-z]+\b", text))
amount_hits = len(re.findall(r"\$\s?\d[\d,]*(?:\.\d+)?(?:\s?(?:k|K|M|ARR))?", text))
date_hits = len(
re.findall(
r"\b(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}(?:/\d{2,4})?|today|tomorrow|monday|tuesday|wednesday|thursday|friday|saturday|sunday|q\d|eod)\b",
text,
flags=re.IGNORECASE,
)
)
org_hits = len(re.findall(r"\b[A-Z][A-Za-z&]+(?:\s+[A-Z][A-Za-z&]+){0,2}\b", text))
action_hits = len(
re.findall(
r"\b(?:must|should|needs to|need to|action item|follow-up|follow up|assign|schedule|review|approve|deploy|send|draft|confirm|disable|escalate)\b",
text,
flags=re.IGNORECASE,
)
)
rough = person_hits + amount_hits + date_hits + min(org_hits, 12) + action_hits
return max(0, rough)
def detect_content_type(text: str) -> str:
lower = text.lower()
scores = {
"email": 0,
"meeting_notes": 0,
"support_ticket": 0,
"sop": 0,
}
for token in ["subject:", "from:", "to:", "reply", "thread", "cc:"]:
if token in lower:
scores["email"] += 2
for token in ["attendees", "standup", "retro", "meeting", "notes", "agenda"]:
if token in lower:
scores["meeting_notes"] += 2
for token in ["ticket", "severity", "repro", "issue", "priority", "case:"]:
if token in lower:
scores["support_ticket"] += 2
for token in ["sop", "procedure", "runbook", "checklist", "policy", "step"]:
if token in lower:
scores["sop"] += 2
if re.search(r"\bif\b", lower):
scores["sop"] += 1
scores["support_ticket"] += 1
if re.search(r"\baction items?\b", lower):
scores["meeting_notes"] += 2
picked = max(scores.items(), key=lambda item: item[1])[0]
if scores[picked] == 0:
return "Unknown"
pretty = {
"email": "Email",
"meeting_notes": "Meeting Notes",
"support_ticket": "Support Ticket",
"sop": "SOP",
}
return pretty[picked]
def to_doc_type_key(label: str) -> str:
mapping = {
"Email": "email",
"Meeting Notes": "meeting_notes",
"Support Ticket": "support_ticket",
"SOP": "sop",
}
return mapping.get(label, "sop")
def unique_in_order(values):
seen = set()
out = []
for value in values:
clean = value.strip()
lower = clean.lower()
if clean and lower not in seen:
seen.add(lower)
out.append(clean)
return out
def safe_json_from_text(raw: str):
body = raw.strip()
if not body:
return None
if body.startswith("```"):
body = re.sub(r"^```(?:json)?", "", body).strip()
body = re.sub(r"```$", "", body).strip()
match = re.search(r"\{[\s\S]*\}", body)
if match:
body = match.group(0)
try:
loaded = json.loads(body)
except json.JSONDecodeError:
return None
return loaded if isinstance(loaded, dict) else None
def clip(text: str, n: int) -> str:
return text[:n] if len(text) <= n else text[: n - 1].rstrip() + "..."
def normalize_confidence(value, fallback: float = 0.5) -> float:
try:
parsed = float(value)
except (TypeError, ValueError):
parsed = fallback
return max(0.0, min(1.0, round(parsed, 2)))
def find_context_snippet(text: str, entity: str) -> str:
clean = entity.strip()
if not clean:
return ""
match = re.search(re.escape(clean), text, flags=re.IGNORECASE)
if not match:
return clip(clean, 120)
start = max(0, match.start() - 42)
end = min(len(text), match.end() + 70)
snippet = text[start:end].strip().replace("\n", " ")
return clip(normalize_space(snippet), 140)
def split_step_candidates(text: str):
lines = [line.strip() for line in text.splitlines() if line.strip()]
explicit = []
for line in lines:
if re.match(r"^(\d+[\).]|[-*])\s*", line):
explicit.append(re.sub(r"^(\d+[\).]|[-*])\s*", "", line).strip())
elif re.search(
r"\b(must|should|need to|needs to|if|when|assign|send|draft|approve|review|deploy|fix)\b",
line,
flags=re.IGNORECASE,
):
explicit.append(line)
if len(explicit) >= 2:
return explicit[:12]
sentence_chunks = re.split(r"(?<=[.!?])\s+", normalize_space(text))
fallback = [chunk for chunk in sentence_chunks if 20 <= len(chunk) <= 220]
return fallback[:10]
def infer_owner(text: str):
owner_map = {
"finance": "Finance",
"procurement": "Procurement",
"security": "Security",
"support": "Support",
"legal": "Legal",
"manager": "Manager",
"requester": "Requester",
"customer": "Customer",
"engineering": "Engineering",
"qa": "QA",
"product": "Product",
"ops": "Operations",
"it": "IT",
}
lower = text.lower()
for key, value in owner_map.items():
if key in lower:
return value
return None
def extract_entities_heuristic(text: str):
people = re.findall(r"\b[A-Z][a-z]+\s+[A-Z][a-z]+\b", text)
people += [tag.replace("@", "") for tag in re.findall(r"@[A-Za-z0-9_.-]+", text)]
orgs = []
for phrase in re.findall(r"\b[A-Z][A-Za-z&.-]+(?:\s+[A-Z][A-Za-z&.-]+){0,2}\b", text):
if re.search(r"\b(Team|Ops|Office|Leadership|Council|Finance|Security|Procurement|Support|Engineering)\b", phrase):
orgs.append(phrase)
dates = re.findall(
r"\b(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}(?:/\d{2,4})?|today|tomorrow|monday|tuesday|wednesday|thursday|friday|saturday|sunday|next week|eod|q\d|fy\d{2}|\d{1,2}:\d{2}\s?(?:am|pm)?(?:\s?[A-Z]{2,4})?)\b",
text,
flags=re.IGNORECASE,
)
amounts = re.findall(r"\$\s?\d[\d,]*(?:\.\d+)?(?:\s?(?:k|K|M|ARR|%))?", text)
action_candidates = split_step_candidates(text)
actions = []
for item in action_candidates:
if re.search(
r"\b(assign|send|review|approve|validate|build|draft|notify|schedule|disable|deploy|escalate|confirm|investigate|provide|update|track|fix)\b",
item,
flags=re.IGNORECASE,
):
actions.append(clip(item, 110))
rows = []
for value in unique_in_order(people)[:20]:
rows.append(
{
"entity": value,
"type": "person",
"confidence": 0.62,
"context": find_context_snippet(text, value),
}
)
for value in unique_in_order(orgs)[:16]:
rows.append(
{
"entity": value,
"type": "org",
"confidence": 0.58,
"context": find_context_snippet(text, value),
}
)
for value in unique_in_order(dates)[:20]:
rows.append(
{
"entity": value,
"type": "date",
"confidence": 0.7,
"context": find_context_snippet(text, value),
}
)
for value in unique_in_order(amounts)[:20]:
rows.append(
{
"entity": value,
"type": "amount",
"confidence": 0.74,
"context": find_context_snippet(text, value),
}
)
for value in unique_in_order(actions)[:20]:
rows.append(
{
"entity": value,
"type": "action",
"confidence": 0.54,
"context": find_context_snippet(text, value),
}
)
return dedupe_entities(rows)
def extract_workflow_heuristic(text: str):
steps = []
for idx, line in enumerate(split_step_candidates(text), start=1):
condition = None
if re.search(r"\b(if|when|unless)\b", line, flags=re.IGNORECASE):
condition = clip(line, 140)
steps.append(
{
"order": idx,
"action": clip(line, 160),
"owner": infer_owner(line),
"condition": condition,
}
)
if not steps:
steps.append(
{
"order": 1,
"action": "Review source text and identify next action",
"owner": None,
"condition": None,
}
)
return steps[:12]
def dedupe_entities(rows):
seen = set()
out = []
for row in rows:
entity = str(row.get("entity", "")).strip()
kind = str(row.get("type", "")).strip().lower()
if not entity or kind not in ENTITY_TYPES:
continue
key = (entity.lower(), kind)
if key in seen:
continue
seen.add(key)
out.append(
{
"entity": entity,
"type": kind,
"confidence": normalize_confidence(row.get("confidence"), 0.5),
"context": clip(str(row.get("context", "")).strip(), 180),
}
)
return out
def build_gemini_prompt(text: str, guessed_type: str) -> str:
return f"""You extract structured entities and workflow steps from noisy business text.
Return only a JSON object with this exact schema:
{{
"summary": "string",
"document_type": "sop|meeting_notes|email|support_ticket",
"entities": [
{{"entity": "string", "type": "person|org|date|amount|action", "confidence": 0.0, "context": "string"}}
],
"workflow": [
{{"order": 1, "action": "string", "owner": "string|null", "condition": "string|null"}}
]
}}
Rules:
- infer document_type from text
- include at least 8 entities if present
- confidence is 0 to 1
- context is a short snippet from source
- keep workflow actions concise and executable
- no markdown, no commentary, JSON only
Detected type hint: {guessed_type}
Source text:
{text}
"""
def extract_with_gemini(text: str, guessed_type: str):
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
return None, "missing_api_key"
payload = {
"contents": [{"parts": [{"text": build_gemini_prompt(text, guessed_type)}]}],
"generationConfig": {
"temperature": 0.1,
"topP": 0.8,
"maxOutputTokens": 3072,
"responseMimeType": "application/json",
},
}
try:
response = requests.post(f"{GEMINI_URL}?key={api_key}", json=payload, timeout=35)
response.raise_for_status()
body = response.json()
chunks = []
for candidate in body.get("candidates", []):
content = candidate.get("content", {})
for part in content.get("parts", []):
if "text" in part:
chunks.append(part["text"])
parsed = safe_json_from_text("\n".join(chunks))
if not parsed:
return None, "invalid_json"
return parsed, "ok"
except requests.RequestException:
return None, "request_failed"
except ValueError:
return None, "invalid_response"
def coerce_gemini_payload(payload, text: str, guessed_type: str):
entity_rows = payload.get("entities", []) if isinstance(payload.get("entities"), list) else []
workflow_rows = payload.get("workflow", []) if isinstance(payload.get("workflow"), list) else []
summary = str(payload.get("summary", "")).strip()
normalized_entities = dedupe_entities(entity_rows)
steps = []
for idx, step in enumerate(workflow_rows, start=1):
if not isinstance(step, dict):
continue
action = str(step.get("action", "")).strip()
if not action:
continue
owner = step.get("owner")
condition = step.get("condition")
steps.append(
{
"order": int(step.get("order", idx)) if str(step.get("order", "")).isdigit() else idx,
"action": clip(action, 160),
"owner": str(owner).strip() if isinstance(owner, str) and owner.strip() else None,
"condition": str(condition).strip() if isinstance(condition, str) and condition.strip() else None,
}
)
doc_type = str(payload.get("document_type", "")).strip().lower()
if doc_type not in {"sop", "meeting_notes", "email", "support_ticket"}:
doc_type = to_doc_type_key(guessed_type)
if not summary:
sentence = re.split(r"(?<=[.!?])\s+", normalize_space(text))
summary = clip(" ".join(sentence[:2]), 260)
if not steps:
steps = extract_workflow_heuristic(text)
if not normalized_entities:
normalized_entities = extract_entities_heuristic(text)
return {
"summary": summary,
"document_type": doc_type,
"entities": normalized_entities,
"workflow": steps,
}
def run_extraction_pipeline(text: str, guessed_type: str):
gemini_raw, status = extract_with_gemini(text, guessed_type)
if gemini_raw:
payload = coerce_gemini_payload(gemini_raw, text, guessed_type)
payload["method"] = "gemini"
payload["fallback_reason"] = ""
return payload
fallback_payload = {
"summary": clip(" ".join(re.split(r"(?<=[.!?])\s+", normalize_space(text))[:2]), 260)
or "Structured extraction generated from heuristic analysis.",
"document_type": to_doc_type_key(guessed_type),
"entities": extract_entities_heuristic(text),
"workflow": extract_workflow_heuristic(text),
"method": "heuristic",
"fallback_reason": status,
}
return fallback_payload
def check_rate_limit() -> tuple[bool, int]:
now = time.time()
recent = [
ts
for ts in st.session_state.rate_limit_timestamps
if now - ts <= RATE_LIMIT_WINDOW_SECONDS
]
st.session_state.rate_limit_timestamps = recent
if len(recent) >= RATE_LIMIT_COUNT:
retry_after = int(RATE_LIMIT_WINDOW_SECONDS - (now - min(recent)))
return False, max(1, retry_after)
st.session_state.rate_limit_timestamps.append(now)
return True, 0
def entity_summary_text(rows):
counts = {kind: 0 for kind in ENTITY_TYPES}
for row in rows:
kind = row.get("type")
if kind in counts:
counts[kind] += 1
total = sum(counts.values())
return (
f"Found {total} entities: "
f"{counts['person']} people, {counts['date']} dates, "
f"{counts['amount']} amounts, {counts['action']} actions"
)
def type_color(entity_type: str) -> str:
palette = {
"person": "#4FC3F7",
"org": "#FFA726",
"date": "#81C784",
"amount": "#EF5350",
"action": "#90CAF9",
}
return palette.get(entity_type, "#B0BEC5")
def highlight_entities_html(text: str, rows):
segments = []
for row in rows:
entity = str(row.get("entity", "")).strip()
kind = str(row.get("type", "")).strip().lower()
if not entity:
continue
for match in re.finditer(re.escape(entity), text, flags=re.IGNORECASE):
segments.append((match.start(), match.end(), kind))
segments.sort(key=lambda part: (part[0], -(part[1] - part[0])))
merged = []
cursor = -1
for start, end, kind in segments:
if start < cursor:
continue
merged.append((start, end, kind))
cursor = end
output = []
index = 0
for start, end, kind in merged:
output.append(html.escape(text[index:start]))
color = type_color(kind)
token = html.escape(text[start:end])
output.append(
f"{token}"
)
index = end
output.append(html.escape(text[index:]))
joined = "".join(output).replace("\n", "
")
return f"
Deconstruct noisy, real world content into structured schemas connected to downstream action.