Spaces:
Runtime error
Runtime error
File size: 6,852 Bytes
9652783 8dd7a92 d1430d8 7af88ea 6fafd7f d1430d8 6b68695 d1430d8 6fafd7f d1430d8 5ee0ae9 6fafd7f d1430d8 8dd7a92 2f9ce87 d1430d8 ca66c12 8dd7a92 d1430d8 e4afb79 d1430d8 8dd7a92 2f9ce87 8dd7a92 d1430d8 ca66c12 8dd7a92 d1430d8 e4afb79 d1430d8 8dd7a92 2f9ce87 d1430d8 ca66c12 8dd7a92 d1430d8 e4afb79 d1430d8 8dd7a92 6b68695 d1430d8 8dd7a92 d1430d8 8dd7a92 6fafd7f d1430d8 6b68695 8dd7a92 d1430d8 e4afb79 8dd7a92 5ee0ae9 d1430d8 e4afb79 d1430d8 6fafd7f d1430d8 8dd7a92 76f085e d1430d8 8dd7a92 76f085e d1430d8 8dd7a92 a794cad d1430d8 8dd7a92 76f085e d1430d8 76f085e 9652783 d1430d8 76f085e d1430d8 51628ed d1430d8 6fafd7f d1430d8 51628ed a794cad d1430d8 6fafd7f d1430d8 5d1ecf9 8dd7a92 51628ed a794cad 6fafd7f d1430d8 a794cad 76f085e a794cad 1fa31dd 174072d 6fafd7f d1430d8 | 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 | import gradio as gr
from transformers import pipeline
import re
# === Global Caching Variable ===
# We must move the LLM initialization out of the global scope to prevent startup timeouts.
# This variable will hold the loaded pipeline after the first generation click.
CACHED_LLM_PIPELINE = None
# --- LLM Initialization and Retrieval (CRITICAL FIX) ---
def get_llm_pipeline():
"""Initializes the T5-Large model only when first requested and caches it."""
global CACHED_LLM_PIPELINE
if CACHED_LLM_PIPELINE is None:
# NOTE: This block is what caused the timeout when run globally.
# Now it only runs AFTER the user clicks 'Generate'.
print("--- Initializing T5-Large Model (one-time load) ---")
try:
CACHED_LLM_PIPELINE = pipeline("text2text-generation", model="google/flan-t5-large")
except Exception as e:
print(f"CRITICAL ERROR: Failed to load LLM pipeline: {e}")
raise RuntimeError("Model loading failed during runtime.") from e
return CACHED_LLM_PIPELINE
# --- The Core MCP Model Functions ---
def llm_generate(prompt: str, max_tokens=512, temp=0.7, rep_pen=5.0) -> str:
"""Helper for generating structured output with max repetition penalty."""
# Retrieve the cached pipeline. This triggers the initial load if it hasn't happened.
llm_pipeline = get_llm_pipeline()
output = llm_pipeline(
prompt,
max_new_tokens=max_tokens,
temperature=temp,
repetition_penalty=rep_pen,
top_p=0.9
)[0]["generated_text"]
return output.strip()
# --- Specialized LLM Tools (Calling the refactored llm_generate) ---
def requirements_planner(idea: str) -> str:
"""LLM Tool 1: Generates Requirements."""
prompt = (
"You are an expert software requirements analyst. "
"Extract clear, structured, and detailed functional and non-functional requirements "
f"for the idea: {idea}\n\n"
"1. Functional Requirements:\n"
)
return llm_generate(prompt)
def architecture_designer(requirements: str) -> str:
"""LLM Tool 2: Generates Architecture based on Requirements."""
prompt = (
"You are a senior software architect. "
"Design a high-level architecture including key modules, APIs, and data flow "
f"based on these requirements:\n{requirements}\n\n"
"1. Key Modules:\n"
)
return llm_generate(prompt)
def workflow_mapper(architecture: str) -> str:
"""LLM Tool 3: Generates Development Workflow based on Architecture."""
prompt = (
"You are a software project manager. "
"Outline a detailed development workflow (phases, tasks, deliverables) "
f"based on this architecture:\n{architecture}\n\n"
"Phase 1: Project Setup\n- Task: "
)
return llm_generate(prompt)
def code_suggester(workflow: str) -> str:
"""LLM Tool 4: Generates Python Starter Code."""
prompt = (
"Write clean, well-commented starter Python code for this project. "
"Define classes, functions, and logical placeholders, focused on the Gradio interface "
f"and the workflow:\n{workflow}"
)
# Use a lower repetition penalty for code generation
return llm_generate(prompt, rep_pen=2.5)
# --- Utility for Diagram Generation ---
import re
def visualizer(architecture_text: str) -> str:
"""Generates a simple Mermaid diagram from the architecture text."""
# Logic to extract modules and build a basic LR graph (Left to Right)
text_for_parsing = re.sub(r'^\d+\.', '', architecture_text, flags=re.MULTILINE)
modules = re.findall(r"\b[A-Z][A-Za-z0-9_ ]+", text_for_parsing)
modules = [m for m in list(dict.fromkeys(modules)) if len(m.strip()) > 2]
if len(modules) < 2:
modules = ["Gradio_UI", "Controller", "LLM_Model"]
mermaid = "graph LR\n"
for i in range(len(modules) - 1):
mermaid += f" {modules[i].replace(' ', '_')} --> {modules[i+1].replace(' ', '_')}\n"
return f"```mermaid\n{mermaid}```"
# === The Core MCP Controller Logic ===
def generate_all_design(project_idea: str):
"""
The main controller function that orchestrates the entire chained LLM workflow.
Output of one step feeds directly into the next.
"""
if not project_idea.strip():
# Quick check before triggering model load
return "Error: Please enter a project idea.", "", "", "", ""
# 1. Requirements (Input: Idea)
reqs = requirements_planner(idea=project_idea)
# 2. Architecture (Input: Requirements)
arch = architecture_designer(requirements=reqs)
# 3. Workflow (Input: Architecture)
flow = workflow_mapper(architecture=arch)
# 4. Code Template (Input: Workflow)
code = code_suggester(workflow=flow)
# 5. Diagram (Input: Architecture)
diagram = visualizer(architecture_text=arch)
# Returns the structured design elements
return reqs, arch, flow, code, diagram
# === Gradio UI (The Presenter) ===
with gr.Blocks(title="FlowForge AI") as app:
gr.Markdown("<h1 style='text-align:center;color:#0f62fe;'>⚙️ FlowForge AI Workflow Designer</h1>")
gr.Markdown("### Enter your project idea to generate the full Requirements, Architecture, and Workflow.")
user_input = gr.Textbox(label="Describe your project idea (e.g., 'AI app to design software workflow...)", lines=3)
# The generation button triggers the model loading/generation process
generate_btn = gr.Button("Generate Full Design", variant="primary")
with gr.Tabs():
with gr.TabItem("1. Requirements"):
req_out = gr.Textbox(label="Functional and Non-functional Requirements", lines=8, interactive=False)
with gr.TabItem("2. Architecture"):
arch_out = gr.Textbox(label="High-Level Architecture & Data Flow", lines=8, interactive=False)
with gr.TabItem("3. Workflow"):
flow_out = gr.Textbox(label="Development Phases, Tasks, and Deliverables", lines=8, interactive=False)
with gr.TabItem("4. Code Template"):
# Ensure code output uses gr.Code for syntax highlighting
code_out = gr.Code(label="Starter Python Code (Based on Workflow)", language="python", lines=15, interactive=False)
with gr.TabItem("5. Architecture Diagram"):
# This is where the Mermaid markdown will be rendered
diagram_out = gr.Markdown("Architecture Diagram Source will appear here.")
generate_btn.click(
# The key function where the model initialization is now handled
fn=generate_all_design,
inputs=user_input,
outputs=[req_out, arch_out, flow_out, code_out, diagram_out]
)
if __name__ == "__main__":
# The Gradio app launches immediately, before the LLM is loaded.
pass
|