Spaces:
Runtime error
Runtime error
Download app.py from abhidgp1978/flowforge-ai: direct link, hf CLI and curl.
- Browser
- Download file 6.85 kB
-
https://huggingface.co/spaces/abhidgp1978/flowforge-ai/resolve/main/app.py
- Command line
-
hf download hf://spaces/abhidgp1978/flowforge-ai/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abhidgp1978/flowforge-ai/resolve/main/app.py
6.85 kB
| 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 | |