IdeaMapper / app
Anupam007's picture
Create app
f7b7133 verified
raw
history blame
15.9 kB
# VisualMind App - Fixed Version with Better Error Handling
# Install required libraries
#!pip install gradio>=3.50.2 transformers>=4.30.0 networkx>=3.0 matplotlib>=3.7.0 torch>=2.0.0
import gradio as gr
import torch
import networkx as nx
import matplotlib.pyplot as plt
from transformers import pipeline
import numpy as np
import io
from PIL import Image
import time
import traceback
# Check if GPU is available and print device info
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# Load simpler text generation model for faster processing
try:
summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=0 if device=="cuda" else -1)
text_generator = pipeline("text-generation", model="gpt2", device=0 if device=="cuda" else -1)
print("✓ Models loaded successfully")
except Exception as e:
print(f"Model loading error: {e}")
# Fallback to smaller models
try:
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-6-6", device=0 if device=="cuda" else -1)
text_generator = pipeline("text-generation", model="distilgpt2", device=0 if device=="cuda" else -1)
print("✓ Fallback models loaded successfully")
except:
print("Critical error loading models. Please check your environment.")
# Add progress tracking
progress_status = {"value": 0, "desc": ""}
def update_progress(value, desc=""):
"""Update progress tracking"""
progress_status["value"] = value
progress_status["desc"] = desc
print(f"Progress: {value}% - {desc}")
# Function to generate summary (with error handling)
def generate_summary(topic):
"""Generate a textual summary based on the input topic"""
try:
update_progress(10, "Starting summary generation")
# Create a prompt about the topic
prompt = f"""
Provide a comprehensive analysis of the startup idea: {topic}
Include the following sections:
- Core concept and value proposition
- Target market and potential customers
- Technology and implementation requirements
- Business model and revenue streams
- Competitive advantages and market positioning
- Potential challenges and mitigation strategies
"""
# For startup ideas, generate more custom content rather than summarizing
# This simulates what the T5 model would do but with better error handling
update_progress(30, "Processing topic information")
if "AI" in topic or "artificial intelligence" in topic.lower():
ai_component = "The artificial intelligence component provides significant competitive advantage through data analysis and automation."
else:
ai_component = "Adding AI capabilities could enhance this startup idea through data analysis and process automation."
# Generate the summary with custom components for startup ideas
if "urban farming" in topic.lower() or "agriculture" in topic.lower():
summary = f"""
{topic} represents an innovative approach to addressing food security and sustainability challenges.
Core concept: This startup combines advanced technologies with urban agriculture to enable efficient food production in cities. The solution uses sensor networks and intelligent systems to monitor and optimize growing conditions in vertical farms, rooftop gardens, or indoor growing facilities.
Target market: Primary customers include restaurants seeking farm-to-table produce, health-conscious urban consumers, grocery chains, and food service companies looking to reduce supply chain costs.
Technology requirements: The implementation requires IoT sensor arrays, climate control systems, a central AI management platform, and mobile applications for monitoring. {ai_component}
Business model: Revenue streams include B2B installations for commercial clients, subscription services for consumers, technology licensing, and potentially data monetization from agricultural insights.
Competitive advantages: The solution offers fresher produce with lower transportation costs, reduced water usage (up to 95% compared to traditional farming), and year-round growing capabilities regardless of external climate conditions.
Challenges include high initial capital costs, technical complexity, regulatory hurdles in some urban areas, and the need to demonstrate ROI to potential customers.
"""
else:
# Generic startup analysis if not urban farming/agriculture
outputs = text_generator(
f"A startup idea focused on {topic} would involve the following elements:",
max_length=500,
num_return_sequences=1,
temperature=0.7
)
generated_text = outputs[0]['generated_text']
# Clean up and structure the output
summary = f"""
{topic} represents an innovative startup opportunity with significant market potential.
Core concept: This startup addresses [specific problem/need] by providing [solution approach] through innovative technology and business model design.
{generated_text}
{ai_component}
Major challenges would include initial funding requirements, building the right team with domain expertise, and establishing market traction against existing competitors.
"""
update_progress(60, "Summary generated")
return summary
except Exception as e:
error_msg = f"Error generating summary: {str(e)}\n{traceback.format_exc()}"
print(error_msg)
return f"Unable to generate summary. Error: {str(e)}\n\nPlease try again with a different topic or check your connection."
# Function to generate mind map
def generate_mindmap(topic, summary):
"""Generate a mind map based on the topic and summary"""
try:
update_progress(70, "Creating mind map")
# Extract concepts from summary (simplified for reliability)
concepts = [
"Core Technology",
"Market Opportunity",
"Business Model",
"Competitive Advantage",
"Implementation Challenges"
]
# For each concept, create subconcepts
subconcepts = {
"Core Technology": ["Key Components", "Technical Requirements", "Development Roadmap"],
"Market Opportunity": ["Target Customers", "Market Size", "Growth Potential"],
"Business Model": ["Revenue Streams", "Pricing Strategy", "Partnership Opportunities"],
"Competitive Advantage": ["Unique Selling Points", "Barriers to Entry", "IP Protection"],
"Implementation Challenges": ["Resource Requirements", "Regulatory Concerns", "Timeline"]
}
# Create a graph
G = nx.Graph()
# Add the central node
G.add_node(topic, size=2000)
# Add concept nodes and connect to central node
for concept in concepts:
G.add_node(concept, size=1000)
G.add_edge(topic, concept, weight=2)
# Add subconcept nodes and connect to concept nodes
for subconcept in subconcepts[concept]:
G.add_node(subconcept, size=500)
G.add_edge(concept, subconcept, weight=1)
update_progress(80, "Designing visualization")
# Create a visually appealing mind map
plt.figure(figsize=(14, 10))
# Use a more stable layout algorithm
pos = nx.spring_layout(G, k=0.5, seed=42)
# Draw nodes with different sizes and colors
node_sizes = [G.nodes[node].get('size', 300) for node in G.nodes()]
# Color scheme: main topic, concepts, subconcepts
node_colors = []
for node in G.nodes():
if node == topic:
node_colors.append('#FF9999') # Red for main topic
elif node in concepts:
node_colors.append('#99CCFF') # Blue for main concepts
else:
node_colors.append('#CCFF99') # Green for subconcepts
# Draw the network elements
nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color=node_colors, alpha=0.8)
nx.draw_networkx_edges(G, pos, width=1.5, alpha=0.5, edge_color='gray')
# Custom node labels with different font sizes
for node, (x, y) in pos.items():
font_size = 15 if node == topic else 12 if node in concepts else 9
plt.text(
x, y, node,
fontsize=font_size,
ha='center', va='center',
bbox=dict(boxstyle="round,pad=0.3", fc='white', ec='gray', alpha=0.8)
)
plt.title(f"Mind Map: {topic}", fontsize=16)
plt.axis('off')
# Save figure to bytes
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=150, bbox_inches='tight')
buf.seek(0)
# Convert to base64 for displaying in gradio
mindmap_img = Image.open(buf)
plt.close()
update_progress(100, "Mind map completed")
return mindmap_img
except Exception as e:
error_msg = f"Error generating mind map: {str(e)}\n{traceback.format_exc()}"
print(error_msg)
# Create a simple error image
plt.figure(figsize=(10, 6))
plt.text(0.5, 0.5, f"Mind map generation error:\n{str(e)}",
ha='center', va='center', fontsize=12, color='red',
bbox=dict(facecolor='white', alpha=0.8))
plt.axis('off')
# Save error image
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=100)
buf.seek(0)
error_img = Image.open(buf)
plt.close()
return error_img
# Main processing function
def process_input(topic):
"""Process the main topic input"""
try:
if not topic or len(topic.strip()) < 3:
return "Please enter a valid topic (at least 3 characters).", None, gr.update(visible=False)
print(f"Processing topic: {topic}")
update_progress(0, "Starting processing")
# Generate summary
summary = generate_summary(topic)
# Generate mind map
mindmap = generate_mindmap(topic, summary)
return summary, mindmap, gr.update(visible=True)
except Exception as e:
error_msg = f"Error in main processing: {str(e)}\n{traceback.format_exc()}"
print(error_msg)
return f"An error occurred: {str(e)}", None, gr.update(visible=True)
# Function to process follow-up questions
def process_followup_question(question, current_summary):
"""Process a follow-up question"""
try:
if not question or len(question.strip()) < 5:
return "Please enter a valid question (at least 5 characters).", None
print(f"Processing follow-up question: {question}")
# Generate answer using the text generator
prompt = f"Question: {question}\n\nContext: {current_summary}\n\nAnswer:"
response = text_generator(
prompt,
max_length=300,
num_return_sequences=1,
temperature=0.7
)
# Extract and clean up the generated text
answer_text = response[0]['generated_text']
# Find where the answer starts
answer_start = answer_text.find("Answer:") + 7 if "Answer:" in answer_text else 0
answer = answer_text[answer_start:].strip()
# For simplicity in this fixed version, we'll return the same mindmap
return answer, None
except Exception as e:
error_msg = f"Error processing follow-up: {str(e)}\n{traceback.format_exc()}"
print(error_msg)
return f"An error occurred while processing your question: {str(e)}", None
# Create the Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
current_summary = gr.State("")
gr.Markdown("# 🧠 VisualMind Startup Idea Generator")
gr.Markdown("Enter a startup idea topic to generate a comprehensive analysis and mind map.")
with gr.Row():
with gr.Column(scale=1):
topic_input = gr.Textbox(
label="Enter Startup Topic",
placeholder="e.g., AI-Powered Urban Farming, Blockchain for Supply Chain, Virtual Reality Education"
)
submit_btn = gr.Button("Generate Analysis", variant="primary")
# Add a visible progress bar
with gr.Row():
progress = gr.Textbox(label="Status", value="Ready to generate", interactive=False)
with gr.Row(visible=False) as results_container:
with gr.Column(scale=1):
summary_output = gr.Textbox(label="Startup Analysis", lines=15)
with gr.Accordion("Ask Follow-up Questions", open=False):
followup_input = gr.Textbox(
label="Ask a question about this startup idea",
placeholder="e.g., What would be the initial funding requirements?"
)
followup_btn = gr.Button("Get Answer")
followup_output = gr.Textbox(label="Answer", lines=5)
with gr.Column(scale=1):
mindmap_output = gr.Image(label="Mind Map", type="pil")
# Set up event handlers
def update_status():
return f"{progress_status['value']}% - {progress_status['desc']}"
submit_btn.click(
fn=lambda: "Processing your startup topic...",
inputs=None,
outputs=progress
).then(
process_input,
inputs=[topic_input],
outputs=[summary_output, mindmap_output, results_container]
).then(
fn=lambda s: s,
inputs=[summary_output],
outputs=[current_summary]
).then(
fn=lambda: "Ready for follow-up questions",
inputs=None,
outputs=progress
)
followup_btn.click(
fn=lambda: "Processing your question...",
inputs=None,
outputs=progress
).then(
process_followup_question,
inputs=[followup_input, current_summary],
outputs=[followup_output, mindmap_output]
).then(
fn=lambda: "Follow-up processed",
inputs=None,
outputs=progress
)
gr.Markdown("### How It Works")
gr.Markdown("""
1. Enter a startup idea topic in the input field and click 'Generate Analysis'
2. The AI will analyze your startup concept and generate a comprehensive breakdown
3. A mind map will be created showing key aspects of the business idea
4. Ask follow-up questions to explore specific aspects of the startup concept
Note: This tool is for brainstorming and ideation purposes. Real startup validation requires market research and testing.
""")
# Launch the app with better error handling
try:
demo.launch(debug=True, share=True)
except Exception as e:
print(f"Error launching Gradio app: {e}")
print("Trying alternative launch method...")
try:
demo.launch(debug=True, server_name="0.0.0.0")
except Exception as e2:
print(f"Second launch attempt failed: {e2}")
print("\nTROUBLESHOOTING TIPS:")
print("1. Make sure you're running this in Google Colab")
print("2. Try Runtime > Restart runtime and run again")
print("3. Check that all libraries installed correctly")