File size: 23,950 Bytes
2cad607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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()