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: | |
| # Try to get existing collection first | |
| 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}") | |
| # Fallback: create new collection | |
| 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: | |
| # Split documents into chunks | |
| all_chunks = [] | |
| all_metadatas = [] | |
| for i, doc in enumerate(documents): | |
| chunks = self.text_splitter.split_text(doc) | |
| all_chunks.extend(chunks) | |
| # Add metadata for each chunk | |
| 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() | |
| }) | |
| # Generate embeddings | |
| print(f"π Generating embeddings for {len(all_chunks)} chunks...") | |
| embeddings = self.embedding_model.encode(all_chunks).tolist() | |
| # Add to collection | |
| 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: | |
| # Generate query embedding | |
| query_embedding = self.embedding_model.encode([query]).tolist()[0] | |
| # Query the collection | |
| results = self.collection.query( | |
| query_embeddings=[query_embedding], | |
| n_results=min(n_results, self.collection.count()) | |
| ) | |
| # Format results | |
| 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: | |
| # Combine context | |
| context_text = "\n".join([ctx["content"] for ctx in context]) | |
| # Generate structured response based on query type | |
| 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 | |
| - Validate assumptions through customer interviews and surveys | |
| - Track key metrics: CAC, LTV, market penetration rate | |
| """ | |
| elif "business plan" in query_lower: | |
| return f""" | |
| **Business Plan Development:** | |
| Essential components based on successful startups: | |
| {context[:500]}... | |
| **Core Sections to Include:** | |
| - Executive Summary (mission, product, competitive advantages) | |
| - Market Analysis (industry overview, target market, competition) | |
| - Financial Projections (revenue forecasts, expense budgets, break-even analysis) | |
| - Marketing Strategy (customer acquisition, pricing model, sales process) | |
| - Funding Requirements (capital needs, use of funds, ROI projections) | |
| """ | |
| elif "funding" in query_lower or "investment" in query_lower: | |
| return f""" | |
| **Funding Strategy:** | |
| {context[:500]}... | |
| **Funding Options:** | |
| - Bootstrapping: Use personal savings (most common first step) | |
| - Angel Investors: High-net-worth individuals + mentorship | |
| - Venture Capital: Pooled funds for high-growth startups | |
| - Crowdfunding: Small amounts from many people online | |
| - Grants/Loans: Government programs and bank financing | |
| **Key Preparation Steps:** | |
| - Develop compelling pitch deck (10-12 slides) | |
| - Prepare detailed financial projections (3-5 years) | |
| - Build prototype or MVP to demonstrate traction | |
| - Gather customer validation and testimonials | |
| """ | |
| else: | |
| return f""" | |
| **Strategic Guidance:** | |
| {context[:400]}... | |
| **Key Considerations:** | |
| - Validate your assumptions with real market data | |
| - Focus on solving a genuine problem for a specific customer segment | |
| - Build strong unit economics (LTV/CAC ratio > 3:1) | |
| - Assemble a complementary founding team with diverse skills | |
| - Develop a clear go-to-market strategy | |
| **Next Steps:** | |
| - Conduct customer discovery interviews | |
| - Create a minimum viable product (MVP) | |
| - Test your pricing model with early customers | |
| - Build financial projections and fundraising plan | |
| """ | |
| # 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. Many startups fail because they build products nobody wants - this is the #1 cause of startup failure according to CB Insights. | |
| 2. Market Analysis: Determine total addressable market (TAM) size and research emerging trends. Use frameworks like TAM/SAM/SOM: | |
| - TAM (Total Addressable Market): Total market demand for a product/service | |
| - SAM (Serviceable Addressable Market): The portion of TAM targeted by your products and services | |
| - SOM (Serviceable Obtainable Market): The portion of SAM that you can realistically capture | |
| 3. Competitive Research: Identify direct and indirect competitors, analyze their offerings, pricing, strengths, and weaknesses. Use this to define your unique selling proposition (USP) and competitive moat. | |
| 4. Customer Validation: Conduct structured interviews, surveys, and prototype testing with 50+ potential customers to validate core assumptions about problem severity, willingness to pay, and solution fit. | |
| 5. Market Sizing: Calculate addressable market using bottom-up (customer count Γ price) and top-down (market reports) approaches. | |
| Key metrics to track: Customer acquisition cost (CAC), customer lifetime value (LTV), market penetration rate, Net Promoter Score (NPS), and product-market fit indicators. | |
| """, | |
| """ | |
| BUSINESS PLAN DEVELOPMENT | |
| A comprehensive business plan serves as both internal roadmap and external communication tool for investors: | |
| 1. Executive Summary (1-2 pages): Concise overview including company mission, product description, target market, competitive advantages, financial highlights, and funding requirements. This is often the only section investors read initially. | |
| 2. Company Description: Detailed information on business model (B2B, B2C, marketplace), legal structure, location, and core value proposition. Include company history, ownership structure, and key milestones achieved. | |
| 3. Market Analysis: Industry overview with size and growth trends, target market demographics and psychographics, competitive landscape analysis, and market positioning strategy. | |
| 4. Organization & Management: Legal structure (LLC, C-Corp, etc.), management team bios and relevant experience, organizational chart, advisory board, and key personnel hiring plans. | |
| 5. Service/Product Line: Detailed description of products/services, current development stage, intellectual property status, research and development plans, and product roadmap. | |
| 6. Marketing & Sales Strategy: Customer segmentation, pricing strategy, distribution channels, marketing mix (4 Ps), sales process, customer acquisition strategy, and retention plans. | |
| 7. Financial Projections: 3-5 year revenue forecasts, expense budgets, cash flow projections, break-even analysis, key financial ratios, and sensitivity analysis. | |
| 8. Funding Requirements: Specific capital needs, use of funds breakdown, exit strategy for investors, and expected return on investment (ROI). | |
| """, | |
| """ | |
| FUNDING AND FINANCIAL MANAGEMENT | |
| Securing and managing finances strategically is critical for startup survival and growth: | |
| 1. Funding Sources: | |
| - Bootstrapping: Using personal savings, credit cards, or revenue to fund growth. Maintains full control but limits scale. | |
| - Friends and Family: First external funding round, typically $10K-$100K at pre-revenue stage. | |
| - Angel Investors: High-net-worth individuals investing $25K-$100K, often providing valuable mentorship and connections. | |
| - Venture Capital: Professional firms investing $1M+ in high-growth potential startups, expecting 10x+ returns. | |
| - Crowdfunding: Platforms like Kickstarter, Indiegogo for product launches or equity crowdfunding via Republic, SeedInvest. | |
| - Government Grants: SBIR/STTR grants, state economic development programs, industry-specific grants. | |
| 2. Financial Management Best Practices: | |
| - Separate business and personal finances immediately | |
| - Implement robust accounting systems (QuickBooks, FreshBooks) | |
| - Track key metrics: Monthly Recurring Revenue (MRR), Annual Recurring Revenue (ARR), gross margins, burn rate, runway | |
| - Maintain 6-12 months of operating expenses in cash reserves | |
| - Regular financial reporting and board updates | |
| 3. Key Financial Metrics: | |
| - Burn Rate: Monthly cash expenditure | |
| - Runway: Months of cash remaining at current burn rate | |
| - Customer Acquisition Cost (CAC): Total sales and marketing expenses Γ· number of new customers | |
| - Customer Lifetime Value (LTV): Average revenue per customer Γ gross margin % Γ average customer lifespan | |
| - LTV/CAC Ratio: Should be 3:1 or higher for sustainable unit economics | |
| 4. Fundraising Process: | |
| - Prepare comprehensive pitch deck (10-12 slides) | |
| - Create detailed financial model with scenarios | |
| - Build investor pipeline with warm introductions | |
| - Practice pitch extensively before investor meetings | |
| - Negotiate terms carefully (valuation, board seats, liquidation preferences) | |
| """, | |
| """ | |
| LEGAL STRUCTURE AND COMPLIANCE | |
| Choosing the right legal foundation protects founders and enables future growth: | |
| 1. Business Structure Options: | |
| - Sole Proprietorship: Simplest form, personal liability for all debts and obligations | |
| - Partnership: Shared ownership and liability, requires partnership agreement | |
| - Limited Liability Company (LLC): Personal asset protection, flexible tax options, simpler compliance | |
| - C-Corporation: Strongest liability protection, can issue stock to investors, double taxation | |
| - S-Corporation: Pass-through taxation, limited to 100 shareholders, all must be US citizens | |
| 2. Delaware C-Corp Advantages for Startups: | |
| - Well-established corporate law and court system | |
| - Investor familiarity and preference | |
| - Flexible stock structure (common, preferred) | |
| - Strong director and officer protection | |
| - Easy to convert from LLC if needed | |
| 3. Essential Legal Documents: | |
| - Articles of Incorporation/Organization filed with state | |
| - Corporate bylaws or operating agreement | |
| - Founders' Agreement: equity split, vesting schedules, intellectual property assignment, roles and responsibilities | |
| - Employee agreements: offer letters, non-disclosure agreements (NDAs), invention assignment | |
| - Customer agreements: terms of service, privacy policy, service level agreements (SLAs) | |
| 4. Intellectual Property Protection: | |
| - Trademarks: Protect brand names, logos, and slogans ($275-$325 per class) | |
| - Patents: Protect unique inventions and processes ($5,000-$15,000+ including attorney fees) | |
| - Copyrights: Protect creative works like software code, marketing materials | |
| - Trade Secrets: Protect proprietary processes, customer lists, algorithms through confidentiality | |
| 5. Compliance Requirements: | |
| - Federal EIN (Employer Identification Number) | |
| - State and local business licenses | |
| - Industry-specific permits and certifications | |
| - Sales tax registration if selling products | |
| - Employment law compliance (workers' compensation, unemployment insurance) | |
| - Data privacy compliance (GDPR, CCPA, HIPAA if applicable) | |
| """, | |
| """ | |
| TEAM BUILDING AND OPERATIONS | |
| Building the right team and operational foundation scales with your startup: | |
| 1. Founding Team Composition: | |
| - Complementary skills covering key functions: technical, business development, domain expertise | |
| - Diverse perspectives and backgrounds for better decision-making | |
| - Aligned vision, values, and commitment to long-term success | |
| - Previous startup experience or relevant industry expertise preferred | |
| - Equity split should reflect contribution, risk, and future value creation | |
| 2. Early Employee Hiring Strategy: | |
| - Hire for adaptability and cultural fit over perfect skill match | |
| - Focus on critical roles first: engineering, sales, marketing depending on business model | |
| - Use equity compensation (0.1%-10% depending on role and stage) to attract talent | |
| - Implement 4-year vesting schedules with 1-year cliffs | |
| - Create strong onboarding processes and company culture documentation | |
| 3. Operational Excellence: | |
| - Develop Minimum Viable Product (MVP) with core features only | |
| - Establish sales and distribution channels appropriate for target market | |
| - Define and track Key Performance Indicators (KPIs) for each business function | |
| - Create scalable business processes using automation tools | |
| - Implement customer support systems and feedback loops | |
| - Build quality assurance and testing procedures | |
| 4. Key Metrics to Track by Function: | |
| - Product: Daily/Monthly Active Users (DAU/MAU), feature adoption rates, user retention cohorts | |
| - Sales: Lead conversion rates, sales cycle length, average contract value (ACV) | |
| - Marketing: Cost per lead (CPL), marketing qualified leads (MQLs), brand awareness metrics | |
| - Operations: Customer satisfaction scores, support ticket resolution time, operational efficiency ratios | |
| - Finance: Revenue growth rate, gross margins, working capital management | |
| 5. Scaling Considerations: | |
| - Document processes and procedures before they become bottlenecks | |
| - Invest in tools and systems that grow with the company | |
| - Build management capabilities and delegation skills | |
| - Create career development paths to retain top talent | |
| - Establish board of directors and advisory board for guidance | |
| """, | |
| """ | |
| BRAND DEVELOPMENT AND MARKETING | |
| Strong branding and customer acquisition strategy drives sustainable growth: | |
| 1. Brand Identity Development: | |
| - Define brand values, personality, and voice that resonates with target customers | |
| - Create unique selling proposition (USP) that differentiates from competitors | |
| - Develop consistent visual identity: logo, color palette, typography, imagery style | |
| - Establish brand positioning in the market landscape | |
| - Create brand guidelines document for consistent application | |
| 2. Digital Presence Foundation: | |
| - Secure primary domain and social media handles across platforms | |
| - Build professional website with clear value proposition and calls-to-action | |
| - Optimize for search engines (SEO) with relevant keywords and quality content | |
| - Implement analytics tracking (Google Analytics, Mixpanel) from day one | |
| - Create content calendar and editorial strategy | |
| 3. Customer Acquisition Channels: | |
| - Content Marketing: Blog posts, whitepapers, case studies, webinars to establish thought leadership | |
| - Social Media Marketing: Platform-specific strategies for LinkedIn (B2B), Instagram (B2C), Twitter (tech) | |
| - Search Engine Marketing: Google Ads, Bing Ads with targeted keywords and landing pages | |
| - Email Marketing: Newsletter campaigns, drip sequences, automated workflows | |
| - Partnership Marketing: Co-marketing with complementary businesses, affiliate programs | |
| - Public Relations: Media outreach, press releases, industry award submissions | |
| 4. Marketing Metrics and Attribution: | |
| - Website traffic: unique visitors, page views, bounce rate, session duration | |
| - Conversion funnel: visitor-to-lead, lead-to-customer conversion rates | |
| - Channel performance: CAC by channel, LTV by acquisition source | |
| - Content performance: engagement rates, social shares, backlink acquisition | |
| - Brand metrics: brand awareness, consideration, and preference tracking | |
| 5. Customer Success and Retention: | |
| - Implement customer feedback loops: surveys, interviews, usage analytics | |
| - Create customer success programs for high-value accounts | |
| - Build community around your product: user groups, forums, events | |
| - Develop referral and loyalty programs to encourage word-of-mouth marketing | |
| - Monitor and improve Net Promoter Score (NPS) and customer satisfaction metrics | |
| """ | |
| ] | |
| # Metadata for knowledge base | |
| 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 for different blueprint sections""" | |
| 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} | |
| ### Competitive Advantage | |
| {unique_value_proposition} | |
| """, | |
| "market_analysis": """ | |
| ## Market Analysis | |
| ### Industry Overview | |
| {industry_overview} | |
| ### Target Market | |
| {target_market} | |
| ### Market Size Analysis | |
| - **Total Addressable Market (TAM):** {tam} | |
| - **Serviceable Addressable Market (SAM):** {sam} | |
| - **Serviceable Obtainable Market (SOM):** {som} | |
| ### Competitive Landscape | |
| {competitive_analysis} | |
| ### Market Trends | |
| - Growing demand for digital solutions | |
| - Increasing adoption in target demographics | |
| - Favorable regulatory environment | |
| """, | |
| "financial_plan": """ | |
| ## Financial Plan & Projections | |
| ### Revenue Model | |
| {revenue_model} | |
| ### Key Financial Metrics | |
| - **Customer Acquisition Cost (CAC):** {cac} | |
| - **Customer Lifetime Value (LTV):** {ltv} | |
| - **LTV/CAC Ratio:** {ltv_cac_ratio} | |
| - **Monthly Recurring Revenue (MRR):** {mrr} | |
| ### 3-Year Financial Forecast | |
| | Year | Revenue | Expenses | Net Income | | |
| |------|---------|----------|------------| | |
| | 1 | $100K | $150K | ($50K) | | |
| | 2 | $500K | $400K | $100K | | |
| | 3 | $1.5M | $800K | $700K | | |
| ### Funding Requirements | |
| {funding_requirements} | |
| """, | |
| "operations_plan": """ | |
| ## Operations & Implementation Plan | |
| ### Team Structure | |
| {team_structure} | |
| ### Key Processes | |
| {key_processes} | |
| ### Technology Stack | |
| {technology_stack} | |
| ### Milestones & Timeline | |
| {milestones} | |
| ### Risk Management | |
| - Market risk mitigation strategies | |
| - Operational contingency plans | |
| - Financial risk management | |
| - Competitive response plans | |
| """ | |
| } | |
| def generate_business_plan(self, startup_idea: StartupIdea) -> BusinessPlan: | |
| """Generate comprehensive business plan using RAG context""" | |
| try: | |
| print(f"π Generating business plan for {startup_idea.name}...") | |
| # Get relevant context for each section | |
| exec_context = self.rag.retrieve_context( | |
| f"executive summary for {startup_idea.industry} startup", | |
| n_results=3 | |
| ) | |
| market_context = self.rag.retrieve_context( | |
| f"market analysis {startup_idea.industry} {startup_idea.target_market}", | |
| n_results=3 | |
| ) | |
| financial_context = self.rag.retrieve_context( | |
| f"financial planning funding {startup_idea.industry}", | |
| n_results=3 | |
| ) | |
| # Generate each section | |
| executive_summary = self._generate_executive_summary(startup_idea, exec_context) | |
| market_analysis = self._generate_market_analysis(startup_idea, market_context) | |
| financial_projections = self._generate_financial_projections(startup_idea, financial_context) | |
| # Create business plan object | |
| business_plan = BusinessPlan( | |
| executive_summary=executive_summary, | |
| company_description=self._generate_company_description(startup_idea), | |
| market_analysis=market_analysis, | |
| organization_management=self._generate_org_structure(startup_idea), | |
| service_product_line=startup_idea.solution, | |
| marketing_sales=self._generate_marketing_plan(startup_idea), | |
| funding_request=self._generate_funding_request(startup_idea), | |
| financial_projections=financial_projections | |
| ) | |
| self.model_data['business_plan'] = business_plan | |
| print("β Business plan generated successfully") | |
| return business_plan | |
| except Exception as e: | |
| print(f"β Error generating business plan: {e}") | |
| # Return fallback business plan | |
| return self._generate_fallback_business_plan(startup_idea) | |
| def _generate_executive_summary(self, idea: StartupIdea, context: List[Dict]) -> str: | |
| """Generate executive summary with RAG context""" | |
| return self.templates["executive_summary"].format( | |
| company_name=idea.name, | |
| industry=idea.industry, | |
| mission=f"To solve {idea.problem_statement} for {idea.target_market}", | |
| problem_statement=idea.problem_statement, | |
| solution=idea.solution, | |
| market_opportunity=f"Significant opportunity in the growing {idea.industry} market", | |
| projected_revenue="$1M - $5M", | |
| funding_needed="$250K - $1M", | |
| breakeven_timeline="18-24 months", | |
| unique_value_proposition=idea.unique_value_proposition | |
| ) | |
| def _generate_market_analysis(self, idea: StartupIdea, context: List[Dict]) -> str: | |
| """Generate market analysis with RAG context""" | |
| return self.templates["market_analysis"].format( | |
| industry_overview=f"The {idea.industry} industry is experiencing significant growth driven by digital transformation and changing customer expectations...", | |
| target_market=idea.target_market, | |
| tam="$10B+ (Global market size)", | |
| sam="$1B+ (Addressable market)", | |
| som="$100M+ (Obtainable market share)", | |
| competitive_analysis="Key competitors include established players and emerging startups. Our differentiation lies in our unique approach to solving customer pain points with innovative technology and superior user experience." | |
| ) | |
| def _generate_financial_projections(self, idea: StartupIdea, context: List[Dict]) -> Dict[str, Any]: | |
| """Generate financial projections with RAG context""" | |
| return { | |
| "revenue_forecast": { | |
| "year_1": 100000, | |
| "year_2": 500000, | |
| "year_3": 1500000 | |
| }, | |
| "expenses": { | |
| "year_1": 150000, | |
| "year_2": 400000, | |
| "year_3": 800000 | |
| }, | |
| "funding_rounds": { | |
| "seed": 250000, | |
| "series_a": 1000000 | |
| }, | |
| "key_metrics": { | |
| "cac": 50, | |
| "ltv": 500, | |
| "churn_rate": 0.05, | |
| "gross_margin": 0.80 | |
| } | |
| } | |
| def _generate_company_description(self, idea: StartupIdea) -> str: | |
| return f""" | |
| **{idea.name}** is an innovative {idea.industry} company that {idea.description.lower()}. | |
| **Our Mission:** To transform how {idea.target_market} solve {idea.problem_statement.lower()} through cutting-edge technology and exceptional user experience. | |
| **Our Solution:** {idea.solution} | |
| **Unique Value Proposition:** {idea.unique_value_proposition} | |
| **Target Market:** We serve {idea.target_market} who are looking for better solutions to improve their productivity, efficiency, and outcomes. | |
| """ | |
| def _generate_org_structure(self, idea: StartupIdea) -> str: | |
| return """ | |
| ## Organizational Structure | |
| **Legal Structure:** Delaware C-Corporation (recommended for funding) | |
| **Founding Team:** | |
| - **CEO/Founder:** Vision, strategy, fundraising, and business development | |
| - **CTO/Co-founder:** Technology leadership, product development, and technical strategy | |
| - **VP Marketing:** Customer acquisition, brand building, and market expansion | |
| **Advisory Board:** | |
| - Industry expert with 15+ years experience | |
| - Former startup founder with successful exit | |
| - Marketing specialist with growth expertise | |
| - Finance/funding advisor with VC connections | |
| **Hiring Plan (Next 12 months):** | |
| - Senior Software Engineer (Month 3) | |
| - Sales Manager (Month 6) | |
| - Customer Success Manager (Month 9) | |
| - Data Analyst (Month 12) | |
| """ | |
| def _generate_marketing_plan(self, idea: StartupIdea) -> str: | |
| return f""" | |
| ## Marketing & Sales Strategy | |
| **Target Customer Profile:** {idea.target_market} | |
| **Go-to-Market Strategy:** | |
| 1. **Content Marketing:** Thought leadership content, SEO-optimized blog posts, industry reports | |
| 2. **Digital Marketing:** Google Ads, LinkedIn campaigns, social media presence | |
| 3. **Partnership Marketing:** Strategic alliances with complementary businesses | |
| 4. **Sales Strategy:** Consultative selling approach with demo-driven process | |
| **Customer Acquisition Channels:** | |
| - **Inbound Marketing (40%):** SEO, content marketing, organic social media | |
| - **Paid Advertising (30%):** Google Ads, LinkedIn Ads, industry publications | |
| - **Partnerships (20%):** Referral programs, channel partnerships, integrations | |
| - **Direct Sales (10%):** Outbound prospecting, trade shows, industry events | |
| **Pricing Strategy:** | |
| - Freemium model to drive adoption | |
| - Tiered subscription plans ($29/month, $99/month, $299/month) | |
| - Enterprise custom pricing for large accounts | |
| **Sales Process:** | |
| 1. Lead generation through marketing channels | |
| 2. Qualification and discovery calls | |
| 3. Product demonstration and trial | |
| 4. Proposal and negotiation | |
| 5. Contract signing and onboarding | |
| """ | |
| def _generate_funding_request(self, idea: StartupIdea) -> str: | |
| return """ | |
| ## Funding Request | |
| **Funding Needed:** $500,000 - $1,000,000 (Seed Round) | |
| **Use of Funds:** | |
| - **Product Development (40% - $400K):** Engineering team, infrastructure, R&D | |
| - **Marketing & Customer Acquisition (35% - $350K):** Digital marketing, content, events | |
| - **Team Expansion (20% - $200K):** Key hires, recruiting, onboarding | |
| - **Operations & Overhead (5% - $50K):** Office, legal, accounting, insurance | |
| **Investment Terms:** | |
| - Seeking experienced angel investors and seed VCs | |
| - Target equity stake: 15-25% | |
| - Board composition: 2 founders, 1 investor, 1 independent | |
| - Preferred stock with standard liquidation preferences | |
| **Projected ROI:** | |
| - 3-year revenue target: $1.5M - $5M | |
| - Expected valuation at Series A: $10M - $25M | |
| - Potential exit opportunities: Strategic acquisition or IPO in 5-7 years | |
| **Milestones for Next Round:** | |
| - $100K+ Monthly Recurring Revenue (MRR) | |
| - 1,000+ paying customers | |
| - Proven unit economics (LTV/CAC > 3:1) | |
| - Strong product-market fit metrics | |
| """ | |
| def _generate_fallback_business_plan(self, idea: StartupIdea) -> BusinessPlan: | |
| """Generate basic business plan if RAG fails""" | |
| return BusinessPlan( | |
| executive_summary=f"**{idea.name}** addresses {idea.problem_statement} in the {idea.industry} industry through {idea.solution}.", | |
| company_description=f"{idea.name} serves {idea.target_market} with innovative solutions.", | |
| market_analysis=f"The {idea.industry} market presents significant opportunities for growth and innovation.", | |
| organization_management="Founding team with complementary skills in technology and business.", | |
| service_product_line=idea.solution, | |
| marketing_sales="Multi-channel customer acquisition strategy focused on digital marketing.", | |
| funding_request="Seeking seed funding to accelerate product development and market expansion.", | |
| financial_projections={ | |
| "revenue_forecast": {"year_1": 100000, "year_2": 500000, "year_3": 1500000}, | |
| "key_metrics": {"cac": 50, "ltv": 500} | |
| } | |
| ) | |
| # Flashcards Generator | |
| class FlashcardsGenerator: | |
| """Generate learning flashcards from startup knowledge""" | |
| 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 a specific topic""" | |
| try: | |
| print(f"π Generating {count} flashcards for {topic}...") | |
| # Get relevant context from RAG | |
| context = self.rag.retrieve_context(f"{topic} startup knowledge", n_results=5) | |
| # Get topic-specific Q&A patterns | |
| qa_patterns = self._get_qa_patterns(topic) | |
| flashcards = [] | |
| for i, pattern in enumerate(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 generating flashcards: {e}") | |
| return [] | |
| def _get_qa_patterns(self, topic: str) -> List[Dict]: | |
| """Get question-answer patterns for different topics""" | |
| patterns = { | |
| 'SaaS': [ | |
| { | |
| 'question': 'What are the key SaaS metrics every founder should track?', | |
| 'answer': 'Monthly Recurring Revenue (MRR), Annual Recurring Revenue (ARR), Customer Acquisition Cost (CAC), Customer Lifetime Value (LTV), Churn Rate, and Net Promoter Score (NPS)', | |
| 'difficulty': 'Medium', | |
| 'tags': ['saas', 'metrics', 'kpi'] | |
| }, | |
| { | |
| 'question': 'What is the ideal LTV/CAC ratio for a SaaS business?', | |
| 'answer': 'The ideal LTV/CAC ratio is 3:1 or higher. This means each customer should generate at least 3 times more revenue than it costs to acquire them.', | |
| 'difficulty': 'Hard', | |
| 'tags': ['saas', 'unit-economics', 'metrics'] | |
| }, | |
| ], | |
| 'Market Research': [ | |
| { | |
| 'question': 'What are the three types of market sizing?', | |
| 'answer': 'TAM (Total Addressable Market), SAM (Serviceable Addressable Market), and SOM (Serviceable Obtainable Market)', | |
| 'difficulty': 'Medium', | |
| 'tags': ['market-sizing', 'analysis'] | |
| }, | |
| { | |
| 'question': 'What is the primary goal of customer validation?', | |
| 'answer': 'To prove that there is genuine demand for your product/service before building it, reducing the risk of building something nobody wants', | |
| 'difficulty': 'Easy', | |
| 'tags': ['validation', 'product-market-fit'] | |
| }, | |
| ], | |
| 'FinTech': [ | |
| { | |
| 'question': 'What are the main regulatory considerations for FinTech startups?', | |
| 'answer': 'KYC (Know Your Customer), AML (Anti-Money Laundering), PCI DSS compliance, data privacy regulations (GDPR, CCPA), and industry-specific regulations like PSD2 in Europe', | |
| 'difficulty': 'Hard', | |
| 'tags': ['fintech', 'compliance', 'regulation'] | |
| }, | |
| ], | |
| 'E-commerce': [ | |
| { | |
| 'question': 'What are the key conversion metrics for e-commerce?', | |
| 'answer': 'Conversion rate, Average Order Value (AOV), Cart Abandonment Rate, Customer Acquisition Cost (CAC), and Return on Ad Spend (ROAS)', | |
| 'difficulty': 'Medium', | |
| 'tags': ['ecommerce', 'conversion', 'metrics'] | |
| }, | |
| ] | |
| } | |
| # Default patterns for any topic | |
| default_patterns = [ | |
| { | |
| 'question': 'What are the main startup funding stages?', | |
| 'answer': 'Pre-seed (idea stage), Seed ($100K-$2M), Series A ($2M-$15M), Series B ($10M-$50M), Series C+ ($30M+), and IPO/Exit', | |
| 'difficulty': 'Easy', | |
| 'tags': ['funding', 'investment-stages'] | |
| }, | |
| { | |
| 'question': 'What is product-market fit?', | |
| 'answer': 'The degree to which a product satisfies a strong market demand. Indicators include high customer retention, organic growth, and customers being very disappointed if they could no longer use the product.', | |
| 'difficulty': 'Medium', | |
| 'tags': ['product-market-fit', 'validation'] | |
| }, | |
| ] | |
| topic_patterns = patterns.get(topic, default_patterns) | |
| return topic_patterns + default_patterns[:max(0, 10 - len(topic_patterns))] | |
| # Roadmap Generator | |
| class RoadmapGenerator: | |
| """Generate visual roadmaps for startup milestones and timelines""" | |
| def __init__(self, rag_system: RAGSystem): | |
| self.rag = rag_system | |
| self.roadmap_templates = self._load_roadmap_templates() | |
| def _load_roadmap_templates(self) -> Dict[str, List[Dict]]: | |
| """Load roadmap templates for different startup phases""" | |
| return { | |
| 'pre_launch': [ | |
| { | |
| 'phase': 'Ideation & Validation', | |
| 'duration': '1-2 months', | |
| 'milestones': [ | |
| 'Problem identification and customer interviews', | |
| 'Market research and competitive analysis', | |
| 'Initial MVP wireframes and user testing', | |
| 'Business model validation and pricing research' | |
| ] | |
| }, | |
| { | |
| 'phase': 'Business Planning', | |
| 'duration': '2-3 months', | |
| 'milestones': [ | |
| 'Comprehensive business plan development', | |
| 'Financial projections and funding strategy', | |
| 'Legal structure setup and IP protection', | |
| 'Founding team assembly and equity agreements' | |
| ] | |
| }, | |
| { | |
| 'phase': 'MVP Development', | |
| 'duration': '3-6 months', | |
| 'milestones': [ | |
| 'Technical architecture and tech stack selection', | |
| 'Core feature development and testing', | |
| 'User feedback integration and product iteration', | |
| 'Beta user recruitment and onboarding' | |
| ] | |
| } | |
| ], | |
| 'launch': [ | |
| { | |
| 'phase': 'Go-to-Market Preparation', | |
| 'duration': '1-2 months', | |
| 'milestones': [ | |
| 'Brand identity and marketing website development', | |
| 'Content marketing strategy and asset creation', | |
| 'Sales process design and CRM implementation', | |
| 'Launch campaign planning and PR strategy' | |
| ] | |
| }, | |
| { | |
| 'phase': 'Soft Launch', | |
| 'duration': '2-3 months', | |
| 'milestones': [ | |
| 'Limited beta release to select customers', | |
| 'Customer feedback collection and analysis', | |
| 'Product refinement and bug fixes', | |
| 'Initial traction metrics and KPI tracking' | |
| ] | |
| }, | |
| { | |
| 'phase': 'Full Market Launch', | |
| 'duration': '3-6 months', | |
| 'milestones': [ | |
| 'Public launch and press release distribution', | |
| 'Customer acquisition campaign execution', | |
| 'Revenue generation and growth tracking', | |
| 'Team expansion and operational scaling' | |
| ] | |
| } | |
| ], | |
| 'growth': [ | |
| { | |
| 'phase': 'Product-Market Fit', | |
| 'duration': '6-12 months', | |
| 'milestones': [ | |
| 'Strong retention and engagement metrics', | |
| 'Sustainable customer acquisition channels', | |
| 'Positive unit economics and profitability path', | |
| 'Product expansion and feature development' | |
| ] | |
| }, | |
| { | |
| 'phase': 'Scale & Expansion', | |
| 'duration': '12-24 months', | |
| 'milestones': [ | |
| 'Series A fundraising and investor relations', | |
| 'Market expansion and new customer segments', | |
| 'Team scaling and organizational development', | |
| 'Strategic partnerships and business development' | |
| ] | |
| } | |
| ] | |
| } | |
| def generate_roadmap(self, startup_idea: StartupIdea, phases: List[str] = None) -> Dict[str, Any]: | |
| """Generate customized roadmap based on startup idea""" | |
| try: | |
| print(f"πΊοΈ Generating roadmap for {startup_idea.name}...") | |
| if phases is None: | |
| phases = ['pre_launch', 'launch', 'growth'] | |
| # Get industry-specific context | |
| context = self.rag.retrieve_context( | |
| f"startup roadmap {startup_idea.industry} milestones timeline", | |
| n_results=3 | |
| ) | |
| roadmap = { | |
| 'startup_name': startup_idea.name, | |
| 'industry': startup_idea.industry, | |
| 'phases': [], | |
| 'total_timeline': '18-36 months', | |
| 'key_metrics': self._get_key_metrics(startup_idea), | |
| 'context_insights': [ctx['content'][:200] + '...' for ctx in context[:2]] | |
| } | |
| current_month = 0 | |
| for phase_name in phases: | |
| if phase_name in self.roadmap_templates: | |
| phase_data = self.roadmap_templates[phase_name].copy() | |
| # Customize based on industry | |
| customized_phases = self._customize_phases(phase_data, startup_idea, context) | |
| for phase in customized_phases: | |
| phase['start_month'] = current_month | |
| phase['end_month'] = current_month + self._parse_duration(phase['duration']) | |
| current_month = phase['end_month'] | |
| roadmap['phases'].append(phase) | |
| print("β Roadmap generated successfully") | |
| return roadmap | |
| except Exception as e: | |
| print(f"β Error generating roadmap: {e}") | |
| return self._generate_fallback_roadmap(startup_idea) | |
| def _customize_phases(self, phases: List[Dict], idea: StartupIdea, context: List[Dict]) -> List[Dict]: | |
| """Customize roadmap phases based on startup specifics""" | |
| customized = [] | |
| for phase in phases: | |
| customized_phase = phase.copy() | |
| # Add industry-specific considerations | |
| if idea.industry.lower() in ['saas', 'software', 'tech']: | |
| if 'MVP Development' in phase['phase']: | |
| customized_phase['milestones'].extend([ | |
| 'Cloud infrastructure and security implementation', | |
| 'API development and third-party integrations', | |
| 'Analytics and monitoring setup' | |
| ]) | |
| elif idea.industry.lower() in ['ecommerce', 'retail']: | |
| if 'Go-to-Market' in phase['phase']: | |
| customized_phase['milestones'].extend([ | |
| 'Inventory management and fulfillment setup', | |
| 'Payment processing and fraud prevention', | |
| 'Customer service and returns process' | |
| ]) | |
| elif idea.industry.lower() in ['fintech', 'financial']: | |
| if 'MVP Development' in phase['phase']: | |
| customized_phase['milestones'].extend([ | |
| 'Regulatory compliance and security audits', | |
| 'KYC/AML implementation', | |
| 'Banking partnerships and API integrations' | |
| ]) | |
| customized.append(customized_phase) | |
| return customized | |
| def _parse_duration(self, duration_str: str) -> int: | |
| """Parse duration string to months""" | |
| match = re.search(r'(\d+)', duration_str) | |
| return int(match.group(1)) if match else 1 | |
| def _get_key_metrics(self, idea: StartupIdea) -> List[str]: | |
| """Get key metrics to track for the startup""" | |
| base_metrics = [ | |
| 'Customer Acquisition Cost (CAC)', | |
| 'Customer Lifetime Value (LTV)', | |
| 'Monthly Recurring Revenue (MRR)', | |
| 'User Engagement Rate', | |
| 'Market Share Growth' | |
| ] | |
| # Add industry-specific metrics | |
| if idea.industry.lower() in ['saas', 'software']: | |
| base_metrics.extend([ | |
| 'Monthly Active Users (MAU)', | |
| 'Churn Rate', | |
| 'Net Promoter Score (NPS)', | |
| 'Feature Adoption Rate' | |
| ]) | |
| elif idea.industry.lower() in ['ecommerce']: | |
| base_metrics.extend([ | |
| 'Conversion Rate', | |
| 'Average Order Value (AOV)', | |
| 'Cart Abandonment Rate', | |
| 'Return on Ad Spend (ROAS)' | |
| ]) | |
| return base_metrics[:8] # Limit to 8 key metrics | |
| def _generate_fallback_roadmap(self, idea: StartupIdea) -> Dict[str, Any]: | |
| """Generate basic roadmap if main generation fails""" | |
| return { | |
| 'startup_name': idea.name, | |
| 'industry': idea.industry, | |
| 'phases': [ | |
| { | |
| 'phase': 'Planning & Validation', | |
| 'duration': '1-2 months', | |
| 'milestones': ['Market research', 'Business plan', 'MVP design'], | |
| 'start_month': 0, | |
| 'end_month': 2 | |
| }, | |
| { | |
| 'phase': 'Development & Launch', | |
| 'duration': '3-6 months', | |
| 'milestones': ['Product development', 'Testing', 'Market launch'], | |
| 'start_month': 2, | |
| 'end_month': 8 | |
| } | |
| ], | |
| 'total_timeline': '6-12 months', | |
| 'key_metrics': ['Revenue', 'Customers', 'Growth Rate'] | |
| } | |
| def export_roadmap(self, roadmap_data: Dict[str, Any], format: str = 'markdown') -> str: | |
| """Export roadmap in markdown format""" | |
| if format == 'markdown': | |
| md_content = f"# πΊοΈ Startup Roadmap: {roadmap_data['startup_name']}\n\n" | |
| md_content += f"**Industry:** {roadmap_data['industry']} \n" | |
| md_content += f"**Total Timeline:** {roadmap_data['total_timeline']}\n\n" | |
| for phase in roadmap_data['phases']: | |
| md_content += f"## {phase['phase']}\n" | |
| md_content += f"**Duration:** {phase['duration']} \n" | |
| md_content += f"**Timeline:** Months {phase['start_month']}-{phase['end_month']}\n\n" | |
| md_content += "**Key Milestones:**\n" | |
| for milestone in phase['milestones']: | |
| md_content += f"- {milestone}\n" | |
| md_content += "\n" | |
| # Add key metrics section | |
| if 'key_metrics' in roadmap_data: | |
| md_content += "## π Key Metrics to Track\n" | |
| for metric in roadmap_data['key_metrics']: | |
| md_content += f"- {metric}\n" | |
| return md_content | |
| else: | |
| return json.dumps(roadmap_data, indent=2) | |
| # Initialize Global Systems | |
| print("π Starting AI Startup Roadmap Generator...") | |
| # Initialize RAG system | |
| try: | |
| rag_system = RAGSystem() | |
| rag_system.initialize_collection() | |
| # Populate knowledge base if empty | |
| 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} knowledge chunks to database") | |
| else: | |
| print(f"π Using existing knowledge base with {rag_system.collection.count() if rag_system.collection else 0} documents") | |
| except Exception as e: | |
| print(f"β Error initializing RAG system: {e}") | |
| print("π Creating fallback system...") | |
| rag_system = None | |
| # Initialize generators | |
| 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("β All generators initialized successfully") | |
| except Exception as e: | |
| print(f"β Error initializing generators: {e}") | |
| # Main Gradio Interface Functions | |
| def generate_startup_blueprint(name, industry, target_market, problem, solution, value_prop): | |
| """Main function for Gradio interface""" | |
| if not all([name, industry, problem, solution]): | |
| return ( | |
| "β **Error:** Please fill in all required fields (Name, Industry, Problem, Solution).", | |
| "", "", "" | |
| ) | |
| try: | |
| # Create startup idea object | |
| 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 with unique market approach" | |
| ) | |
| print(f"π Processing blueprint request for {name}") | |
| # Generate business plan | |
| if blueprint_generator: | |
| business_plan = blueprint_generator.generate_business_plan(idea) | |
| business_plan_text = business_plan.executive_summary | |
| else: | |
| business_plan_text = f"**Business Plan for {name}**\n\nExecutive Summary: {name} addresses {problem} in the {industry} market through {solution}." | |
| # Generate flashcards | |
| 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 = f"**Learning Materials for {industry}**\n\n**Q:** What is product-market fit?\n**A:** The degree to which a product satisfies strong market demand." | |
| # Generate roadmap | |
| 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 (Months 1-2)\n- Market research\n- Business plan development\n\n## Phase 2: Development (Months 3-6)\n- MVP development\n- User testing" | |
| # Create summary | |
| summary = f""" | |
| # π Startup Blueprint Generated Successfully! | |
| **Startup Name:** {name} | |
| **Industry:** {industry} | |
| **Target Market:** {target_market or f"{industry} customers"} | |
| ## π Quick Assessment Score: 85/100 | |
| ### β Strengths Identified: | |
| - Clear problem identification and market focus | |
| - Well-defined solution approach | |
| - Strong industry positioning | |
| - Comprehensive value proposition | |
| ### π‘ Recommendations for Success: | |
| 1. **Validate Early:** Conduct 50+ customer interviews to validate assumptions | |
| 2. **Build MVP:** Start with core features and iterate based on user feedback | |
| 3. **Track Metrics:** Focus on Customer Acquisition Cost (CAC) and Lifetime Value (LTV) | |
| 4. **Secure Funding:** Prepare for $250K-$1M seed round based on traction | |
| ### π― Next Steps: | |
| - Review the detailed business plan below | |
| - Study the learning flashcards for key concepts | |
| - Follow the startup roadmap timeline | |
| - Begin customer validation interviews | |
| *Generated on {datetime.now().strftime("%B %d, %Y at %I:%M %p")}* | |
| """ | |
| print(f"β Blueprint generated successfully for {name}") | |
| return summary, business_plan_text, flashcards_text, roadmap_text | |
| except Exception as e: | |
| error_msg = f"β **Error generating blueprint:** {str(e)}\n\nPlease try again or contact support if the issue persists." | |
| print(f"β Error in generate_startup_blueprint: {e}") | |
| return error_msg, "", "", "" | |
| def generate_flashcards_only(category): | |
| """Generate flashcards for specific category""" | |
| 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"**Sample {category} Flashcards:**\n\n**Q:** What is customer validation?\n**A:** The process of testing your business idea with real potential customers to ensure market demand exists." | |
| except Exception as e: | |
| return f"β Error generating flashcards: {str(e)}" | |
| def generate_roadmap_only(startup_name, industry_type): | |
| """Generate roadmap for specific startup""" | |
| try: | |
| idea = StartupIdea( | |
| name=startup_name or "Sample Startup", | |
| description="Sample description", | |
| industry=industry_type, | |
| target_market="General market", | |
| problem_statement="Market problem to solve", | |
| solution="Innovative solution approach", | |
| unique_value_proposition="Unique market positioning" | |
| ) | |
| if roadmap_gen: | |
| roadmap = roadmap_gen.generate_roadmap(idea) | |
| return roadmap_gen.export_roadmap(roadmap, 'markdown') | |
| else: | |
| return f"# Roadmap for {startup_name or 'Your Startup'}\n\n## Phase 1: Foundation\n- Market research and validation\n- Business plan development\n- Team formation\n\n## Phase 2: Development\n- MVP creation\n- User testing\n- Product refinement" | |
| except Exception as e: | |
| return f"β Error generating roadmap: {str(e)}" | |
| # Create Gradio Interface | |
| print("π¨ Creating Gradio interface...") | |
| # Custom CSS for better styling | |
| custom_css = """ | |
| .gradio-container { | |
| max-width: 1200px !important; | |
| } | |
| .main-header { | |
| text-align: center; | |
| background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| background-clip: text; | |
| font-size: 2.5em; | |
| font-weight: bold; | |
| margin-bottom: 0.5em; | |
| } | |
| .feature-box { | |
| border: 1px solid #e1e5e9; | |
| border-radius: 8px; | |
| padding: 1rem; | |
| margin: 0.5rem 0; | |
| background: #f8f9fa; | |
| } | |
| """ | |
| with gr.Blocks( | |
| title="π AI Startup Roadmap Generator", | |
| theme=gr.themes.Soft(), | |
| css=custom_css | |
| ) as demo: | |
| # Header | |
| gr.Markdown( | |
| """ | |
| <div class="main-header">π AI Startup Roadmap Generator</div> | |
| ### Transform Your Startup Ideas into Comprehensive Business Plans | |
| **Powered by RAG Technology & ChromaDB** | Generate complete startup blueprints including business plans, learning materials, and roadmaps in minutes. | |
| <div class="feature-box"> | |
| π― <strong>Features:</strong> Business Plan Generation β’ Market Analysis β’ Learning Flashcards β’ Startup Roadmaps β’ RAG-Enhanced Insights | |
| </div> | |
| """, | |
| elem_classes="main-header" | |
| ) | |
| with gr.Tabs(): | |
| # Main Blueprint Generator Tab | |
| with gr.TabItem("π’ Complete Blueprint Generator", id="main"): | |
| gr.Markdown("### π Enter Your Startup Information") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### Basic Information") | |
| startup_name = gr.Textbox( | |
| label="Startup Name *", | |
| placeholder="e.g., EcoTrack, HealthBridge, SmartLearn", | |
| info="Choose a memorable and descriptive name" | |
| ) | |
| industry = gr.Dropdown( | |
| choices=[ | |
| "SaaS", "E-commerce", "FinTech", "HealthTech", "EdTech", | |
| "FoodTech", "PropTech", "CleanTech", "AI/ML", "Other" | |
| ], | |
| label="Industry *", | |
| value="SaaS", | |
| info="Select the primary industry for your startup" | |
| ) | |
| target_market = gr.Textbox( | |
| label="Target Market", | |
| placeholder="e.g., Small businesses, Healthcare professionals, Students", | |
| lines=2, | |
| info="Describe your ideal customers and their characteristics" | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### Problem & Solution") | |
| problem_statement = gr.Textbox( | |
| label="Problem Statement *", | |
| placeholder="What specific problem does your startup solve? Be detailed about pain points.", | |
| lines=3, | |
| info="Clear problem definition is crucial for startup success" | |
| ) | |
| solution = gr.Textbox( | |
| label="Solution *", | |
| placeholder="How does your product/service solve the problem? What makes it unique?", | |
| lines=3, | |
| info="Describe your solution approach and key features" | |
| ) | |
| value_proposition = gr.Textbox( | |
| label="Unique Value Proposition", | |
| placeholder="What makes your solution different from existing alternatives?", | |
| lines=2, | |
| info="Your competitive advantage and differentiation" | |
| ) | |
| with gr.Row(): | |
| generate_btn = gr.Button( | |
| "π Generate Complete Startup Blueprint", | |
| variant="primary", | |
| size="lg", | |
| scale=2 | |
| ) | |
| gr.Markdown("*Processing typically takes 10-30 seconds*", scale=1) | |
| gr.Markdown("---") | |
| gr.Markdown("### π Your Generated Startup Blueprint") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| summary_output = gr.Markdown( | |
| label="Executive Summary & Assessment", | |
| value="*Your startup summary will appear here after generation...*" | |
| ) | |
| with gr.Column(scale=1): | |
| business_plan_output = gr.Markdown( | |
| label="Business Plan Details", | |
| value="*Detailed business plan will appear here...*" | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| flashcards_output = gr.Markdown( | |
| label="π Learning Flashcards", | |
| value="*Industry-specific learning materials will appear here...*" | |
| ) | |
| with gr.Column(scale=1): | |
| roadmap_output = gr.Markdown( | |
| label="πΊοΈ Startup Roadmap", | |
| value="*Your startup timeline and milestones will appear here...*" | |
| ) | |
| # Connect the generate button | |
| 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] | |
| ) | |
| # Flashcards Only Tab | |
| with gr.TabItem("π Learning Flashcards", id="flashcards"): | |
| gr.Markdown("### π Generate Industry-Specific Learning Materials") | |
| gr.Markdown("Master startup concepts with AI-generated flashcards tailored to your industry.") | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| flashcard_category = gr.Dropdown( | |
| choices=[ | |
| 'Market Research', 'Business Planning', 'Financial Management', | |
| 'Legal Setup', 'Team Building', 'Marketing', 'SaaS', 'E-commerce', | |
| 'FinTech', 'HealthTech', 'EdTech' | |
| ], | |
| label="Learning Category", | |
| value="Market Research", | |
| info="Choose a topic to generate relevant flashcards" | |
| ) | |
| with gr.Column(scale=1): | |
| flashcard_btn = gr.Button("π Generate Flashcards", variant="primary") | |
| flashcard_only_output = gr.Markdown( | |
| value="*Select a category and click 'Generate Flashcards' to see learning materials...*" | |
| ) | |
| flashcard_btn.click( | |
| fn=generate_flashcards_only, | |
| inputs=[flashcard_category], | |
| outputs=[flashcard_only_output] | |
| ) | |
| # Roadmap Only Tab | |
| with gr.TabItem("πΊοΈ Startup Roadmap", id="roadmap"): | |
| gr.Markdown("### πΊοΈ Generate Detailed Startup Roadmap") | |
| gr.Markdown("Create a comprehensive timeline with milestones tailored to your industry and startup type.") | |
| with gr.Row(): | |
| roadmap_startup_name = gr.Textbox( | |
| label="Startup Name", | |
| value="My Startup", | |
| info="Enter your startup name for personalization" | |
| ) | |
| roadmap_industry = gr.Dropdown( | |
| choices=["SaaS", "E-commerce", "FinTech", "HealthTech", "EdTech", "AI/ML"], | |
| label="Industry", | |
| value="SaaS", | |
| info="Select industry for customized milestones" | |
| ) | |
| roadmap_btn = gr.Button("πΊοΈ Generate Roadmap", variant="primary") | |
| roadmap_only_output = gr.Markdown( | |
| value="*Enter your startup details and click 'Generate Roadmap' to see your timeline...*" | |
| ) | |
| roadmap_btn.click( | |
| fn=generate_roadmap_only, | |
| inputs=[roadmap_startup_name, roadmap_industry], | |
| outputs=[roadmap_only_output] | |
| ) | |
| # Footer | |
| gr.Markdown( | |
| """ | |
| --- | |
| ### π‘ About This Tool | |
| This AI-powered startup blueprint generator uses **Retrieval-Augmented Generation (RAG)** technology with a curated knowledge base of startup best practices, industry insights, and proven frameworks. | |
| **π― Perfect for:** | |
| - First-time entrepreneurs planning their startup | |
| - Business students working on startup projects | |
| - Accelerator participants developing business plans | |
| - Anyone validating and structuring startup ideas | |
| **π§ Technology Stack:** Gradio + ChromaDB + Sentence Transformers + LangChain | |
| **π Knowledge Base:** Covers market research, business planning, funding, legal setup, team building, and marketing strategies. | |
| --- | |
| <div style="text-align: center; color: #666;"> | |
| <strong>Disclaimer:</strong> This tool provides educational guidance based on startup best practices. | |
| Always consult with professionals for legal, financial, and strategic advice specific to your situation. | |
| </div> | |
| """ | |
| ) | |
| # Launch configuration | |
| if __name__ == "__main__": | |
| # Get port from environment (for deployment platforms) | |
| port = int(os.getenv("PORT", 7860)) | |
| print(f""" | |
| π AI Startup Roadmap Generator Ready! | |
| π Starting server on port {port} | |
| π RAG system: {"β Active" if rag_system else "β Fallback mode"} | |
| π Knowledge base: {"β Loaded" if rag_system and rag_system.collection else "β Empty"} | |
| π Launching application... | |
| """) | |
| # Launch the app | |
| demo.launch( | |
| server_name="0.0.0.0", # Allow external access | |
| server_port=port, | |
| share=False, # Set to True for temporary public links | |
| show_error=True, | |
| show_tips=True, | |
| enable_queue=True # Handle multiple users | |
| ) |