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("""
Enterprise Solution Architecture Assistant — Powered by Hugging Face
Requirement Analysis · Solution Architecture · Fit-Gap Analysis · Deployment Reports