ForwardDeployAI / app.py
Faraz618's picture
Create app.py
2cad607 verified
Raw
History Blame Contribute Delete
24 kB
import gradio as gr
from transformers import pipeline
from fpdf import FPDF
import pandas as pd
import tempfile
import os
import re
from datetime import datetime
# ─────────────────────────────────────────
# Load Hugging Face Models (cached after first run)
# ─────────────────────────────────────────
print("Loading models...")
classifier = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli"
)
summarizer = pipeline(
"summarization",
model="facebook/bart-large-cnn",
min_length=60,
max_length=180
)
print("Models ready.")
# ─────────────────────────────────────────
# Constants
# ─────────────────────────────────────────
REQUIREMENT_CATEGORIES = [
"Data Integration & ETL",
"AI & Machine Learning",
"Workflow Automation",
"Cloud Infrastructure",
"Security & Compliance",
"User Interface & Experience",
"API & Microservices",
"Analytics & Reporting",
"Legacy System Migration",
"Real-time Processing",
]
ARCHITECTURE_PATTERNS = {
"Data Integration & ETL": ("Data Pipeline Architecture", ["Apache Kafka", "Airflow", "dbt", "PostgreSQL"]),
"AI & Machine Learning": ("ML Platform Architecture", ["Hugging Face", "FastAPI", "MLflow", "Docker"]),
"Workflow Automation": ("Event-Driven Architecture", ["n8n", "Temporal", "RabbitMQ", "FastAPI"]),
"Cloud Infrastructure": ("Cloud-Native Architecture", ["AWS ECS", "Terraform", "K8s", "CloudWatch"]),
"Security & Compliance": ("Zero-Trust Architecture", ["Vault", "Keycloak", "OAuth2", "WAF"]),
"User Interface & Experience": ("Micro-Frontend Architecture", ["React", "Next.js", "Tailwind", "Vercel"]),
"API & Microservices": ("API Gateway Architecture", ["Kong", "FastAPI", "gRPC", "Redis"]),
"Analytics & Reporting": ("Data Warehouse Architecture", ["Snowflake", "dbt", "Metabase", "Redshift"]),
"Legacy System Migration": ("Strangler Fig Architecture", ["API Adapter Layer", "Kafka", "Docker", "PostgreSQL"]),
"Real-time Processing": ("Stream Processing Architecture", ["Apache Flink", "Kafka Streams", "Redis", "InfluxDB"]),
}
FITGAP_COMPONENTS = [
"Authentication & Access Control",
"Data Ingestion Pipeline",
"AI / ML Inference Layer",
"Reporting & Dashboard",
"API Integration Layer",
"Notification & Alerting",
"Audit Logging",
"Scalability & Load Balancing",
]
# ─────────────────────────────────────────
# Tab 1 β€” Requirement Analyzer
# ─────────────────────────────────────────
def analyze_requirements(client_name, industry, requirements_text, existing_systems):
if not requirements_text.strip():
return "⚠️ Please enter client requirements.", None
# Zero-shot classification
clf_result = classifier(
requirements_text,
candidate_labels=REQUIREMENT_CATEGORIES,
multi_label=True
)
# Summarize requirements
safe_text = requirements_text[:1024]
try:
summary_result = summarizer(safe_text, truncation=True)
summary = summary_result[0]["summary_text"]
except Exception:
summary = requirements_text[:300] + "..."
# Complexity score
top_scores = clf_result["scores"][:3]
avg_score = sum(top_scores) / len(top_scores)
complexity = "🟒 Low" if avg_score < 0.45 else ("🟑 Medium" if avg_score < 0.70 else "πŸ”΄ High")
# Build output
lines = []
lines.append(f"## πŸ“‹ Requirement Analysis β€” {client_name or 'Client'}")
lines.append(f"**Industry:** {industry or 'Not specified'}")
lines.append(f"**Existing Systems:** {existing_systems or 'Not specified'}")
lines.append("")
lines.append("### πŸ“ Executive Summary")
lines.append(summary)
lines.append("")
lines.append("### 🏷️ Requirement Categories (Confidence)")
rows = []
for label, score in zip(clf_result["labels"], clf_result["scores"]):
bar = "β–ˆ" * int(score * 20) + "β–‘" * (20 - int(score * 20))
emoji = "βœ…" if score > 0.6 else ("πŸ”Ά" if score > 0.35 else "⬜")
lines.append(f"{emoji} **{label}** β€” {score:.0%} `{bar}`")
rows.append({"Category": label, "Confidence": f"{score:.0%}", "Priority": emoji})
lines.append("")
lines.append(f"### βš™οΈ Solution Complexity: {complexity}")
lines.append("")
lines.append("### 🎯 Top 3 Focus Areas")
for i, (label, score) in enumerate(zip(clf_result["labels"][:3], clf_result["scores"][:3]), 1):
lines.append(f"{i}. **{label}** ({score:.0%} confidence)")
df = pd.DataFrame(rows)
return "\n".join(lines), df
# ─────────────────────────────────────────
# Tab 2 β€” Solution Architect
# ─────────────────────────────────────────
def generate_architecture(client_name, requirements_text, timeline_weeks, budget):
if not requirements_text.strip():
return "⚠️ Please enter requirements first."
clf_result = classifier(
requirements_text,
candidate_labels=REQUIREMENT_CATEGORIES,
multi_label=True
)
top_labels = clf_result["labels"][:3]
top_scores = clf_result["scores"][:3]
primary_label = top_labels[0]
pattern, tech_stack = ARCHITECTURE_PATTERNS.get(
primary_label,
("Modular Monolith Architecture", ["Python", "FastAPI", "PostgreSQL", "Docker"])
)
weeks = int(timeline_weeks) if timeline_weeks else 12
lines = []
lines.append(f"## πŸ—οΈ Solution Architecture β€” {client_name or 'Client'}")
lines.append(f"**Recommended Pattern:** `{pattern}`")
lines.append(f"**Timeline:** {weeks} weeks **Budget:** {budget or 'Not specified'}")
lines.append("")
lines.append("### πŸ”© Architecture Components")
component_map = {
"Data Integration & ETL": [("Ingestion Layer", "Kafka / Airflow DAGs"), ("Transform Layer", "dbt + Pandas"), ("Storage Layer", "PostgreSQL + S3")],
"AI & Machine Learning": [("Model Serving", "FastAPI + Hugging Face Inference"), ("Experiment Tracking", "MLflow"), ("Data Versioning", "DVC + S3")],
"Workflow Automation": [("Orchestrator", "Temporal / n8n"), ("Event Bus", "RabbitMQ"), ("State Store", "Redis")],
"Cloud Infrastructure": [("Compute", "AWS ECS / EKS"), ("IaC", "Terraform"), ("Monitoring", "CloudWatch + Grafana")],
"Security & Compliance": [("Identity Provider", "Keycloak / Auth0"), ("Secrets Management", "HashiCorp Vault"), ("Audit Trail", "Elasticsearch")],
"API & Microservices": [("Gateway", "Kong / AWS API Gateway"), ("Services", "FastAPI Microservices"), ("Cache", "Redis")],
"Analytics & Reporting": [("Warehouse", "Snowflake / Redshift"), ("Transform", "dbt"), ("Viz", "Metabase / Superset")],
"Legacy System Migration": [("Adapter Layer", "REST Wrapper API"), ("Event Bridge", "Kafka"), ("Parallel Run", "Feature Flags")],
"Real-time Processing": [("Stream Processor", "Apache Flink"), ("Message Bus", "Kafka"), ("Time-Series DB", "InfluxDB")],
"User Interface & Experience": [("Frontend", "Next.js + Tailwind"), ("State Mgmt", "Zustand / Redux"), ("CDN", "Cloudflare")],
}
components = component_map.get(primary_label, [
("Backend", "FastAPI"), ("Database", "PostgreSQL"), ("Cache", "Redis")
])
for name, tech in components:
lines.append(f"- **{name}:** `{tech}`")
lines.append("")
lines.append("### πŸ”„ Data Flow")
data_flows = [
"1. Client request enters via API Gateway with auth validation",
"2. Request routed to appropriate microservice",
"3. Business logic executed; data retrieved from primary store",
"4. AI/ML inference called where applicable",
"5. Response formatted and returned; event logged to audit trail",
"6. Async background jobs triggered for downstream processing",
]
for flow in data_flows:
lines.append(flow)
lines.append("")
lines.append("### πŸ“… Phased Delivery Plan")
phase_weeks = max(2, weeks // 3)
lines.append(f"- **Phase 1 β€” Discovery & POC** (Weeks 1–{phase_weeks}): Requirements validation, prototype core components")
lines.append(f"- **Phase 2 β€” Pilot Build** (Weeks {phase_weeks+1}–{phase_weeks*2}): Build integrations, internal testing, stakeholder demos")
lines.append(f"- **Phase 3 β€” Production** (Weeks {phase_weeks*2+1}–{weeks}): Hardening, security review, go-live, handover")
lines.append("")
lines.append("### πŸ› οΈ Recommended Tech Stack")
for tech in tech_stack:
lines.append(f"- `{tech}`")
lines.append("")
lines.append("### πŸ“Š Secondary Architecture Concerns")
for label, score in zip(top_labels[1:], top_scores[1:]):
p2, _ = ARCHITECTURE_PATTERNS.get(label, ("Modular Design", []))
lines.append(f"- **{label}** ({score:.0%}): Consider {p2} patterns for this layer")
return "\n".join(lines)
# ─────────────────────────────────────────
# Tab 3 β€” Fit-Gap Analyzer
# ─────────────────────────────────────────
def run_fitgap(client_name, requirements_text, available_capabilities):
if not requirements_text.strip():
return "⚠️ Please enter requirements.", None
rows = []
lines = []
lines.append(f"## πŸ” Fit-Gap Analysis β€” {client_name or 'Client'}")
lines.append("")
caps_lower = (available_capabilities or "").lower()
for component in FITGAP_COMPONENTS:
result = classifier(
f"{requirements_text}\n\nDoes this require: {component}?",
candidate_labels=["required", "not required"],
)
required = result["labels"][0] == "required"
confidence = result["scores"][0]
keyword = component.lower().split()[0]
platform_has = keyword in caps_lower
if required and platform_has:
status, action = "βœ… FIT", "No action needed"
elif required and not platform_has:
status, action = "πŸ”΄ GAP", "Build / procure this capability"
elif not required and platform_has:
status, action = "🟑 OPTIONAL", "Available but not required β€” disable to reduce cost"
else:
status, action = "⬜ N/A", "Not applicable for this engagement"
lines.append(f"**{component}** β†’ {status} ({confidence:.0%} confidence)")
lines.append(f" ↳ _{action}_")
lines.append("")
rows.append({
"Component": component,
"Status": status,
"Confidence": f"{confidence:.0%}",
"Action": action,
})
gaps = sum(1 for r in rows if "GAP" in r["Status"])
fits = sum(1 for r in rows if "FIT" in r["Status"])
options = sum(1 for r in rows if "OPTIONAL" in r["Status"])
lines.append("---")
lines.append(f"### πŸ“Š Summary: {fits} Fit | {gaps} Gap(s) | {options} Optional")
if gaps == 0:
lines.append("βœ… **Platform is fully capable of meeting requirements.**")
elif gaps <= 2:
lines.append(f"🟑 **Minor gaps found. {gaps} component(s) need to be built or procured.**")
else:
lines.append(f"πŸ”΄ **Significant gaps found. Recommend phased implementation to address {gaps} missing components.**")
df = pd.DataFrame(rows)
return "\n".join(lines), df
# ─────────────────────────────────────────
# Tab 4 β€” Deployment Report Generator
# ─────────────────────────────────────────
def generate_report(client_name, industry, requirements_text, existing_systems,
available_capabilities, timeline_weeks, budget):
if not client_name.strip() or not requirements_text.strip():
return None, "⚠️ Please provide at least Client Name and Requirements."
# Run all analyses
analysis_md, _ = analyze_requirements(client_name, industry, requirements_text, existing_systems)
architecture_md = generate_architecture(client_name, requirements_text, timeline_weeks, budget)
fitgap_md, df = run_fitgap(client_name, requirements_text, available_capabilities)
def strip_md(text):
text = re.sub(r"[#*`_~\[\]β–ˆβ–‘βœ…πŸ”΄πŸŸ‘πŸŸ’β¬œπŸ”ΆπŸ—οΈπŸ“‹πŸ“πŸ·οΈβš™οΈπŸŽ―πŸ”©πŸ”„πŸ“…πŸ› οΈπŸ“ŠπŸ”β†’β†³]", "", text)
return text.strip()
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
# Header
pdf.set_fill_color(26, 82, 118)
pdf.rect(0, 0, 210, 28, "F")
pdf.set_text_color(255, 255, 255)
pdf.set_font("Helvetica", "B", 18)
pdf.set_y(8)
pdf.cell(0, 10, "ForwardDeployAI - Deployment Readiness Report", ln=True, align="C")
pdf.set_font("Helvetica", "", 10)
pdf.cell(0, 6, f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')} | Client: {client_name}", ln=True, align="C")
pdf.set_text_color(0, 0, 0)
pdf.ln(10)
def section(title):
pdf.set_fill_color(240, 248, 255)
pdf.set_font("Helvetica", "B", 13)
pdf.set_text_color(26, 82, 118)
pdf.cell(0, 9, title, ln=True, fill=True)
pdf.set_text_color(0, 0, 0)
pdf.ln(2)
def body(text, size=10):
pdf.set_font("Helvetica", "", size)
for line in text.splitlines():
clean = strip_md(line).strip()
if not clean:
pdf.ln(2)
continue
try:
pdf.multi_cell(0, 6, clean)
except Exception:
pass
# Section 1 β€” Client Overview
section("1. Client Overview")
pdf.set_font("Helvetica", "", 10)
overview = (
f"Client Name : {client_name}\n"
f"Industry : {industry or 'Not specified'}\n"
f"Existing Systems: {existing_systems or 'Not specified'}\n"
f"Budget Range : {budget or 'Not specified'}\n"
f"Timeline : {timeline_weeks or 'Not specified'} weeks"
)
for line in overview.splitlines():
pdf.cell(0, 7, line, ln=True)
pdf.ln(4)
# Section 2 β€” Requirement Analysis
section("2. Requirement Analysis")
body(analysis_md)
pdf.ln(4)
# Section 3 β€” Solution Architecture
section("3. Solution Architecture")
body(architecture_md)
pdf.ln(4)
# Section 4 β€” Fit-Gap Analysis
section("4. Fit-Gap Analysis")
body(fitgap_md)
if df is not None and not df.empty:
pdf.ln(4)
pdf.set_font("Helvetica", "B", 9)
col_w = [70, 28, 28, 64]
headers = ["Component", "Status", "Confidence", "Action"]
pdf.set_fill_color(26, 82, 118)
pdf.set_text_color(255, 255, 255)
for h, w in zip(headers, col_w):
pdf.cell(w, 7, h, border=1, fill=True)
pdf.ln()
pdf.set_text_color(0, 0, 0)
pdf.set_font("Helvetica", "", 8)
for i, row in df.iterrows():
fill = i % 2 == 0
pdf.set_fill_color(245, 249, 252) if fill else pdf.set_fill_color(255, 255, 255)
for val, w in zip([row["Component"], row["Status"], row["Confidence"], row["Action"]], col_w):
clean_val = strip_md(str(val))
pdf.cell(w, 6, clean_val, border=1, fill=True)
pdf.ln()
pdf.ln(6)
# Section 5 β€” Recommendations
section("5. Deployment Recommendations")
gaps = len([r for _, r in df.iterrows() if "GAP" in r["Status"]]) if df is not None else 0
recs = [
f"1. Begin with a 2-week technical discovery workshop to validate all requirements.",
f"2. Address {gaps} identified gap(s) before pilot phase to avoid scope creep.",
f"3. Build a proof-of-value prototype in weeks 3-4 to validate architecture choices.",
f"4. Establish daily standup cadence and weekly stakeholder demos from day one.",
f"5. Document all integration points and obtain sign-off before production deployment.",
f"6. Define SLAs, rollback procedures, and monitoring dashboards pre-go-live.",
]
for rec in recs:
pdf.set_font("Helvetica", "", 10)
pdf.multi_cell(0, 6, rec)
pdf.ln(1)
# Footer
pdf.set_y(-15)
pdf.set_font("Helvetica", "I", 8)
pdf.set_text_color(128, 128, 128)
pdf.cell(0, 10, "ForwardDeployAI β€” Powered by Hugging Face | github.com/Faraz6180", align="C")
# Save
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
pdf.output(tmp.name)
return tmp.name, "βœ… Report generated successfully! Click download to save."
# ─────────────────────────────────────────
# Gradio UI
# ─────────────────────────────────────────
CSS = """
.gradio-container { font-family: 'Segoe UI', sans-serif; }
.tab-nav button { font-weight: 600; font-size: 14px; }
footer { display: none !important; }
"""
with gr.Blocks(
title="ForwardDeployAI",
theme=gr.themes.Base(
primary_hue="blue",
secondary_hue="indigo",
font=gr.themes.GoogleFont("Inter"),
),
css=CSS
) as demo:
gr.HTML("""
<div style='text-align:center; padding:24px 0 8px 0;'>
<h1 style='font-size:2rem; color:#1A5276; margin:0;'>πŸ—οΈ ForwardDeployAI</h1>
<p style='color:#555; margin:6px 0 0 0; font-size:1rem;'>
Enterprise Solution Architecture Assistant β€” Powered by Hugging Face
</p>
<p style='color:#888; font-size:0.85rem; margin:4px 0 0 0;'>
Requirement Analysis Β· Solution Architecture Β· Fit-Gap Analysis Β· Deployment Reports
</p>
</div>
""")
# ── Shared Inputs ──
with gr.Accordion("πŸ“₯ Client Brief (used across all tabs)", open=True):
with gr.Row():
inp_client = gr.Textbox(label="Client Name", placeholder="e.g. Acme Corp", scale=2)
inp_industry = gr.Textbox(label="Industry", placeholder="e.g. Healthcare, FinTech", scale=2)
inp_timeline = gr.Number( label="Timeline (weeks)", value=12, scale=1)
inp_budget = gr.Textbox(label="Budget Range", placeholder="e.g. $100K–$250K", scale=1)
inp_requirements = gr.Textbox(
label="Client Requirements",
placeholder="Describe the business problem and what the client needs...",
lines=5
)
with gr.Row():
inp_existing = gr.Textbox(
label="Existing Systems / Tech Stack",
placeholder="e.g. SAP ERP, on-premise SQL Server, legacy Java monolith",
lines=2, scale=3
)
inp_capabilities = gr.Textbox(
label="Available Platform Capabilities",
placeholder="e.g. Authentication, API Layer, Cloud hosting, CI/CD",
lines=2, scale=3
)
with gr.Tabs():
# ── Tab 1 ──
with gr.Tab("πŸ“‹ Requirement Analyzer"):
gr.Markdown("Classifies business requirements into technical categories using **BART-Large-MNLI** zero-shot classification.")
btn1 = gr.Button("πŸ” Analyze Requirements", variant="primary", size="lg")
with gr.Row():
out1_md = gr.Markdown(label="Analysis")
out1_df = gr.Dataframe(label="Category Scores", wrap=True)
btn1.click(
analyze_requirements,
inputs=[inp_client, inp_industry, inp_requirements, inp_existing],
outputs=[out1_md, out1_df]
)
# ── Tab 2 ──
with gr.Tab("πŸ—οΈ Solution Architect"):
gr.Markdown("Generates a full solution architecture, component breakdown, data flow, and phased delivery plan.")
btn2 = gr.Button("βš™οΈ Generate Architecture", variant="primary", size="lg")
out2_md = gr.Markdown(label="Architecture")
btn2.click(
generate_architecture,
inputs=[inp_client, inp_requirements, inp_timeline, inp_budget],
outputs=out2_md
)
# ── Tab 3 ──
with gr.Tab("πŸ” Fit-Gap Analyzer"):
gr.Markdown("Evaluates which solution components are required vs available, identifying gaps and optional features.")
btn3 = gr.Button("πŸ“Š Run Fit-Gap Analysis", variant="primary", size="lg")
with gr.Row():
out3_md = gr.Markdown(label="Fit-Gap Report")
out3_df = gr.Dataframe(label="Gap Table", wrap=True)
btn3.click(
run_fitgap,
inputs=[inp_client, inp_requirements, inp_capabilities],
outputs=[out3_md, out3_df]
)
# ── Tab 4 ──
with gr.Tab("πŸ“„ Deployment Report"):
gr.Markdown("Runs all three analyses and compiles a downloadable **PDF deployment readiness report**.")
btn4 = gr.Button("πŸ–¨οΈ Generate PDF Report", variant="primary", size="lg")
out4_status = gr.Markdown()
out4_file = gr.File(label="πŸ“₯ Download Report", file_types=[".pdf"])
btn4.click(
generate_report,
inputs=[inp_client, inp_industry, inp_requirements, inp_existing,
inp_capabilities, inp_timeline, inp_budget],
outputs=[out4_file, out4_status]
)
# ── Tab 5 ──
with gr.Tab("ℹ️ About"):
gr.Markdown("""
## About ForwardDeployAI
This tool simulates the core workflow of a **Forward Deployment Engineer** β€” the bridge between client business requirements and scalable technical solutions.
### πŸ€– Hugging Face Models Used
| Model | Task |
|---|---|
| `facebook/bart-large-mnli` | Zero-shot requirement classification |
| `facebook/bart-large-cnn` | Requirement summarization |
### πŸ”§ What It Does
1. **Requirement Analyzer** β€” Classifies free-text client requirements into 10 technical architecture categories with confidence scores
2. **Solution Architect** β€” Recommends architecture patterns, component stacks, data flows, and phased delivery plans
3. **Fit-Gap Analyzer** β€” Evaluates 8 core solution components against available capabilities and flags gaps
4. **Report Generator** β€” Produces a branded, multi-section PDF deployment readiness report
### πŸ‘€ Built by
**Faraz Mubeen Haider** β€” AI Engineer
[github.com/Faraz6180](https://github.com/Faraz6180) Β· [linkedin.com/in/farazmubeen-ai](https://linkedin.com/in/farazmubeen-ai)
""")
gr.HTML("""
<div style='text-align:center; padding:16px; color:#aaa; font-size:0.8rem; border-top:1px solid #eee; margin-top:16px;'>
ForwardDeployAI Β· Powered by πŸ€— Hugging Face Β· Built by Faraz Mubeen Haider
</div>
""")
demo.launch()