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

import gradio as gr
from groq import Groq
import os
import json
from datetime import datetime

# Initialize Groq client
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))

# Session state management
class IdeationSession:
    def __init__(self):
        self.ideas = []
        self.current_idea = None
        
session = IdeationSession()

# System prompts
DISCOVERY_PROMPT = """You are a startup ideation expert. Help users discover innovative startup ideas using these four sources:

1. **Problems**: Identify real problems (agricultural waste, infrastructure issues, import dependency)
2. **Intersections**: Combine fields (Transportation + Mobile = Uber, Hospitality + Internet = Airbnb)
3. **Future Trends**: Emerging technologies (AI, drones, IoT, renewable energy)
4. **Edges of Knowledge**: Cutting-edge breakthroughs (new materials, gene editing, quantum computing)

Be specific, provide concrete examples, and encourage bold thinking."""

EVALUATION_PROMPT = """Evaluate startup ideas using the 4-question framework:

**Q1: Is it a good problem?** Market size, pain level, financial loss, customer recognition
**Q2: Can I fix it?** Skills, realistic assessment, learning curve
**Q3: Is solution robust?** Easy to use, addresses pain, provides benefits, easy decision
**Q4: Do I have resources?** MVP capability, customer access, scaling potential, minimum funding

Rate honestly (1-10 for each criterion) and provide constructive feedback."""

REFINEMENT_PROMPT = """Help refine ideas based on evaluation:
- Strong ideas: Develop MVP strategy, customer discovery plan, next steps
- Weak areas: Suggest specific improvements and potential pivots
- Focus on: Customer interviews (not surveys), building with own resources, minimal MVP, quick testing, finding mentors"""

ACTION_PLANNING_PROMPT = """Create concrete action plans:
1. Immediate actions (this week): 3-5 specific validation tasks
2. Short-term goals (1 month): Customer discovery targets, MVP specs
3. Resources needed: Skills, team, tools, initial budget
4. Milestones: Success metrics, decision points, timeline

Be specific and actionable for beginners."""

def chat_with_groq(message, system_prompt, history=None):
    """Send message to Groq API"""
    try:
        messages = [{"role": "system", "content": system_prompt}]
        if history:
            messages.extend(history)
        messages.append({"role": "user", "content": message})
        
        response = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=messages,
            temperature=0.7,
            max_tokens=2000,
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"Error: {str(e)}. Please check your GROQ_API_KEY environment variable."

def format_for_chatbot(history):
    """Format chat history for Gradio Chatbot - handles both tuple and dict formats"""
    # Gradio 6.x uses dict format with role/content
    formatted = []
    for msg in history:
        formatted.append({
            "role": msg["role"],
            "content": msg["content"]
        })
    return formatted

def discover_ideas(source_type, user_input, context, history):
    """Help discover ideas"""
    if not user_input or not context:
        return history, history
    
    prompt = f"""Using the {source_type} approach:

My Background: {context}
My Observation: {user_input}

Please help me explore innovative startup ideas. Provide:
1. Specific idea suggestions based on my observation
2. Real-world examples of similar successful solutions
3. Probing questions to help me think deeper
4. Potential opportunities I might be missing

Focus on ideas that are innovative, address real needs, and have potential for scale."""
    
    history.append({"role": "user", "content": prompt})
    response = chat_with_groq(prompt, DISCOVERY_PROMPT, history)
    history.append({"role": "assistant", "content": response})
    
    return format_for_chatbot(history), history

def evaluate_idea(idea_desc, target_market, problem_stmt, solution, history):
    """Evaluate using 4-question framework"""
    if not idea_desc or not problem_stmt:
        return history, history, "Please fill in at least Idea Description and Problem Statement"
    
    prompt = f"""Evaluate this startup idea using the 4-question framework:

**Idea Description:** {idea_desc}

**Target Market:** {target_market}

**Problem Statement:** {problem_stmt}

**Solution Approach:** {solution}

Please provide:
1. Detailed evaluation for each of the 4 questions
2. Scores (1-10) for each major criterion
3. Overall assessment
4. Specific areas that need improvement
5. Red flags or concerns (if any)
6. Strengths to leverage

Be honest and constructive. This is for a beginner entrepreneur."""
    
    history.append({"role": "user", "content": prompt})
    response = chat_with_groq(prompt, EVALUATION_PROMPT, history)
    history.append({"role": "assistant", "content": response})
    
    session.current_idea = {
        "description": idea_desc,
        "target_market": target_market,
        "problem": problem_stmt,
        "solution": solution,
        "evaluation": response,
        "timestamp": datetime.now().isoformat()
    }
    session.ideas.append(session.current_idea)
    
    return format_for_chatbot(history), history, f"โœ… Idea #{len(session.ideas)} evaluated and saved!"

def refine_idea(refinement_input, history):
    """Refine and improve idea"""
    if not session.current_idea:
        error_msg = [{"role": "assistant", "content": "โš ๏ธ Please evaluate an idea first in the 'Evaluate Ideas' tab before seeking refinement advice."}]
        return format_for_chatbot(error_msg), history, ""
    
    if not refinement_input:
        return format_for_chatbot(history), history, ""
    
    prompt = f"""Based on the evaluation of my current idea, I need help with:

{refinement_input}

**Current Idea Summary:**
- Problem: {session.current_idea['problem']}
- Solution: {session.current_idea['solution']}
- Target Market: {session.current_idea['target_market']}

Please provide specific, actionable advice to improve this idea."""
    
    history.append({"role": "user", "content": prompt})
    
    # Include previous evaluation for context
    context_messages = [
        {"role": "assistant", "content": f"Previous Evaluation:\n{session.current_idea['evaluation']}"},
        {"role": "user", "content": prompt}
    ]
    
    response = chat_with_groq(prompt, REFINEMENT_PROMPT, context_messages)
    history.append({"role": "assistant", "content": response})
    
    return format_for_chatbot(history), history, "๐Ÿ’ก Refinement suggestions provided"

def create_action_plan(goals, timeline, resources, history):
    """Create action plan"""
    if not session.current_idea:
        error_msg = [{"role": "assistant", "content": "โš ๏ธ Please evaluate an idea first before creating an action plan."}]
        return format_for_chatbot(error_msg), history, ""
    
    if not goals or not timeline:
        return format_for_chatbot(history), history, "Please fill in at least Goals and Timeline"
    
    prompt = f"""Create a detailed action plan for my startup idea:

**Idea:** {session.current_idea['description']}
**Problem:** {session.current_idea['problem']}
**Solution:** {session.current_idea['solution']}
**Target Market:** {session.current_idea['target_market']}

**My Goals:** {goals}
**Timeline:** {timeline}
**Available Resources:** {resources}

Please create a comprehensive action plan with:
1. Immediate next steps (this week)
2. Short-term milestones (1 month)
3. Medium-term objectives (3 months)
4. Resource requirements (skills, team, tools, budget)
5. Key metrics to track
6. Potential obstacles and how to overcome them

Make it specific and actionable for an absolute beginner."""
    
    history.append({"role": "user", "content": prompt})
    response = chat_with_groq(prompt, ACTION_PLANNING_PROMPT, history)
    history.append({"role": "assistant", "content": response})
    
    session.current_idea['action_plan'] = response
    session.current_idea['updated'] = datetime.now().isoformat()
    
    return format_for_chatbot(history), history, "๐Ÿ“‹ Action plan created and saved!"

def export_session():
    """Export all ideas"""
    if not session.ideas:
        return "No ideas to export yet. Start by discovering and evaluating ideas!", ""
    
    report = f"""# STARTUP IDEATION SESSION REPORT
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Total Ideas Explored: {len(session.ideas)}

{'='*80}

"""
    
    for i, idea in enumerate(session.ideas, 1):
        report += f"""
## IDEA {i}: {idea['description'][:100]}{'...' if len(idea['description']) > 100 else ''}

**Target Market:** {idea['target_market']}

**Problem Statement:**
{idea['problem']}

**Solution Approach:**
{idea['solution']}

**Evaluation:**
{idea['evaluation']}

"""
        if 'action_plan' in idea:
            report += f"""
**Action Plan:**
{idea['action_plan']}
"""
        
        report += f"\n{'='*80}\n"
    
    json_data = json.dumps({
        "export_date": datetime.now().isoformat(),
        "total_ideas": len(session.ideas),
        "ideas": session.ideas
    }, indent=2)
    
    return report, json_data

def clear_session():
    """Reset session"""
    global session
    session = IdeationSession()
    return "โœ… Session cleared! You can start fresh.", [], []

# Build Gradio Interface
with gr.Blocks(title="Startup Ideation Assistant") as app:
    
    gr.HTML("""
    <div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                padding: 2rem; border-radius: 10px; color: white; margin-bottom: 2rem; text-align: center;'>
        <h1 style='margin: 0 0 0.5rem 0;'>๐Ÿš€ Startup Ideation Assistant</h1>
        <p style='margin: 0; font-size: 1.1rem;'>AI-Powered Idea Discovery, Evaluation & Planning</p>
    </div>
    """)
    
    gr.Markdown("""
    ## Welcome to Your Startup Journey!
    
    This tool guides you through 4 stages:
    1. **Discover Ideas** - Generate innovative ideas from 4 proven sources
    2. **Evaluate Ideas** - Test viability with critical questions
    3. **Refine Ideas** - Strengthen weak areas
    4. **Create Action Plan** - Build concrete execution roadmap
    """)
    
    discovery_history = gr.State([])
    evaluation_history = gr.State([])
    refinement_history = gr.State([])
    planning_history = gr.State([])
    
    with gr.Tabs():
        
        # TAB 1: IDEA DISCOVERY
        with gr.Tab("1๏ธโƒฃ Discover Ideas"):
            gr.Markdown("### Four Sources of Innovative Ideas")
            
            with gr.Row():
                with gr.Column(scale=2):
                    source_selector = gr.Radio(
                        choices=[
                            "๐Ÿ”ด Problems",
                            "๐Ÿ”„ Intersections",
                            "๐Ÿ”ฎ Future Trends",
                            "๐Ÿงฌ Edges of Knowledge"
                        ],
                        label="Select Idea Source",
                        value="๐Ÿ”ด Problems"
                    )
                    
                    user_context = gr.TextArea(
                        label="Your Background & Interests",
                        placeholder="Example: I'm a software developer interested in solving agricultural problems in Pakistan...",
                        lines=3
                    )
                    
                    user_input = gr.TextArea(
                        label="Your Observation or Question",
                        placeholder="Example: I noticed farmers waste tons of crop residue after harvest. This could be valuable...",
                        lines=4
                    )
                    
                    discover_btn = gr.Button("๐Ÿ’ก Discover Ideas", variant="primary", size="lg")
                
                with gr.Column(scale=3):
                    discovery_chat = gr.Chatbot(
                        label="AI Idea Discovery Assistant",
                        height=500
                    )
            
            discover_btn.click(
                fn=discover_ideas,
                inputs=[source_selector, user_input, user_context, discovery_history],
                outputs=[discovery_chat, discovery_history]
            )
        
        # TAB 2: IDEA EVALUATION
        with gr.Tab("2๏ธโƒฃ Evaluate Ideas"):
            gr.Markdown("### The 4-Question Evaluation Framework")
            
            with gr.Row():
                with gr.Column():
                    idea_desc = gr.TextArea(
                        label="๐Ÿ“ Idea Description",
                        placeholder="Describe your startup idea in detail...",
                        lines=3
                    )
                    
                    target_market = gr.TextArea(
                        label="๐ŸŽฏ Target Market",
                        placeholder="Who are your customers? How many potential users?",
                        lines=2
                    )
                    
                    problem_statement = gr.TextArea(
                        label="โ“ Problem Statement",
                        placeholder="What problem does this solve? Why is it important?",
                        lines=3
                    )
                    
                    solution_approach = gr.TextArea(
                        label="๐Ÿ’ก Your Solution",
                        placeholder="How will you solve this problem?",
                        lines=3
                    )
                    
                    evaluate_btn = gr.Button("๐Ÿ” Evaluate Idea", variant="primary", size="lg")
                    eval_status = gr.Textbox(label="Status", interactive=False)
            
            with gr.Row():
                evaluation_chat = gr.Chatbot(
                    label="AI Evaluation Results",
                    height=500
                )
            
            evaluate_btn.click(
                fn=evaluate_idea,
                inputs=[idea_desc, target_market, problem_statement, solution_approach, evaluation_history],
                outputs=[evaluation_chat, evaluation_history, eval_status]
            )
        
        # TAB 3: IDEA REFINEMENT
        with gr.Tab("3๏ธโƒฃ Refine Ideas"):
            gr.Markdown("### Improve and Strengthen Your Idea")
            
            with gr.Row():
                with gr.Column(scale=1):
                    refinement_input = gr.TextArea(
                        label="What would you like to improve?",
                        placeholder="Example: How can I reduce costs? How do I find early customers? What if people don't recognize this problem?",
                        lines=5
                    )
                    
                    refine_btn = gr.Button("โœจ Get Refinement Advice", variant="primary", size="lg")
                    refine_status = gr.Textbox(label="Status", interactive=False)
                
                with gr.Column(scale=2):
                    refinement_chat = gr.Chatbot(
                        label="AI Refinement Advisor",
                        height=600
                    )
            
            refine_btn.click(
                fn=refine_idea,
                inputs=[refinement_input, refinement_history],
                outputs=[refinement_chat, refinement_history, refine_status]
            )
        
        # TAB 4: ACTION PLANNING
        with gr.Tab("4๏ธโƒฃ Create Action Plan"):
            gr.Markdown("### From Idea to Execution")
            
            with gr.Row():
                with gr.Column():
                    goals_input = gr.TextArea(
                        label="๐ŸŽฏ Your Goals",
                        placeholder="Example: Validate idea with 20 customers, build MVP, find co-founder...",
                        lines=3
                    )
                    
                    timeline_input = gr.TextArea(
                        label="โฐ Timeline",
                        placeholder="Example: 3 months, 6 months, 1 year...",
                        lines=2
                    )
                    
                    resources_input = gr.TextArea(
                        label="๐Ÿ’ฐ Available Resources",
                        placeholder="Example: Skills (Python, marketing), Time (20hrs/week), Money ($5000), Team (solo)...",
                        lines=3
                    )
                    
                    plan_btn = gr.Button("๐Ÿ“‹ Create Action Plan", variant="primary", size="lg")
                    plan_status = gr.Textbox(label="Status", interactive=False)
            
            with gr.Row():
                planning_chat = gr.Chatbot(
                    label="AI Action Plan",
                    height=500
                )
            
            plan_btn.click(
                fn=create_action_plan,
                inputs=[goals_input, timeline_input, resources_input, planning_history],
                outputs=[planning_chat, planning_history, plan_status]
            )
        
        # TAB 5: EXPORT & SUMMARY
        with gr.Tab("5๏ธโƒฃ Export & Summary"):
            gr.Markdown("### ๐Ÿ“Š Your Ideation Journey Summary")
            
            with gr.Row():
                export_btn = gr.Button("๐Ÿ“ฅ Generate Report", variant="primary", size="lg")
                clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear Session", variant="secondary")
            
            with gr.Row():
                with gr.Column():
                    report_output = gr.TextArea(
                        label="Formatted Report",
                        lines=20
                    )
                
                with gr.Column():
                    json_output = gr.TextArea(
                        label="JSON Data (for portability)",
                        lines=20
                    )
            
            clear_status = gr.Textbox(label="Status", interactive=False)
            
            export_btn.click(fn=export_session, outputs=[report_output, json_output])
            clear_btn.click(fn=clear_session, outputs=[clear_status, discovery_history, evaluation_history])
    
    gr.Markdown("""
    ---
    ### ๐Ÿ‘จโ€๐Ÿ’ป Developed by Najaf Ali Sharqi
    *AI-powered startup ideation platform for aspiring entrepreneurs*
    """)

if __name__ == "__main__":
    app.launch()