Spaces:
Sleeping
Sleeping
Download app.py from arcalab/semantic-extraction: direct link, hf CLI and curl.
- Browser
- Download file 44.5 kB
-
https://huggingface.co/spaces/arcalab/semantic-extraction/resolve/main/app.py
- Command line
-
hf download hf://spaces/arcalab/semantic-extraction/app.py
-
curl -L -o app.py https://huggingface.co/spaces/arcalab/semantic-extraction/resolve/main/app.py
44.5 kB
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"<span style='background:{color}33;border:1px solid {color};border-radius:6px;padding:1px 4px;'>{token}</span>"
)
index = end
output.append(html.escape(text[index:]))
joined = "".join(output).replace("\n", "<br>")
return f"<div style='line-height:1.85;font-size:0.95rem;color:#dce2ea'>{joined}</div>"
def slugify(text: str) -> str:
candidate = re.sub(r"[^a-zA-Z0-9]+", "_", text.strip().lower())
candidate = re.sub(r"_+", "_", candidate).strip("_")
return candidate or "field"
def build_default_schema_rows(rows):
counters = {}
schema_rows = []
for idx, row in enumerate(rows, start=1):
name = slugify(str(row.get("entity", "")))
counters[name] = counters.get(name, 0) + 1
suffix = "" if counters[name] == 1 else f"_{counters[name]}"
schema_rows.append(
{
"order": idx,
"field_name": f"{name}{suffix}",
"source_entity": row.get("entity", ""),
"source_type": row.get("type", ""),
"include": True,
"x": False,
}
)
return schema_rows
def collect_field_values(schema_rows, entities):
value_map = {}
for row in schema_rows:
include = bool(row.get("include", True))
remove = bool(row.get("x", False))
field_name = str(row.get("field_name", "")).strip()
source_entity = str(row.get("source_entity", "")).strip()
if not include or remove or not field_name:
continue
if not source_entity:
if field_name not in value_map:
value_map[field_name] = []
continue
matches = [
item.get("entity", "")
for item in entities
if str(item.get("entity", "")).strip().lower() == source_entity.lower()
]
if field_name not in value_map:
value_map[field_name] = []
for match in matches or [source_entity]:
if str(match).strip() and str(match).strip() not in value_map[field_name]:
value_map[field_name].append(str(match).strip())
return value_map
def to_scalar_or_list(values):
if not values:
return None
if len(values) == 1:
return values[0]
return values
def yaml_scalar(value) -> str:
if value is None:
return "null"
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (int, float)):
return str(value)
text = str(value)
if text == "":
return '""'
if re.search(r"[:\-\[\]{}#,&*!|>'\"%@`]|\n", text):
escaped = text.replace("\"", "\\\"")
return f'"{escaped}"'
return text
def render_yaml(value, depth: int = 0) -> str:
pad = " " * depth
if isinstance(value, dict):
lines = []
for key, inner in value.items():
if isinstance(inner, (dict, list)):
lines.append(f"{pad}{key}:")
lines.append(render_yaml(inner, depth + 1))
else:
lines.append(f"{pad}{key}: {yaml_scalar(inner)}")
return "\n".join(lines)
if isinstance(value, list):
lines = []
for item in value:
if isinstance(item, (dict, list)):
lines.append(f"{pad}-")
lines.append(render_yaml(item, depth + 1))
else:
lines.append(f"{pad}- {yaml_scalar(item)}")
return "\n".join(lines)
return f"{pad}{yaml_scalar(value)}"
def create_outputs(
schema_rows,
entities,
workflow_steps,
summary,
doc_type,
source_text,
):
sorted_rows = sorted(
schema_rows,
key=lambda row: int(row.get("order", 9999)) if str(row.get("order", "")).isdigit() else 9999,
)
field_values_raw = collect_field_values(sorted_rows, entities)
field_values = {name: to_scalar_or_list(values) for name, values in field_values_raw.items()}
payload = {
"document_type": doc_type,
"summary": summary,
"word_count": word_count(source_text),
"entity_count": len(entities),
"fields": field_values,
"workflow": {"steps": workflow_steps},
}
json_text = json.dumps(payload, indent=2)
csv_buffer = io.StringIO()
csv_writer = csv.writer(csv_buffer)
csv_writer.writerow(["field_name", "value"])
for key, value in field_values.items():
if isinstance(value, list):
csv_writer.writerow([key, " | ".join(value)])
elif value is None:
csv_writer.writerow([key, ""])
else:
csv_writer.writerow([key, value])
csv_text = csv_buffer.getvalue()
workflow_payload = {
"workflow": {
"document_type": doc_type,
"summary": summary,
"steps": workflow_steps,
"fields": field_values,
}
}
workflow_yaml = render_yaml(workflow_payload)
outputs = {
"JSON": json_text,
"CSV": csv_text,
"Workflow YAML": workflow_yaml,
}
return outputs, payload
def render_flow_diagram(steps) -> None:
if not steps:
st.info("No workflow steps available yet.")
return
blocks = []
for idx, step in enumerate(steps, start=1):
condition = step.get("condition")
border = "#4FC3F7" if not condition else "#FFA726"
shade = "rgba(79,195,247,0.11)" if not condition else "rgba(255,167,38,0.14)"
owner = step.get("owner") or "Unassigned"
cond_html = ""
if condition:
cond_html = f"<div style='font-size:0.78rem;color:#f8c27a;margin-top:6px;'>Condition: {html.escape(str(condition))}</div>"
blocks.append(
f"""
<div style='border:1px solid {border};background:{shade};border-radius:14px;padding:12px 14px;margin:6px 0;'>
<div style='font-size:0.74rem;color:#8aa1b4'>Step {idx}</div>
<div style='font-size:0.95rem;font-weight:600;color:#f2f4f8'>{html.escape(str(step.get("action", "")))}</div>
<div style='font-size:0.78rem;color:#b8c4d0;margin-top:4px;'>Owner: {html.escape(str(owner))}</div>
{cond_html}
</div>
"""
)
if idx < len(steps):
blocks.append("<div style='text-align:center;color:#5f7890;font-size:1.15rem;'>↓</div>")
st.markdown("".join(blocks), unsafe_allow_html=True)
def locked_tabs_css(unlocked: int) -> str:
locked = [i for i in range(2, 5) if i > unlocked]
if not locked:
return ""
selector = ", ".join(
[f"div[data-testid='stTabs'] button[data-baseweb='tab']:nth-of-type({i})" for i in locked]
)
return f"""
<style>
{selector} {{
opacity: 0.34;
filter: grayscale(0.65);
pointer-events: none;
}}
div[data-testid='stTabs'] button[data-baseweb='tab'] {{
border-radius: 10px 10px 0 0;
border: 1px solid rgba(255,255,255,0.08);
}}
.pipeline-card {{
border: 1px solid rgba(158, 180, 198, 0.18);
background: linear-gradient(150deg, rgba(22,27,35,0.9), rgba(14,18,24,0.82));
border-radius: 14px;
padding: 14px 16px;
}}
.metric-chip {{
display:inline-block;
border:1px solid rgba(97,130,158,0.36);
background:rgba(37,52,68,0.45);
border-radius:999px;
padding:4px 11px;
margin:3px 6px 3px 0;
font-size:0.78rem;
}}
</style>
"""
def reset_pipeline_state() -> None:
st.session_state.step_unlocked = 1
st.session_state.content_text = ""
st.session_state.step1_content_input = ""
st.session_state.selected_sample_id = ""
st.session_state.sample_picker = ""
st.session_state.entities = []
st.session_state.workflow_steps = []
st.session_state.summary = ""
st.session_state.schema_rows = []
st.session_state.output_format = "JSON"
st.session_state.final_outputs = {}
st.session_state.final_payload = {}
st.session_state.last_extraction_method = ""
st.session_state.detected_type = "sop"
def dataset_table(samples):
rows = []
for sample in samples:
preview = clip(normalize_space(sample.get("raw_text", "")), 120)
rows.append(
{
"id": sample.get("id", ""),
"type": sample.get("type", ""),
"title": sample.get("title", ""),
"domain": sample.get("domain", ""),
"preview": preview,
}
)
return pd.DataFrame(rows)
def pick_sample_options(samples):
options = []
for sample in samples:
value = sample.get("id", "")
label = f"{sample.get('id', '')} - {sample.get('title', '')}"
options.append((value, label))
return options
st.set_page_config(
page_title="Semantic Data Extraction and Workflow Automation",
page_icon="🧩",
layout="wide",
)
init_state()
samples = load_samples()
schema_reference = load_schema()
st.markdown(
"""
<style>
.hero {
border: 1px solid rgba(139, 170, 194, 0.22);
border-radius: 18px;
padding: 18px 20px;
background:
radial-gradient(circle at 10% 10%, rgba(80, 170, 255, 0.16), transparent 33%),
radial-gradient(circle at 90% 20%, rgba(255, 160, 60, 0.14), transparent 36%),
linear-gradient(145deg, #111722, #0e141d 62%, #141b28);
}
.hero h1 {
margin: 0;
font-size: 2rem;
letter-spacing: 0.02em;
}
.hero p {
margin: 0.35rem 0 0 0;
color: #a8bac9;
font-size: 0.98rem;
}
</style>
<div class='hero'>
<h1>Semantic Data Extraction and Workflow Automation</h1>
<p>Deconstruct noisy, real world content into structured schemas connected to downstream action.</p>
</div>
""",
unsafe_allow_html=True,
)
stats_text = st.session_state.step1_content_input
st.session_state.last_stats = {
"words": word_count(stats_text),
"estimated_entities": estimate_entities_count(stats_text),
"content_type": detect_content_type(stats_text),
}
st.markdown(locked_tabs_css(st.session_state.step_unlocked), unsafe_allow_html=True)
tab1, tab2, tab3, tab4 = st.tabs(TAB_LABELS)
with tab1:
st.markdown("### Step 1: Provide Your Content")
st.caption("Paste unstructured text directly or use a sample helper to accelerate testing.")
sample_options = pick_sample_options(samples)
option_values = [""] + [item[0] for item in sample_options]
option_labels = {"": "Try with sample (helper only)"}
for value, label in sample_options:
option_labels[value] = label
helper_col, helper_btn_col = st.columns([4, 1.35])
with helper_col:
st.selectbox(
"Try with sample",
options=option_values,
format_func=lambda value: option_labels[value],
key="sample_picker",
)
with helper_btn_col:
st.write("")
load_click = st.button("Load Sample", use_container_width=True)
if load_click and st.session_state.sample_picker:
selected = next(
(item for item in samples if item.get("id") == st.session_state.sample_picker),
None,
)
if selected:
st.session_state.selected_sample_id = selected.get("id", "")
st.session_state.step1_content_input = selected.get("raw_text", "")
st.session_state.content_text = selected.get("raw_text", "")
content = st.text_area(
"Paste unstructured text — meeting notes, emails, SOPs, contracts, anything",
key="step1_content_input",
height=315,
placeholder="",
)
st.session_state.content_text = content
chips = [
f"<span class='metric-chip'>{st.session_state.last_stats['words']} words</span>",
f"<span class='metric-chip'>~{st.session_state.last_stats['estimated_entities']} estimated entities</span>",
f"<span class='metric-chip'>Detected: {st.session_state.last_stats['content_type']}</span>",
]
st.markdown("".join(chips), unsafe_allow_html=True)
extract_click = st.button("Extract Structure →", type="primary", use_container_width=True)
if extract_click:
if not st.session_state.content_text.strip():
st.warning("Please add content before extraction.")
else:
allowed, retry_after = check_rate_limit()
if not allowed:
st.error(
f"Rate limit reached: {RATE_LIMIT_COUNT} requests per {RATE_LIMIT_WINDOW_SECONDS}s. Try again in {retry_after}s."
)
else:
words = word_count(st.session_state.content_text)
detected_label = detect_content_type(st.session_state.content_text)
with st.spinner(f"Extracting entities from {words} words..."):
result = run_extraction_pipeline(st.session_state.content_text, detected_label)
st.session_state.entities = result["entities"]
st.session_state.workflow_steps = result["workflow"]
st.session_state.summary = result["summary"]
st.session_state.detected_type = result["document_type"]
st.session_state.last_extraction_method = result["method"]
st.session_state.schema_rows = build_default_schema_rows(result["entities"])
st.session_state.output_format = "JSON"
st.session_state.final_outputs = {}
st.session_state.final_payload = {}
st.session_state.step_unlocked = max(st.session_state.step_unlocked, 2)
if result["method"] == "heuristic" and result.get("fallback_reason"):
st.info(
f"Gemini unavailable ({result['fallback_reason']}). Used heuristic fallback extraction."
)
else:
st.success("Extraction complete. Continue to Step 2.")
with tab2:
st.markdown("### Step 2: Review Extracted Entities")
if st.session_state.step_unlocked < 2:
st.markdown(
"<div class='pipeline-card'>Run Step 1 to unlock entity review.</div>",
unsafe_allow_html=True,
)
else:
st.caption("Edit, add, remove, and retag entities before schema mapping.")
entity_df = pd.DataFrame(st.session_state.entities)
if entity_df.empty:
entity_df = pd.DataFrame(
[{"entity": "", "type": "action", "confidence": 0.5, "context": "", "x": False}]
)
elif "x" not in entity_df.columns:
entity_df["x"] = False
edited_entities = st.data_editor(
entity_df,
use_container_width=True,
num_rows="dynamic",
hide_index=True,
column_config={
"entity": st.column_config.TextColumn("Entity Name"),
"type": st.column_config.SelectboxColumn("Type", options=ENTITY_TYPES, required=True),
"confidence": st.column_config.NumberColumn(
"Confidence", min_value=0.0, max_value=1.0, step=0.01, format="%.2f"
),
"context": st.column_config.TextColumn("Context Snippet"),
"x": st.column_config.CheckboxColumn("x"),
},
key="entities_editor",
)
apply_col, map_col = st.columns([1, 1])
with apply_col:
apply_entity_click = st.button("Apply Entity Edits", use_container_width=True)
with map_col:
map_click = st.button("Map to Schema →", type="primary", use_container_width=True)
if apply_entity_click:
rows = edited_entities.to_dict(orient="records")
cleaned_rows = [
{
"entity": str(row.get("entity", "")).strip(),
"type": str(row.get("type", "")).strip().lower(),
"confidence": normalize_confidence(row.get("confidence"), 0.5),
"context": clip(str(row.get("context", "")).strip(), 180),
}
for row in rows
if str(row.get("entity", "")).strip()
and str(row.get("type", "")).strip().lower() in ENTITY_TYPES
and not bool(row.get("x", False))
]
st.session_state.entities = dedupe_entities(cleaned_rows)
st.session_state.schema_rows = build_default_schema_rows(st.session_state.entities)
st.success("Entity updates applied.")
if map_click:
rows = edited_entities.to_dict(orient="records")
cleaned_rows = [
{
"entity": str(row.get("entity", "")).strip(),
"type": str(row.get("type", "")).strip().lower(),
"confidence": normalize_confidence(row.get("confidence"), 0.5),
"context": clip(str(row.get("context", "")).strip(), 180),
}
for row in rows
if str(row.get("entity", "")).strip()
and str(row.get("type", "")).strip().lower() in ENTITY_TYPES
and not bool(row.get("x", False))
]
st.session_state.entities = dedupe_entities(cleaned_rows)
st.session_state.schema_rows = build_default_schema_rows(st.session_state.entities)
st.session_state.step_unlocked = max(st.session_state.step_unlocked, 3)
st.success("Schema configuration unlocked.")
st.markdown(f"**{entity_summary_text(st.session_state.entities)}**")
left, right = st.columns([1.05, 1.2])
with left:
st.markdown("#### Original Text with Highlighted Entities")
st.markdown(
highlight_entities_html(st.session_state.content_text, st.session_state.entities),
unsafe_allow_html=True,
)
with right:
st.markdown("#### Workflow Signals")
render_flow_diagram(st.session_state.workflow_steps)
with tab3:
st.markdown("### Step 3: Configure Output Schema")
if st.session_state.step_unlocked < 3:
st.markdown(
"<div class='pipeline-card'>Complete Step 2 and click <b>Map to Schema →</b> to unlock this step.</div>",
unsafe_allow_html=True,
)
else:
st.caption("Choose output format, map entities to field names, add custom fields, and preview live output.")
selected_format = st.radio(
"Output format",
OUTPUT_FORMATS,
horizontal=True,
index=OUTPUT_FORMATS.index(st.session_state.output_format)
if st.session_state.output_format in OUTPUT_FORMATS
else 0,
key="schema_output_format",
)
st.session_state.output_format = selected_format
schema_df = pd.DataFrame(st.session_state.schema_rows)
if schema_df.empty:
schema_df = pd.DataFrame(
[
{
"order": 1,
"field_name": "field_1",
"source_entity": "",
"source_type": "action",
"include": True,
"x": False,
}
]
)
edited_schema = st.data_editor(
schema_df,
use_container_width=True,
num_rows="dynamic",
hide_index=True,
column_config={
"order": st.column_config.NumberColumn("Order", min_value=1, step=1),
"field_name": st.column_config.TextColumn("Field Name"),
"source_entity": st.column_config.TextColumn("Source Entity"),
"source_type": st.column_config.SelectboxColumn(
"Source Type", options=ENTITY_TYPES, required=False
),
"include": st.column_config.CheckboxColumn("Include"),
"x": st.column_config.CheckboxColumn("x"),
},
key="schema_editor",
)
schema_rows = edited_schema.to_dict(orient="records")
cleaned_schema_rows = []
for row in schema_rows:
field_name = slugify(str(row.get("field_name", "")))
if not field_name:
continue
if bool(row.get("x", False)):
continue
cleaned_schema_rows.append(
{
"order": int(row.get("order", 9999)) if str(row.get("order", "")).isdigit() else 9999,
"field_name": field_name,
"source_entity": str(row.get("source_entity", "")).strip(),
"source_type": str(row.get("source_type", "action")).strip().lower()
if str(row.get("source_type", "")).strip()
else "action",
"include": bool(row.get("include", True)),
"x": False,
}
)
st.session_state.schema_rows = cleaned_schema_rows
preview_outputs, preview_payload = create_outputs(
st.session_state.schema_rows,
st.session_state.entities,
st.session_state.workflow_steps,
st.session_state.summary,
st.session_state.detected_type,
st.session_state.content_text,
)
preview_left, preview_right = st.columns([1.05, 0.95])
with preview_left:
st.markdown("#### Live Structured Preview")
st.code(preview_outputs[selected_format], language="yaml" if selected_format == "Workflow YAML" else "json")
with preview_right:
if selected_format == "Workflow YAML":
st.markdown("#### Workflow Diagram")
render_flow_diagram(st.session_state.workflow_steps)
else:
st.markdown("#### Mapping Snapshot")
field_count = len(
[row for row in st.session_state.schema_rows if bool(row.get("include", True))]
)
st.markdown(f"<div class='pipeline-card'>Configured fields: <b>{field_count}</b></div>", unsafe_allow_html=True)
st.json(preview_payload["fields"])
generate_click = st.button("Generate Output →", type="primary", use_container_width=True)
if generate_click:
with st.spinner("Building schema..."):
outputs, payload = create_outputs(
st.session_state.schema_rows,
st.session_state.entities,
st.session_state.workflow_steps,
st.session_state.summary,
st.session_state.detected_type,
st.session_state.content_text,
)
st.session_state.final_outputs = outputs
st.session_state.final_payload = payload
st.session_state.step_unlocked = max(st.session_state.step_unlocked, 4)
st.success("Structured output generated. Continue to Step 4.")
with tab4:
st.markdown("### Step 4: Structured Output")
if st.session_state.step_unlocked < 4 or not st.session_state.final_outputs:
st.markdown(
"<div class='pipeline-card'>Generate output in Step 3 to unlock final structured outputs.</div>",
unsafe_allow_html=True,
)
else:
top_col_left, top_col_right = st.columns([1, 1])
with top_col_left:
st.markdown("#### Original Text")
st.text_area(
"Source",
value=st.session_state.content_text,
height=360,
label_visibility="collapsed",
disabled=True,
)
with top_col_right:
st.markdown("#### Structured Output")
active_format = st.selectbox("Format", OUTPUT_FORMATS, key="final_output_format_picker")
lang = "yaml" if active_format == "Workflow YAML" else "json"
st.code(st.session_state.final_outputs[active_format], language=lang)
words = word_count(st.session_state.content_text)
entities_n = len(st.session_state.entities)
fields_k = len(
[
row
for row in st.session_state.schema_rows
if bool(row.get("include", True)) and not bool(row.get("x", False))
]
)
st.markdown(f"**Extracted {entities_n} entities from {words} words, mapped to {fields_k} fields**")
d1, d2, d3 = st.columns(3)
with d1:
st.download_button(
"Download JSON",
data=st.session_state.final_outputs["JSON"].encode("utf-8"),
file_name="structured_output.json",
mime="application/json",
use_container_width=True,
)
with d2:
st.download_button(
"Download CSV",
data=st.session_state.final_outputs["CSV"].encode("utf-8"),
file_name="structured_output.csv",
mime="text/csv",
use_container_width=True,
)
with d3:
st.download_button(
"Download Workflow YAML",
data=st.session_state.final_outputs["Workflow YAML"].encode("utf-8"),
file_name="workflow_output.yaml",
mime="application/x-yaml",
use_container_width=True,
)
if st.button("Process New Document", use_container_width=True):
reset_pipeline_state()
st.rerun()
st.markdown("---")
with st.expander("Dataset and Schema Reference", expanded=False):
st.caption("Existing sample corpus and output schema kept as-is from data/.")
st.dataframe(dataset_table(samples), use_container_width=True, hide_index=True)
schema_col, sample_col = st.columns(2)
with schema_col:
st.code(json.dumps(schema_reference, indent=2), language="json")
with sample_col:
sample_schema_preview = {
"sample_count": len(samples),
"types": sorted(list({sample.get("type", "") for sample in samples})),
"first_sample": samples[0].get("id") if samples else "",
}
st.code(json.dumps(sample_schema_preview, indent=2), language="json")
st.caption(
f"Extraction mode: {st.session_state.last_extraction_method or 'not-run'} | Rate limit: {RATE_LIMIT_COUNT}/{RATE_LIMIT_WINDOW_SECONDS}s"
)
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)