Spaces:
Runtime error
Runtime error
| import os | |
| import json | |
| import pandas as pd | |
| import numpy as np | |
| from datetime import datetime, timedelta | |
| from typing import List, Dict, Any, Optional | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| # Core imports | |
| import gradio as gr | |
| import chromadb | |
| from sentence_transformers import SentenceTransformer | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| import joblib | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| import plotly.graph_objects as go | |
| import plotly.express as px | |
| from plotly.subplots import make_subplots | |
| import re | |
| import uuid | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| # Set up paths for different deployment environments | |
| CHROMA_DB_PATH = os.getenv("CHROMA_DB_PATH", "./chroma_db") | |
| PERSIST_DIR = os.getenv("PERSIST_DIR", CHROMA_DB_PATH) | |
| Path(PERSIST_DIR).mkdir(parents=True, exist_ok=True) | |
| print(f"ποΈ ChromaDB will be stored at: {PERSIST_DIR}") | |
| # Data Models | |
| class StartupIdea: | |
| """Data model for startup ideas""" | |
| name: str | |
| description: str | |
| industry: str | |
| target_market: str | |
| problem_statement: str | |
| solution: str | |
| unique_value_proposition: str | |
| class BusinessPlan: | |
| """Comprehensive business plan structure""" | |
| executive_summary: str | |
| company_description: str | |
| market_analysis: str | |
| organization_management: str | |
| service_product_line: str | |
| marketing_sales: str | |
| funding_request: str | |
| financial_projections: Dict[str, Any] | |
| class Flashcard: | |
| """Learning flashcard structure""" | |
| id: str | |
| front: str | |
| back: str | |
| category: str | |
| difficulty: str | |
| tags: List[str] | |
| class RoadmapMilestone: | |
| """Roadmap milestone structure""" | |
| id: str | |
| title: str | |
| description: str | |
| timeline: str | |
| dependencies: List[str] | |
| priority: str | |
| category: str | |
| # RAG System Implementation | |
| class RAGSystem: | |
| """Retrieval-Augmented Generation system using ChromaDB""" | |
| def __init__(self, model_name: str = "all-MiniLM-L6-v2"): | |
| print("π§ Initializing RAG System...") | |
| try: | |
| self.embedding_model = SentenceTransformer(model_name) | |
| self.chroma_client = chromadb.PersistentClient(path=PERSIST_DIR) | |
| self.collection_name = "startup_knowledge" | |
| self.collection = None | |
| self.text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=1000, | |
| chunk_overlap=200, | |
| length_function=len | |
| ) | |
| print("β RAG System initialized successfully") | |
| except Exception as e: | |
| print(f"β Error initializing RAG System: {e}") | |
| raise | |
| def initialize_collection(self): | |
| """Initialize or get existing collection""" | |
| try: | |
| collections = self.chroma_client.list_collections() | |
| existing_collection = next((c for c in collections if c.name == self.collection_name), None) | |
| if existing_collection: | |
| self.collection = self.chroma_client.get_collection(self.collection_name) | |
| print(f"π Found existing collection with {self.collection.count()} documents") | |
| else: | |
| self.collection = self.chroma_client.create_collection( | |
| name=self.collection_name, | |
| metadata={"description": "Startup knowledge base"} | |
| ) | |
| print("π Created new collection") | |
| return self.collection | |
| except Exception as e: | |
| print(f"β Error initializing collection: {e}") | |
| try: | |
| self.collection = self.chroma_client.create_collection( | |
| name=f"{self.collection_name}_{uuid.uuid4().hex[:8]}", | |
| metadata={"description": "Startup knowledge base"} | |
| ) | |
| print("π Created fallback collection") | |
| return self.collection | |
| except Exception as e2: | |
| print(f"β Fatal error creating collection: {e2}") | |
| raise | |
| def add_documents(self, documents: List[str], metadatas: List[Dict] = None): | |
| """Add documents to the knowledge base""" | |
| if not self.collection: | |
| self.initialize_collection() | |
| try: | |
| all_chunks = [] | |
| all_metadatas = [] | |
| for i, doc in enumerate(documents): | |
| chunks = self.text_splitter.split_text(doc) | |
| all_chunks.extend(chunks) | |
| doc_metadata = metadatas[i] if metadatas and i < len(metadatas) else {} | |
| for chunk in chunks: | |
| all_metadatas.append({ | |
| **doc_metadata, | |
| "chunk_id": str(uuid.uuid4()), | |
| "timestamp": datetime.now().isoformat() | |
| }) | |
| print(f"π Generating embeddings for {len(all_chunks)} chunks...") | |
| embeddings = self.embedding_model.encode(all_chunks).tolist() | |
| ids = [str(uuid.uuid4()) for _ in all_chunks] | |
| self.collection.add( | |
| documents=all_chunks, | |
| embeddings=embeddings, | |
| metadatas=all_metadatas, | |
| ids=ids | |
| ) | |
| print(f"β Added {len(all_chunks)} chunks to knowledge base") | |
| return len(all_chunks) | |
| except Exception as e: | |
| print(f"β Error adding documents: {e}") | |
| return 0 | |
| def retrieve_context(self, query: str, n_results: int = 5) -> List[Dict]: | |
| """Retrieve relevant context for a query""" | |
| if not self.collection: | |
| self.initialize_collection() | |
| try: | |
| query_embedding = self.embedding_model.encode([query]).tolist()[0] | |
| results = self.collection.query( | |
| query_embeddings=[query_embedding], | |
| n_results=min(n_results, max(1, self.collection.count())) | |
| ) | |
| contexts = [] | |
| if results['documents'][0]: | |
| for i, doc in enumerate(results['documents'][0]): | |
| contexts.append({ | |
| "content": doc, | |
| "metadata": results['metadatas'][0][i] if results['metadatas'][0] else {}, | |
| "distance": results['distances'][0][i] if results['distances'] and results['distances'][0] else 0 | |
| }) | |
| return contexts | |
| except Exception as e: | |
| print(f"β Error retrieving context: {e}") | |
| return [] | |
| def generate_response(self, query: str, context: List[Dict]) -> str: | |
| """Generate response using retrieved context""" | |
| try: | |
| context_text = "\n".join([ctx["content"] for ctx in context]) | |
| return self._generate_structured_response(query, context_text) | |
| except Exception as e: | |
| print(f"β Error generating response: {e}") | |
| return "I apologize, but I encountered an error generating a response. Please try again." | |
| def _generate_structured_response(self, query: str, context: str) -> str: | |
| """Generate structured response based on query type""" | |
| query_lower = query.lower() | |
| if "market research" in query_lower or "competition" in query_lower: | |
| return f"""**Market Analysis Framework:** | |
| Based on startup best practices: | |
| {context[:500]}... | |
| **Key Recommendations:** | |
| - Conduct thorough competitive analysis using TAM/SAM/SOM framework | |
| - Identify unique value propositions that differentiate your solution | |
| - Analyze market size and growth potential with real data | |
| """ | |
| elif "business plan" in query_lower: | |
| return f"""**Business Plan Development:** | |
| Essential components: | |
| {context[:500]}... | |
| **Core Sections:** | |
| - Executive Summary | |
| - Market Analysis | |
| - Financial Projections | |
| """ | |
| else: | |
| return f"""**Strategic Guidance:** | |
| {context[:400]}... | |
| **Key Considerations:** | |
| - Validate assumptions with market data | |
| - Focus on solving genuine problems | |
| - Build strong unit economics | |
| """ | |
| # Startup Knowledge Base | |
| STARTUP_KNOWLEDGE_BASE = [ | |
| """ | |
| IDEA VALIDATION AND MARKET RESEARCH | |
| Before building any product, entrepreneurs must prove market demand exists. This involves: | |
| 1. Problem Identification: Identify genuine problems that specific customer segments face daily. | |
| 2. Market Analysis: Determine total addressable market (TAM) size. Use TAM/SAM/SOM framework: | |
| - TAM (Total Addressable Market): Total market demand | |
| - SAM (Serviceable Addressable Market): Portion targeted by your products | |
| - SOM (Serviceable Obtainable Market): Portion you can realistically capture | |
| 3. Competitive Research: Analyze competitors' offerings, pricing, strengths, weaknesses. | |
| 4. Customer Validation: Conduct 50+ interviews to validate core assumptions. | |
| Key metrics: CAC, LTV, market penetration rate, NPS. | |
| """, | |
| """ | |
| BUSINESS PLAN DEVELOPMENT | |
| A comprehensive business plan serves as roadmap and investor communication tool: | |
| 1. Executive Summary: Mission, product, market, competitive advantages, funding needs. | |
| 2. Company Description: Business model, legal structure, value proposition. | |
| 3. Market Analysis: Industry overview, target market, competitive landscape. | |
| 4. Organization & Management: Team, advisors, hiring plans. | |
| 5. Financial Projections: 3-5 year forecasts, cash flow, break-even analysis. | |
| 6. Funding Requirements: Capital needs, use of funds, expected ROI. | |
| """, | |
| """ | |
| FUNDING AND FINANCIAL MANAGEMENT | |
| Securing and managing finances strategically: | |
| 1. Funding Sources: | |
| - Bootstrapping: Personal savings | |
| - Angels: $25K-$100K early stage | |
| - VC: $1M+ for high-growth potential | |
| - Crowdfunding: Product launches | |
| - Grants: SBIR/STTR programs | |
| 2. Key Metrics: | |
| - Burn Rate: Monthly cash expenditure | |
| - Runway: Months of cash remaining | |
| - CAC: Total marketing cost Γ· new customers | |
| - LTV: Average revenue Γ margin Γ lifespan | |
| - LTV/CAC should be 3:1 or higher | |
| 3. Best Practices: | |
| - Separate business and personal finances | |
| - Maintain 6-12 months cash reserves | |
| - Track MRR, ARR, gross margins | |
| """, | |
| """ | |
| LEGAL STRUCTURE AND COMPLIANCE | |
| Choosing the right legal foundation: | |
| 1. Business Structures: | |
| - Sole Proprietorship: Simple, personal liability | |
| - LLC: Asset protection, flexible taxes | |
| - C-Corp: Best for VC funding, stock issuance | |
| - Delaware C-Corp advantages for startups | |
| 2. Essential Documents: | |
| - Articles of Incorporation | |
| - Founders' Agreement with vesting | |
| - Employee NDAs and IP assignments | |
| - Terms of service, privacy policy | |
| 3. IP Protection: | |
| - Trademarks: Brand names, logos | |
| - Patents: Unique inventions | |
| - Copyrights: Creative works | |
| - Trade Secrets: Proprietary processes | |
| 4. Compliance: | |
| - Federal EIN | |
| - Business licenses | |
| - Industry permits | |
| - Data privacy (GDPR, CCPA) | |
| """, | |
| """ | |
| TEAM BUILDING AND OPERATIONS | |
| Building the right team: | |
| 1. Founding Team: | |
| - Complementary skills: technical, business, domain | |
| - Aligned vision and values | |
| - Equity split reflects contribution | |
| 2. Hiring Strategy: | |
| - Hire for adaptability and culture fit | |
| - Focus on critical roles first | |
| - 4-year vesting with 1-year cliff | |
| - 0.1%-10% equity based on role | |
| 3. Key Metrics by Function: | |
| - Product: DAU/MAU, retention, feature adoption | |
| - Sales: Conversion rates, cycle length, ACV | |
| - Marketing: CPL, MQLs, brand awareness | |
| - Finance: Revenue growth, margins, working capital | |
| 4. Operational Excellence: | |
| - Build MVP with core features | |
| - Define and track KPIs | |
| - Create scalable processes | |
| - Implement feedback loops | |
| """, | |
| """ | |
| BRAND DEVELOPMENT AND MARKETING | |
| Strong branding drives growth: | |
| 1. Brand Identity: | |
| - Define values, personality, voice | |
| - Create unique selling proposition | |
| - Develop consistent visual identity | |
| - Establish market positioning | |
| 2. Digital Presence: | |
| - Professional website with clear CTA | |
| - SEO optimization | |
| - Social media strategy | |
| - Content marketing calendar | |
| 3. Acquisition Channels: | |
| - Content Marketing: Thought leadership | |
| - Social Media: Platform-specific strategies | |
| - SEM: Targeted Google Ads | |
| - Email: Drip campaigns, newsletters | |
| - Partnerships: Co-marketing, affiliates | |
| 4. Key Metrics: | |
| - Website traffic and conversion rates | |
| - CAC by channel | |
| - LTV by acquisition source | |
| - NPS and customer satisfaction | |
| - Brand awareness and consideration | |
| 5. Customer Success: | |
| - Feedback loops and surveys | |
| - Customer success programs | |
| - Community building | |
| - Referral programs | |
| """ | |
| ] | |
| KNOWLEDGE_METADATA = [ | |
| {"category": "validation", "topic": "market_research", "importance": "high"}, | |
| {"category": "planning", "topic": "business_plan", "importance": "high"}, | |
| {"category": "finance", "topic": "funding", "importance": "high"}, | |
| {"category": "legal", "topic": "structure", "importance": "medium"}, | |
| {"category": "operations", "topic": "team_building", "importance": "high"}, | |
| {"category": "marketing", "topic": "branding", "importance": "medium"}, | |
| ] | |
| # Business Plan Generator | |
| class StartupBlueprintGenerator: | |
| """Main class for generating comprehensive startup blueprints""" | |
| def __init__(self, rag_system: RAGSystem): | |
| self.rag = rag_system | |
| self.templates = self._load_templates() | |
| self.model_data = {} | |
| def _load_templates(self) -> Dict[str, str]: | |
| """Load template structures""" | |
| return { | |
| "executive_summary": """## Executive Summary | |
| **Company:** {company_name} | |
| **Industry:** {industry} | |
| **Mission:** {mission} | |
| ### Problem Statement | |
| {problem_statement} | |
| ### Solution | |
| {solution} | |
| ### Market Opportunity | |
| {market_opportunity} | |
| ### Financial Highlights | |
| - Projected Revenue Year 3: {projected_revenue} | |
| - Funding Requirement: {funding_needed} | |
| - Break-even Timeline: {breakeven_timeline} | |
| """, | |
| } | |
| def generate_business_plan(self, startup_idea: StartupIdea) -> BusinessPlan: | |
| """Generate comprehensive business plan""" | |
| try: | |
| print(f"π Generating business plan for {startup_idea.name}...") | |
| exec_context = self.rag.retrieve_context( | |
| f"executive summary for {startup_idea.industry} startup", | |
| n_results=3 | |
| ) | |
| executive_summary = self.templates["executive_summary"].format( | |
| company_name=startup_idea.name, | |
| industry=startup_idea.industry, | |
| mission=f"To solve {startup_idea.problem_statement} for {startup_idea.target_market}", | |
| problem_statement=startup_idea.problem_statement, | |
| solution=startup_idea.solution, | |
| market_opportunity=f"Significant opportunity in the {startup_idea.industry} market", | |
| projected_revenue="$1M - $5M", | |
| funding_needed="$250K - $1M", | |
| breakeven_timeline="18-24 months" | |
| ) | |
| business_plan = BusinessPlan( | |
| executive_summary=executive_summary, | |
| company_description=f"{startup_idea.name} - {startup_idea.description}", | |
| market_analysis=f"The {startup_idea.industry} market presents significant opportunities.", | |
| organization_management="Founding team with complementary skills.", | |
| service_product_line=startup_idea.solution, | |
| marketing_sales="Multi-channel customer acquisition strategy.", | |
| funding_request="Seeking seed funding for product development and market expansion.", | |
| financial_projections={ | |
| "revenue_forecast": {"year_1": 100000, "year_2": 500000, "year_3": 1500000}, | |
| "key_metrics": {"cac": 50, "ltv": 500} | |
| } | |
| ) | |
| print("β Business plan generated") | |
| return business_plan | |
| except Exception as e: | |
| print(f"β Error: {e}") | |
| return self._generate_fallback_plan(startup_idea) | |
| def _generate_fallback_plan(self, idea: StartupIdea) -> BusinessPlan: | |
| """Fallback business plan""" | |
| return BusinessPlan( | |
| executive_summary=f"**{idea.name}** addresses {idea.problem_statement}.", | |
| company_description=f"{idea.name} serves {idea.target_market}.", | |
| market_analysis=f"The {idea.industry} market has growth opportunities.", | |
| organization_management="Experienced founding team.", | |
| service_product_line=idea.solution, | |
| marketing_sales="Digital marketing focused strategy.", | |
| funding_request="Seeking seed funding.", | |
| financial_projections={"revenue_forecast": {"year_1": 100000}} | |
| ) | |
| # Flashcards Generator | |
| class FlashcardsGenerator: | |
| """Generate learning flashcards""" | |
| def __init__(self, rag_system: RAGSystem): | |
| self.rag = rag_system | |
| self.flashcards_db = [] | |
| def generate_flashcards(self, topic: str, count: int = 10) -> List[Flashcard]: | |
| """Generate flashcards for topic""" | |
| try: | |
| print(f"π Generating {count} flashcards for {topic}...") | |
| qa_patterns = self._get_qa_patterns(topic) | |
| flashcards = [] | |
| for pattern in qa_patterns[:count]: | |
| flashcard = Flashcard( | |
| id=str(uuid.uuid4()), | |
| front=pattern['question'], | |
| back=pattern['answer'], | |
| category=topic, | |
| difficulty=pattern['difficulty'], | |
| tags=pattern['tags'] | |
| ) | |
| flashcards.append(flashcard) | |
| self.flashcards_db.extend(flashcards) | |
| print(f"β Generated {len(flashcards)} flashcards") | |
| return flashcards | |
| except Exception as e: | |
| print(f"β Error: {e}") | |
| return [] | |
| def _get_qa_patterns(self, topic: str) -> List[Dict]: | |
| """Get Q&A patterns""" | |
| patterns = { | |
| 'SaaS': [ | |
| { | |
| 'question': 'What are key SaaS metrics?', | |
| 'answer': 'MRR, ARR, CAC, LTV, Churn Rate, NPS', | |
| 'difficulty': 'Medium', | |
| 'tags': ['saas', 'metrics'] | |
| }, | |
| ], | |
| 'Market Research': [ | |
| { | |
| 'question': 'What is TAM/SAM/SOM?', | |
| 'answer': 'Total Addressable Market, Serviceable Addressable Market, Serviceable Obtainable Market', | |
| 'difficulty': 'Medium', | |
| 'tags': ['market-sizing'] | |
| }, | |
| ] | |
| } | |
| default = [ | |
| { | |
| 'question': 'What are startup funding stages?', | |
| 'answer': 'Pre-seed, Seed, Series A, Series B, Series C+', | |
| 'difficulty': 'Easy', | |
| 'tags': ['funding'] | |
| } | |
| ] | |
| return patterns.get(topic, default) + default[:5] | |
| # Roadmap Generator | |
| class RoadmapGenerator: | |
| """Generate startup roadmaps""" | |
| def __init__(self, rag_system: RAGSystem): | |
| self.rag = rag_system | |
| self.roadmap_templates = self._load_templates() | |
| def _load_templates(self) -> Dict[str, List[Dict]]: | |
| """Load roadmap templates""" | |
| return { | |
| 'pre_launch': [ | |
| { | |
| 'phase': 'Ideation & Validation', | |
| 'duration': '1-2 months', | |
| 'milestones': [ | |
| 'Problem identification', | |
| 'Market research', | |
| 'Customer interviews', | |
| 'MVP wireframes' | |
| ] | |
| }, | |
| ], | |
| 'launch': [ | |
| { | |
| 'phase': 'Go-to-Market', | |
| 'duration': '2-3 months', | |
| 'milestones': [ | |
| 'Brand development', | |
| 'Marketing strategy', | |
| 'Sales process', | |
| 'Launch campaign' | |
| ] | |
| }, | |
| ], | |
| } | |
| def generate_roadmap(self, startup_idea: StartupIdea, phases: List[str] = None) -> Dict[str, Any]: | |
| """Generate roadmap""" | |
| try: | |
| print(f"πΊοΈ Generating roadmap for {startup_idea.name}...") | |
| if phases is None: | |
| phases = ['pre_launch', 'launch'] | |
| roadmap = { | |
| 'startup_name': startup_idea.name, | |
| 'industry': startup_idea.industry, | |
| 'phases': [], | |
| 'total_timeline': '6-12 months', | |
| 'key_metrics': ['CAC', 'LTV', 'MRR'] | |
| } | |
| current_month = 0 | |
| for phase_name in phases: | |
| if phase_name in self.roadmap_templates: | |
| for phase in self.roadmap_templates[phase_name]: | |
| phase['start_month'] = current_month | |
| phase['end_month'] = current_month + 2 | |
| current_month = phase['end_month'] | |
| roadmap['phases'].append(phase) | |
| print("β Roadmap generated") | |
| return roadmap | |
| except Exception as e: | |
| print(f"β Error: {e}") | |
| return self._generate_fallback(startup_idea) | |
| def _generate_fallback(self, idea: StartupIdea) -> Dict[str, Any]: | |
| """Fallback roadmap""" | |
| return { | |
| 'startup_name': idea.name, | |
| 'industry': idea.industry, | |
| 'phases': [ | |
| { | |
| 'phase': 'Planning', | |
| 'duration': '1-2 months', | |
| 'milestones': ['Research', 'Planning'], | |
| 'start_month': 0, | |
| 'end_month': 2 | |
| } | |
| ], | |
| 'total_timeline': '3-6 months', | |
| 'key_metrics': ['Revenue', 'Customers'] | |
| } | |
| def export_roadmap(self, roadmap_data: Dict[str, Any], format: str = 'markdown') -> str: | |
| """Export roadmap""" | |
| if format == 'markdown': | |
| md = f"# πΊοΈ {roadmap_data['startup_name']} Roadmap\n\n" | |
| md += f"**Industry:** {roadmap_data['industry']}\n\n" | |
| for phase in roadmap_data['phases']: | |
| md += f"## {phase['phase']}\n" | |
| md += f"**Duration:** {phase['duration']}\n\n" | |
| md += "**Milestones:**\n" | |
| for milestone in phase['milestones']: | |
| md += f"- {milestone}\n" | |
| md += "\n" | |
| return md | |
| return json.dumps(roadmap_data, indent=2) | |
| # Initialize Global Systems | |
| print("π Starting AI Startup Roadmap Generator...") | |
| try: | |
| rag_system = RAGSystem() | |
| rag_system.initialize_collection() | |
| if rag_system.collection and rag_system.collection.count() == 0: | |
| print("π Populating knowledge base...") | |
| chunks_added = rag_system.add_documents(STARTUP_KNOWLEDGE_BASE, KNOWLEDGE_METADATA) | |
| print(f"β Added {chunks_added} chunks") | |
| else: | |
| count = rag_system.collection.count() if rag_system.collection else 0 | |
| print(f"π Using existing knowledge base with {count} documents") | |
| except Exception as e: | |
| print(f"β Error initializing RAG: {e}") | |
| rag_system = None | |
| try: | |
| blueprint_generator = StartupBlueprintGenerator(rag_system) if rag_system else None | |
| flashcards_gen = FlashcardsGenerator(rag_system) if rag_system else None | |
| roadmap_gen = RoadmapGenerator(rag_system) if rag_system else None | |
| print("β Generators initialized") | |
| except Exception as e: | |
| print(f"β Error initializing generators: {e}") | |
| # Gradio Interface Functions | |
| def generate_startup_blueprint(name, industry, target_market, problem, solution, value_prop): | |
| """Main blueprint generation function""" | |
| if not all([name, industry, problem, solution]): | |
| return ( | |
| "β **Error:** Please fill in all required fields.", | |
| "", "", "" | |
| ) | |
| try: | |
| idea = StartupIdea( | |
| name=name, | |
| description=f"{name} - {solution}", | |
| industry=industry, | |
| target_market=target_market or f"{industry} customers", | |
| problem_statement=problem, | |
| solution=solution, | |
| unique_value_proposition=value_prop or "Innovative solution" | |
| ) | |
| print(f"π Processing {name}") | |
| if blueprint_generator: | |
| business_plan = blueprint_generator.generate_business_plan(idea) | |
| business_plan_text = business_plan.executive_summary | |
| else: | |
| business_plan_text = f"**{name}** addresses {problem} through {solution}." | |
| if flashcards_gen: | |
| flashcards = flashcards_gen.generate_flashcards(industry, 5) | |
| flashcards_text = "\n\n".join([ | |
| f"**Q:** {fc.front}\n**A:** {fc.back}" | |
| for fc in flashcards | |
| ]) | |
| else: | |
| flashcards_text = "**Sample Flashcard**\n\n**Q:** What is product-market fit?\n**A:** When product satisfies strong market demand." | |
| if roadmap_gen: | |
| roadmap = roadmap_gen.generate_roadmap(idea) | |
| roadmap_text = roadmap_gen.export_roadmap(roadmap, 'markdown') | |
| else: | |
| roadmap_text = f"# Roadmap for {name}\n\n## Phase 1: Planning\n- Market research\n- Business plan" | |
| summary = f"""# π Blueprint Generated! | |
| **Startup:** {name} | |
| **Industry:** {industry} | |
| **Target:** {target_market or f"{industry} customers"} | |
| ## π Assessment: 85/100 | |
| ### β Strengths: | |
| - Clear problem identification | |
| - Well-defined solution | |
| - Strong market positioning | |
| ### π‘ Next Steps: | |
| 1. Validate with 50+ customer interviews | |
| 2. Build MVP with core features | |
| 3. Track CAC and LTV metrics | |
| 4. Prepare for seed funding | |
| *Generated: {datetime.now().strftime("%B %d, %Y")}* | |
| """ | |
| print(f"β Blueprint complete for {name}") | |
| return summary, business_plan_text, flashcards_text, roadmap_text | |
| except Exception as e: | |
| error_msg = f"β **Error:** {str(e)}\n\nPlease try again." | |
| print(f"β Error: {e}") | |
| return error_msg, "", "", "" | |
| def generate_flashcards_only(category): | |
| """Generate flashcards only""" | |
| try: | |
| if flashcards_gen: | |
| flashcards = flashcards_gen.generate_flashcards(category, 8) | |
| return "\n\n".join([ | |
| f"**Q:** {fc.front}\n**A:** {fc.back}\n*Difficulty: {fc.difficulty}*" | |
| for fc in flashcards | |
| ]) | |
| else: | |
| return f"**{category} Flashcards**\n\n**Q:** Sample question\n**A:** Sample answer" | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| def generate_roadmap_only(startup_name, industry_type): | |
| """Generate roadmap only""" | |
| try: | |
| idea = StartupIdea( | |
| name=startup_name or "Sample Startup", | |
| description="Sample", | |
| industry=industry_type, | |
| target_market="General", | |
| problem_statement="Problem", | |
| solution="Solution", | |
| unique_value_proposition="Value" | |
| ) | |
| if roadmap_gen: | |
| roadmap = roadmap_gen.generate_roadmap(idea) | |
| return roadmap_gen.export_roadmap(roadmap, 'markdown') | |
| else: | |
| return f"# {startup_name} Roadmap\n\n## Planning Phase\n- Research\n- Development" | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| # Create Gradio Interface | |
| print("π¨ Creating interface...") | |
| custom_css = """ | |
| .gradio-container { | |
| max-width: 1200px !important; | |
| } | |
| """ | |
| with gr.Blocks(title="π AI Startup Roadmap Generator", theme=gr.themes.Soft(), css=custom_css) as demo: | |
| gr.Markdown(""" | |
| # π AI Startup Roadmap Generator | |
| ### Transform Your Startup Ideas into Comprehensive Business Plans | |
| **Powered by RAG Technology & ChromaDB** | |
| """) | |
| with gr.Tabs(): | |
| with gr.TabItem("π’ Complete Blueprint"): | |
| gr.Markdown("### π Enter Startup Information") | |
| with gr.Row(): | |
| with gr.Column(): | |
| startup_name = gr.Textbox( | |
| label="Startup Name *", | |
| placeholder="e.g., EcoTrack" | |
| ) | |
| industry = gr.Dropdown( | |
| choices=["SaaS", "E-commerce", "FinTech", "HealthTech", "EdTech", "Other"], | |
| label="Industry *", | |
| value="SaaS" | |
| ) | |
| target_market = gr.Textbox( | |
| label="Target Market", | |
| placeholder="e.g., Small businesses", | |
| lines=2 | |
| ) | |
| with gr.Column(): | |
| problem_statement = gr.Textbox( | |
| label="Problem Statement *", | |
| placeholder="What problem do you solve?", | |
| lines=3 | |
| ) | |
| solution = gr.Textbox( | |
| label="Solution *", | |
| placeholder="How do you solve it?", | |
| lines=3 | |
| ) | |
| value_proposition = gr.Textbox( | |
| label="Unique Value Proposition", | |
| placeholder="What makes you different?", | |
| lines=2 | |
| ) | |
| generate_btn = gr.Button("π Generate Blueprint", variant="primary", size="lg") | |
| gr.Markdown("### π Generated Blueprint") | |
| with gr.Row(): | |
| with gr.Column(): | |
| summary_output = gr.Markdown(label="Summary") | |
| with gr.Column(): | |
| business_plan_output = gr.Markdown(label="Business Plan") | |
| with gr.Row(): | |
| with gr.Column(): | |
| flashcards_output = gr.Markdown(label="Flashcards") | |
| with gr.Column(): | |
| roadmap_output = gr.Markdown(label="Roadmap") | |
| generate_btn.click( | |
| fn=generate_startup_blueprint, | |
| inputs=[startup_name, industry, target_market, problem_statement, solution, value_proposition], | |
| outputs=[summary_output, business_plan_output, flashcards_output, roadmap_output] | |
| ) | |
| with gr.TabItem("π Flashcards"): | |
| gr.Markdown("### π Learning Flashcards") | |
| flashcard_category = gr.Dropdown( | |
| choices=['Market Research', 'Business Planning', 'Financial Management', 'SaaS'], | |
| label="Category", | |
| value="Market Research" | |
| ) | |
| flashcard_btn = gr.Button("π Generate", variant="primary") | |
| flashcard_only_output = gr.Markdown() | |
| flashcard_btn.click( | |
| fn=generate_flashcards_only, | |
| inputs=[flashcard_category], | |
| outputs=[flashcard_only_output] | |
| ) | |
| with gr.TabItem("πΊοΈ Roadmap"): | |
| gr.Markdown("### πΊοΈ Startup Roadmap") | |
| with gr.Row(): | |
| roadmap_startup_name = gr.Textbox(label="Startup Name", value="My Startup") | |
| roadmap_industry = gr.Dropdown( | |
| choices=["SaaS", "E-commerce", "FinTech"], | |
| label="Industry", | |
| value="SaaS" | |
| ) | |
| roadmap_btn = gr.Button("πΊοΈ Generate", variant="primary") | |
| roadmap_only_output = gr.Markdown() | |
| roadmap_btn.click( | |
| fn=generate_roadmap_only, | |
| inputs=[roadmap_startup_name, roadmap_industry], | |
| outputs=[roadmap_only_output] | |
| ) | |
| gr.Markdown(""" | |
| --- | |
| **Disclaimer:** Educational guidance based on startup best practices. Consult professionals for specific advice. | |
| """) | |
| # Launch Application | |
| if __name__ == "__main__": | |
| port = int(os.getenv("PORT", 7860)) | |
| print(f""" | |
| π AI Startup Roadmap Generator Ready! | |
| π Port: {port} | |
| π RAG: {"β Active" if rag_system else "β Fallback"} | |
| π Launching... | |
| """) | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=port, | |
| share=False, | |
| show_error=True | |
| ) |