Alireza1913 commited on
Commit
9fa6b46
·
verified ·
1 Parent(s): 44814ca

Delete app.py

Browse files

import gradio as gr
import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", ""))

API_KNOWLEDGE_BASE = """
You are an expert API architect and indie hacker advisor. You know every major API deeply:

PAYMENT: Stripe, Paddle, LemonSqueezy, PayPal, Razorpay
AI/ML: OpenAI, Anthropic Claude, Replicate, HuggingFace Inference, AssemblyAI, ElevenLabs, Stability AI
COMMUNICATION: Twilio (SMS/Voice), SendGrid (email), Resend, Mailgun, Vonage, WhatsApp Business
DATA/ENRICHMENT: Clearbit, Apollo.io, Hunter.io, Proxycurl, PeopleDataLabs
MAPS/LOCATION: Google Maps, Mapbox, HERE, OpenStreetMap/Nominatim
MEDIA: Cloudinary, Mux (video), Imgix, Transloadit
FINANCE/MARKET DATA: Alpha Vantage, Polygon.io, CoinGecko, Plaid, Finnhub
SEARCH: Algolia, Typesense, Elasticsearch, Meilisearch
AUTH: Auth0, Clerk, Supabase Auth, Firebase Auth
DATABASE/BACKEND: Supabase, Firebase, PlanetScale, Neon, Upstash
SCRAPING/CRAWLING: Apify, ScraperAPI, Browserless, Firecrawl
SOCIAL: Twitter/X API, Reddit API, LinkedIn API, Instagram Graph API
PRODUCTIVITY: Notion API, Airtable, Google Workspace, Microsoft Graph
E-COMMERCE: Shopify, WooCommerce, Printful (print-on-demand)
ANALYTICS: Mixpanel, PostHog, Amplitude, Plausible
"""

SYSTEM_PROMPT = API_KNOWLEDGE_BASE + """

When a user describes their product idea, you will recommend the perfect API stack.

Your response MUST follow this exact format:

## 🎯 Your Idea in One Line
(restate the idea clearly and concisely)

## 🔧 Recommended API Stack

For each API (recommend 3-5 total), use this format:

### [API Name] — [Role in the product]
- **What it does for you:** (one sentence)
- **Pricing:** (free tier + paid tier, be specific)
- **Docs:** (exact URL)
- **Why not alternatives:** (one sentence)
- **Integration difficulty:** Easy / Medium / Hard

## 💰 Total Monthly API Cost Estimate
(breakdown for 100 users / 1000 users / 10,000 users)

## ⚡ Build Order
(which API to integrate first, second, third — and why)

## 🚨 One Thing to Watch Out For
(the most common mistake with this stack)

Be specific, honest about pricing, and always mention free tiers.
"""

def get_stack_recommendation(idea, budget, technical_level, target_market):
if not idea.strip():
return "Please describe your product idea first."

if not client.api_key:
return "⚠️ ANTHROPIC_API_KEY is not set. Add it in Space Settings → Secrets."

user_message = f"""
My product idea: {idea}

My monthly API budget: {budget}
My technical level: {technical_level}
Target market: {target_market}

Please recommend the best API stack for this.
"""

try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1500,
system=SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_message}]
)
return response.content[0].text
except Exception as e:
return f"❌ Error: {str(e)}"

def ask_followup(question, previous_recommendation):
if not question.strip():
return ""
if not previous_recommendation or previous_recommendation.startswith("Please") or previous_recommendation.startswith("⚠️"):
return "Please generate a stack recommendation first."

try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=800,
system=SYSTEM_PROMPT,
messages=[
{
"role": "user",
"content": f"I got this API stack recommendation:\n\n{previous_recommendation}\n\nMy follow-up question: {question}"
}
]
)
return response.content[0].text
except Exception as e:
return f"❌ Error: {str(e)}"

EXAMPLES = [
["A Notion-like note taking app with AI summarization", "$50/month", "Intermediate", "Students and researchers"],
["An SMS marketing platform for small restaurants", "$30/month", "Beginner", "Local restaurant owners"],
["A job board that auto-matches candidates with AI", "$100/month", "Advanced", "Tech recruiters"],
["A podcast transcription and highlight tool", "$20/month", "Beginner", "Podcasters"],
["A crypto portfolio tracker with price alerts", "$0 (free only)", "Intermediate", "Retail crypto investors"],
]

css = """
.gradio-container { max-width: 900px !important; margin: auto; }
footer { display: none !important; }
"""

with gr.Blocks(css=css, title="API Stack Finder") as demo:
gr.Markdown("""
# 🔧 API Stack Finder
**Describe your product idea → Get the perfect API stack, pricing breakdown, and build order**

Powered by Claude (Anthropic) — No more guessing which APIs to use.
""")

with gr.Row():
with gr.Column(scale=3):
idea_input = gr.Textbox(
label="Describe your product idea",
placeholder="e.g. A platform where freelancers can sell their services and get paid instantly via Stripe...",
lines=4
)
with gr.Column(scale=1):
budget_input = gr.Dropdown(
choices=["$0 (free only)", "$10/month", "$30/month", "$50/month", "$100/month", "$500/month", "Unlimited"],
value="$30/month",
label="Monthly API budget"
)
level_input = gr.Dropdown(
choices=["Beginner", "Intermediate", "Advanced"],
value="Intermediate",
label="Your technical level"
)
market_input = gr.Textbox(
label="Target market",
placeholder="e.g. Small business owners in Europe",
value="General consumers"
)

gr.Markdown("**Try an example:**")
with gr.Row():
for ex in EXAMPLES:
gr.Button(ex[0][:35] + "...", size="sm").click(
lambda e=ex: (e[0], e[1], e[2], e[3]),
outputs=[idea_input, budget_input, level_input, market_input]
)

submit_btn = gr.Button("🔍 Find My API Stack", variant="primary", size="lg")

recommendation_output = gr.Markdown(
value="*Your API stack recommendation will appear here...*",
label="Recommended Stack"
)

gr.Markdown("---")
gr.Markdown("### 💬 Ask a follow-up question")
with gr.Row():
followup_input = gr.Textbox(
label="Follow-up",
placeholder="e.g. Is there a cheaper alternative to Twilio? / How do I handle auth without Auth0?",
scale=4
)
followup_btn = gr.Button("Ask", scale=1, variant="secondary")

followup_output = gr.Markdown()

submit_btn.click(
get_stack_recommendation,
inputs=[idea_input, budget_input, level_input, market_input],
outputs=recommendation_output
)

followup_btn.click(
ask_followup,
inputs=[followup_input, recommendation_output],
outputs=followup_output
)

gr.Markdown("""
---
Built with [Gradio](https://gradio.app) + [Claude](https://anthropic.com) ·
[View on HuggingFace](https://huggingface.co/spaces/Alireza1913/Monetizable_API_Finder)
""")

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

Files changed (1) hide show
  1. app.py +0 -417
app.py DELETED
@@ -1,417 +0,0 @@
1
- import gradio as gr
2
- import requests
3
- from bs4 import BeautifulSoup
4
- import json
5
- import os
6
- import time
7
- import re
8
- from anthropic import Anthropic
9
-
10
- client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", ""))
11
-
12
- CURATED_APIS = [
13
- {
14
- "name": "OpenAI API",
15
- "category": "AI & ML",
16
- "provider": "openai.com",
17
- "pricing_model": "Pay-per-token",
18
- "entry_cost": "$0.002/1K tokens",
19
- "monthly_revenue_potential": "★★★★★",
20
- "description": "GPT-4, embeddings, vision, TTS/STT — the foundation of hundreds of profitable products.",
21
- "monetization_angles": [
22
- "Build a niche GPT wrapper (legal, medical, education)",
23
- "White-label chatbot SaaS for SMBs",
24
- "AI writing tool with tiered pricing",
25
- "RAG-based document Q&A platform"
26
- ],
27
- "entry_points": [
28
- "platform.openai.com — free $5 credit to start",
29
- "Available on RapidAPI for resell",
30
- "Deploy wrapper on HuggingFace Spaces free tier"
31
- ],
32
- "market_signal": "10M+ developers, $1.6B ARR (2024)"
33
- },
34
- {
35
- "name": "Stripe Payments",
36
- "category": "Finance",
37
- "provider": "stripe.com",
38
- "pricing_model": "2.9% + 30¢ per transaction",
39
- "entry_cost": "Free to integrate",
40
- "monthly_revenue_potential": "★★★★★",
41
- "description": "The world's leading payment API. Build billing layers, marketplaces, or subscription tools on top.",
42
- "monetization_angles": [
43
- "Subscription billing SaaS for non-technical founders",
44
- "Stripe Connect marketplace with revenue share",
45
- "Invoice + payment automation for freelancers",
46
- "Usage-based billing engine"
47
- ],
48
- "entry_points": [
49
- "stripe.com/docs — excellent documentation",
50
- "Stripe Connect for multi-party payments",
51
- "stripe.com/partners — official partner program"
52
- ],
53
- "market_signal": "Processes $817B annually, used by 3M+ businesses"
54
- },
55
- {
56
- "name": "AssemblyAI",
57
- "category": "AI & ML",
58
- "provider": "assemblyai.com",
59
- "pricing_model": "Pay-per-minute",
60
- "entry_cost": "$0.002/min (free tier available)",
61
- "monthly_revenue_potential": "★★★★☆",
62
- "description": "Best-in-class speech-to-text with speaker diarization, sentiment, and auto-chapters.",
63
- "monetization_angles": [
64
- "Meeting notes SaaS (Otter.ai competitor)",
65
- "Podcast transcription + search platform",
66
- "Video subtitle generation service",
67
- "Call center analytics tool"
68
- ],
69
- "entry_points": [
70
- "assemblyai.com — 5h free audio/month",
71
- "Python/JS SDK — fast to prototype",
72
- "HuggingFace integration examples available"
73
- ],
74
- "market_signal": "Speech recognition market: $26B by 2030"
75
- },
76
- {
77
- "name": "Twilio",
78
- "category": "Communication",
79
- "provider": "twilio.com",
80
- "pricing_model": "Pay-as-you-go",
81
- "entry_cost": "$0.0075/SMS",
82
- "monthly_revenue_potential": "★★★★☆",
83
- "description": "SMS, Voice, WhatsApp, and email APIs. Every business eventually needs messaging infrastructure.",
84
- "monetization_angles": [
85
- "OTP / 2FA service for apps",
86
- "SMS marketing platform for SMBs",
87
- "WhatsApp business automation",
88
- "No-code notification builder"
89
- ],
90
- "entry_points": [
91
- "twilio.com — $15 free credit on signup",
92
- "WhatsApp Business API via Twilio",
93
- "Twilio Marketplace for resell"
94
- ],
95
- "market_signal": "$4.1B revenue (2023), 330K+ active customers"
96
- },
97
- {
98
- "name": "Cloudinary",
99
- "category": "Media",
100
- "provider": "cloudinary.com",
101
- "pricing_model": "Freemium",
102
- "entry_cost": "Free up to 25GB",
103
- "monthly_revenue_potential": "★★★★☆",
104
- "description": "Image and video upload, transform, optimize, and deliver via CDN. Essential for any media-heavy product.",
105
- "monetization_angles": [
106
- "E-commerce image optimization SaaS",
107
- "Real estate photo enhancement tool",
108
- "Portfolio site builder with auto-optimization",
109
- "White-label media management for agencies"
110
- ],
111
- "entry_points": [
112
- "cloudinary.com/free — generous free tier",
113
- "All major SDKs available",
114
- "Add-on marketplace for resell"
115
- ],
116
- "market_signal": "Used by 1M+ developers, $2B valuation"
117
- },
118
- {
119
- "name": "Alpha Vantage",
120
- "category": "Finance",
121
- "provider": "alphavantage.co",
122
- "pricing_model": "Freemium",
123
- "entry_cost": "Free / $50/month premium",
124
- "monthly_revenue_potential": "★★★☆☆",
125
- "description": "Stocks, crypto, forex, and technical indicators. Solid data foundation for FinTech products.",
126
- "monetization_angles": [
127
- "Stock screener with custom alerts",
128
- "Portfolio tracker with AI analysis",
129
- "Trading signal bot (Telegram/Discord)",
130
- "Financial data dashboard for retail investors"
131
- ],
132
- "entry_points": [
133
- "alphavantage.co — free API key instantly",
134
- "Available on RapidAPI",
135
- "Combine with Claude for AI analysis layer"
136
- ],
137
- "market_signal": "FinTech market: $340B by 2026"
138
- },
139
- {
140
- "name": "OpenWeatherMap",
141
- "category": "Data",
142
- "provider": "openweathermap.org",
143
- "pricing_model": "Freemium",
144
- "entry_cost": "Free up to 1000 calls/day",
145
- "monthly_revenue_potential": "★★★☆☆",
146
- "description": "Weather data for current, forecast, and historical — useful in logistics, agriculture, and travel apps.",
147
- "monetization_angles": [
148
- "Weather widget for websites (embed + ads)",
149
- "Smart farming dashboard for agriculture",
150
- "Logistics route optimization tool",
151
- "Travel weather comparison app"
152
- ],
153
- "entry_points": [
154
- "openweathermap.org/api — instant key",
155
- "RapidAPI for managed resell",
156
- "Combine with mapping API for geo-weather"
157
- ],
158
- "market_signal": "Used in 40K+ apps worldwide"
159
- },
160
- {
161
- "name": "Clearbit Enrichment",
162
- "category": "Data",
163
- "provider": "clearbit.com",
164
- "pricing_model": "Usage-based",
165
- "entry_cost": "Free 50 lookups/month",
166
- "monthly_revenue_potential": "★★★★☆",
167
- "description": "B2B company and contact data enrichment — essential for sales teams and lead generation tools.",
168
- "monetization_angles": [
169
- "Lead enrichment plugin for CRMs",
170
- "Sales intelligence SaaS for SMBs",
171
- "ICP scoring tool for startups",
172
- "LinkedIn + email finder combo tool"
173
- ],
174
- "entry_points": [
175
- "clearbit.com/platform — free tier available",
176
- "HubSpot / Salesforce integration",
177
- "Build an enrichment layer for smaller CRMs"
178
- ],
179
- "market_signal": "Acquired by HubSpot for $150M+"
180
- },
181
- ]
182
-
183
- CATEGORIES = ["All"] + sorted(set(a["category"] for a in CURATED_APIS))
184
-
185
- def get_stars(s):
186
- return s
187
-
188
- def analyze_api_with_claude(api_name, user_context):
189
- """Use Claude to generate a personalized action plan for a chosen API."""
190
- if not client.api_key:
191
- return "⚠️ Set your ANTHROPIC_API_KEY environment variable to enable AI analysis."
192
-
193
- prompt = f"""You are an expert in API monetization and lean startup strategy.
194
-
195
- The user wants to build a profitable product using: **{api_name}**
196
-
197
- User context: {user_context if user_context.strip() else "No additional context provided."}
198
-
199
- Give a concise, actionable response structured as:
200
-
201
- ## 🎯 Best Niche for You
202
- (1-2 sentences on the highest-leverage use case)
203
-
204
- ## 🔨 MVP in 48 Hours
205
- (3-5 bullet points — concrete steps to a working prototype)
206
-
207
- ## 💰 Pricing Strategy
208
- (How to charge, what tiers make sense, realistic MRR target for month 6)
209
-
210
- ## ⚠️ Top Risk
211
- (The #1 thing that could kill this idea and how to validate it fast)
212
-
213
- Keep it sharp, honest, and specific. No fluff."""
214
-
215
- try:
216
- response = client.messages.create(
217
- model="claude-sonnet-4-6",
218
- max_tokens=800,
219
- messages=[{"role": "user", "content": prompt}]
220
- )
221
- return response.content[0].text
222
- except Exception as e:
223
- return f"Error calling Claude API: {str(e)}"
224
-
225
- def scrape_rapidapi_trending():
226
- """Scrape RapidAPI trending/popular APIs for live discovery."""
227
- results = []
228
- try:
229
- headers = {
230
- "User-Agent": "Mozilla/5.0 (compatible; APIScout/1.0)"
231
- }
232
- url = "https://rapidapi.com/hub"
233
- resp = requests.get(url, headers=headers, timeout=8)
234
- soup = BeautifulSoup(resp.text, "html.parser")
235
-
236
- cards = soup.find_all("div", class_=re.compile(r"api-card|ApiCard|card", re.I))[:12]
237
- for card in cards:
238
- name_el = card.find(["h3", "h4", "strong", "span"], class_=re.compile(r"name|title", re.I))
239
- if name_el and len(name_el.get_text(strip=True)) > 3:
240
- results.append(name_el.get_text(strip=True))
241
- except Exception:
242
- pass
243
-
244
- if not results:
245
- results = [
246
- "Spotify Web API", "YouTube Data API", "Twitter/X API",
247
- "Google Maps API", "Shopify Admin API", "Slack API",
248
- "GitHub REST API", "SendGrid Email API"
249
- ]
250
- return list(dict.fromkeys(results))[:8]
251
-
252
- def filter_apis(category):
253
- if category == "All":
254
- filtered = CURATED_APIS
255
- else:
256
- filtered = [a for a in CURATED_APIS if a["category"] == category]
257
- return build_api_table(filtered)
258
-
259
- def build_api_table(apis):
260
- rows = []
261
- for a in apis:
262
- rows.append([
263
- a["name"],
264
- a["category"],
265
- a["pricing_model"],
266
- a["entry_cost"],
267
- a["monthly_revenue_potential"],
268
- a["market_signal"]
269
- ])
270
- return rows
271
-
272
- def get_api_detail(api_name):
273
- api = next((a for a in CURATED_APIS if a["name"] == api_name), None)
274
- if not api:
275
- return "", "", ""
276
-
277
- angles = "\n".join(f"• {m}" for m in api["monetization_angles"])
278
- entry = "\n".join(f"→ {e}" for e in api["entry_points"])
279
-
280
- detail = f"""### {api["name"]}
281
- **Provider:** {api["provider"]}
282
- **Category:** {api["category"]}
283
- **Pricing:** {api["pricing_model"]} — {api["entry_cost"]}
284
- **Market Signal:** {api["market_signal"]}
285
-
286
- ---
287
- {api["description"]}
288
-
289
- **Monetization Angles:**
290
- {angles}
291
-
292
- **How to Get Started:**
293
- {entry}
294
- """
295
- return detail, api["name"], gr.update(interactive=True)
296
-
297
- def run_analysis(api_name, user_context):
298
- if not api_name:
299
- return "Select an API from the table first."
300
- yield "⏳ Claude is analyzing your opportunity..."
301
- result = analyze_api_with_claude(api_name, user_context)
302
- yield result
303
-
304
- def discover_live():
305
- yield "🔍 Scanning RapidAPI for trending APIs..."
306
- time.sleep(1)
307
- found = scrape_rapidapi_trending()
308
- output = "### 🌐 Trending APIs Discovered on RapidAPI\n\n"
309
- output += "| # | API Name |\n|---|----------|\n"
310
- for i, name in enumerate(found, 1):
311
- output += f"| {i} | {name} |\n"
312
- output += "\n> Select any of these from the curated list or ask Claude to analyze one by name."
313
- yield output
314
-
315
- css = """
316
- .gradio-container { max-width: 1100px !important; margin: auto; }
317
- .api-table { font-size: 14px; }
318
- footer { display: none !important; }
319
- """
320
-
321
- with gr.Blocks(css=css, title="Monetizable API Finder") as demo:
322
- gr.Markdown("""
323
- # 🔍 Monetizable API Finder
324
- **Discover APIs you can build profitable products on — powered by Claude**
325
-
326
- Browse curated high-potential APIs, see monetization angles, and get a personalized action plan from Claude.
327
- """)
328
-
329
- with gr.Tabs():
330
-
331
- with gr.Tab("📊 Browse APIs"):
332
- with gr.Row():
333
- cat_filter = gr.Dropdown(
334
- choices=CATEGORIES,
335
- value="All",
336
- label="Filter by category",
337
- scale=2
338
- )
339
- discover_btn = gr.Button("🌐 Discover Live from RapidAPI", scale=3, variant="secondary")
340
-
341
- api_table = gr.Dataframe(
342
- headers=["Name", "Category", "Pricing Model", "Entry Cost", "Revenue Potential ★", "Market Signal"],
343
- value=build_api_table(CURATED_APIS),
344
- interactive=False,
345
- label="Click a row to select an API",
346
- elem_classes=["api-table"],
347
- wrap=True
348
- )
349
-
350
- live_output = gr.Markdown(visible=True)
351
-
352
- cat_filter.change(filter_apis, inputs=cat_filter, outputs=api_table)
353
- discover_btn.click(discover_live, outputs=live_output)
354
-
355
- with gr.Tab("🔎 API Detail + Action Plan"):
356
- with gr.Row():
357
- api_selector = gr.Dropdown(
358
- choices=[a["name"] for a in CURATED_APIS],
359
- label="Select an API to analyze",
360
- scale=3
361
- )
362
- load_btn = gr.Button("Load Details", variant="secondary", scale=1)
363
-
364
- api_detail_md = gr.Markdown("_Select an API above and click Load Details._")
365
-
366
- gr.Markdown("### 🤖 Get Your Personalized Action Plan")
367
- user_context = gr.Textbox(
368
- label="Tell Claude about yourself (optional)",
369
- placeholder="e.g. I'm a solo developer in Iran, budget < $100/month, targeting local SMBs...",
370
- lines=2
371
- )
372
- selected_api_state = gr.State("")
373
- analyze_btn = gr.Button("⚡ Generate Action Plan with Claude", variant="primary", interactive=False)
374
- analysis_output = gr.Markdown("_Your personalized plan will appear here._")
375
-
376
- load_btn.click(
377
- get_api_detail,
378
- inputs=api_selector,
379
- outputs=[api_detail_md, selected_api_state, analyze_btn]
380
- )
381
- analyze_btn.click(
382
- run_analysis,
383
- inputs=[selected_api_state, user_context],
384
- outputs=analysis_output
385
- )
386
-
387
- with gr.Tab("ℹ️ How to Use"):
388
- gr.Markdown("""
389
- ## How This Tool Works
390
-
391
- ### 1. Browse the curated list
392
- All APIs are scored and curated based on:
393
- - **Revenue potential** — how many profitable products have been built on them
394
- - **Low barrier to entry** — free tiers, good docs, fast prototyping
395
- - **Market signal** — real growth data backing the opportunity
396
-
397
- ### 2. Discover live APIs
398
- Click **"Discover Live from RapidAPI"** to pull trending APIs in real-time.
399
-
400
- ### 3. Get your action plan
401
- Select any API → click **Load Details** → optionally describe your background → click **Generate Action Plan**.
402
-
403
- Claude will give you:
404
- - The best niche to target
405
- - An MVP you can build in 48 hours
406
- - A realistic pricing strategy
407
- - The top risk to validate first
408
-
409
- ### 4. Deploy your own
410
- Fork this Space → add your `ANTHROPIC_API_KEY` secret → customize the curated list.
411
-
412
- ---
413
- **Built with:** Gradio · Anthropic Claude · BeautifulSoup · HuggingFace Spaces
414
- """)
415
-
416
- if __name__ == "__main__":
417
- demo.launch()