Alireza1913 commited on
Commit
da07eff
Β·
verified Β·
1 Parent(s): cce671b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -127
app.py CHANGED
@@ -1,134 +1,93 @@
1
  import gradio as gr
2
  import os
3
- import requests
4
-
5
- HF_TOKEN = os.environ.get("HF_TOKEN", "")
6
-
7
- # Using a reliable free model on HuggingFace
8
- API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
9
-
10
- def query_model(prompt):
11
- if not HF_TOKEN:
12
- return None, (
13
- "⚠️ **HF_TOKEN is not set.**\n\n"
14
- "Space Settings β†’ Secrets β†’ New secret\n"
15
- "- Name: `HF_TOKEN`\n"
16
- "- Value: your token from huggingface.co/settings/tokens"
17
- )
18
-
19
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
20
-
21
- full_prompt = f"<|system|>\nYou are an expert API architect and startup advisor.\n</s>\n<|user|>\n{prompt}\n</s>\n<|assistant|>\n"
22
-
23
- payload = {
24
- "inputs": full_prompt,
25
- "parameters": {
26
- "max_new_tokens": 1000,
27
- "temperature": 0.7,
28
- "do_sample": True,
29
- "return_full_text": False,
30
- "stop": ["<|user|>", "</s>"]
31
- }
32
- }
33
-
34
- try:
35
- response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
36
-
37
- if response.status_code == 503:
38
- return None, "⏳ Model is loading (cold start). Wait 30 seconds and try again."
39
- if response.status_code == 401:
40
- return None, "❌ Invalid HF_TOKEN. Go to Space Settings and check your token."
41
- if response.status_code == 429:
42
- return None, "❌ Rate limit. Wait 1 minute and try again."
43
- if response.status_code != 200:
44
- return None, f"❌ API Error {response.status_code}: {response.text[:300]}"
45
-
46
- data = response.json()
47
-
48
- if isinstance(data, list) and len(data) > 0:
49
- text = data[0].get("generated_text", "").strip()
50
- if text:
51
- return text, None
52
-
53
- if isinstance(data, dict) and "error" in data:
54
- return None, f"❌ Model error: {data['error']}"
55
-
56
- return None, f"❌ Empty response from model. Try again."
57
-
58
- except requests.exceptions.Timeout:
59
- return None, "⏳ Request timed out. The model may be loading. Try again in 30 seconds."
60
- except Exception as e:
61
- return None, f"❌ Error: {str(e)}"
62
 
63
 
64
  def get_stack(idea, budget, level, market):
65
  if not idea.strip():
66
  return "⚠️ Please describe your product idea."
 
 
 
67
 
68
- prompt = f"""I want to build: {idea}
69
-
70
- My monthly API budget: {budget}
71
- My technical level: {level}
72
- My target market: {market}
73
-
74
- Please recommend the best API stack for my product using this format:
75
-
76
- ## 🎯 My Idea
77
- (one sentence summary)
78
 
79
- ## πŸ”§ Recommended APIs
 
80
 
81
- ### [API Name] β€” [what it does in my product]
82
- - What it does: (one sentence)
83
- - Pricing: (free tier details + paid pricing)
84
  - Docs: (URL)
85
- - Difficulty: Easy / Medium / Hard
86
-
87
- (repeat for 3-5 APIs)
88
 
89
- ## πŸ’° Monthly Cost Estimate
90
  - 100 users: $X/month
91
  - 1,000 users: $X/month
92
- - 10,000 users: $X/month
93
 
94
  ## ⚑ Build Order
95
- 1. Start with [API] because...
96
- 2. Then add [API] because...
97
- 3. Finally [API] because...
98
 
99
- ## 🚨 Biggest Mistake to Avoid
100
  (one paragraph)"""
101
-
102
- result, error = query_model(prompt)
103
- if error:
104
- return error
105
- return result if result else "❌ No response received. Please try again."
106
 
107
 
108
  def ask_followup(question, prev):
109
  if not question.strip():
110
  return ""
111
  if not prev or prev.startswith("⚠️") or prev.startswith("❌"):
112
- return "⚠️ Generate a stack recommendation first, then ask follow-up questions."
113
-
114
- prompt = f"""Based on this API stack recommendation:
115
- {prev[:600]}
116
-
117
- Answer this follow-up question clearly and concisely:
118
- {question}"""
119
-
120
- result, error = query_model(prompt)
121
- if error:
122
- return error
123
- return result if result else "❌ No response. Please try again."
124
 
125
 
126
  EXAMPLES = [
127
- ["A Notion-like notes app with AI summarization", "$50/month", "Intermediate", "Students"],
128
- ["SMS marketing platform for small restaurants", "$30/month", "Beginner", "Restaurant owners"],
129
- ["Job board that auto-matches candidates with AI", "$100/month", "Advanced", "Tech recruiters"],
130
- ["Podcast transcription and highlight tool", "$20/month", "Beginner", "Podcasters"],
131
- ["Crypto portfolio tracker with price alerts", "$0 (free only)", "Intermediate", "Retail investors"],
132
  ]
133
 
134
  css = """
@@ -139,24 +98,22 @@ footer { display: none !important; }
139
  with gr.Blocks(css=css, title="API Stack Finder") as demo:
140
  gr.Markdown("""
141
  # πŸ”§ API Stack Finder
142
- **Describe your product idea β†’ Get the perfect API stack, pricing, and build order**
143
 
144
- Powered by **Zephyr-7B** via HuggingFace Inference API β€” 100% Free.
145
  """)
146
 
147
  with gr.Row():
148
  with gr.Column(scale=3):
149
  idea_input = gr.Textbox(
150
  label="Describe your product idea",
151
- placeholder="e.g. A platform where freelancers sell services and get paid instantly...",
152
  lines=4
153
  )
154
  with gr.Column(scale=1):
155
  budget_input = gr.Dropdown(
156
- choices=[
157
- "$0 (free only)", "$10/month", "$30/month",
158
- "$50/month", "$100/month", "$500/month", "Unlimited"
159
- ],
160
  value="$30/month",
161
  label="Monthly API budget"
162
  )
@@ -174,7 +131,7 @@ Powered by **Zephyr-7B** via HuggingFace Inference API β€” 100% Free.
174
  gr.Markdown("**Try an example:**")
175
  with gr.Row():
176
  for ex in EXAMPLES:
177
- gr.Button(ex[0][:32] + "...", size="sm").click(
178
  lambda e=ex: (e[0], e[1], e[2], e[3]),
179
  outputs=[idea_input, budget_input, level_input, market_input]
180
  )
@@ -184,7 +141,6 @@ Powered by **Zephyr-7B** via HuggingFace Inference API β€” 100% Free.
184
 
185
  gr.Markdown("---")
186
  gr.Markdown("### πŸ’¬ Ask a follow-up")
187
-
188
  with gr.Row():
189
  followup_input = gr.Textbox(
190
  label="Follow-up question",
@@ -192,25 +148,16 @@ Powered by **Zephyr-7B** via HuggingFace Inference API β€” 100% Free.
192
  scale=4
193
  )
194
  followup_btn = gr.Button("Ask", scale=1, variant="secondary")
195
-
196
  followup_output = gr.Markdown()
197
 
198
- submit_btn.click(
199
- get_stack,
200
  inputs=[idea_input, budget_input, level_input, market_input],
201
- outputs=output
202
- )
203
- followup_btn.click(
204
- ask_followup,
205
  inputs=[followup_input, output],
206
- outputs=followup_output
207
- )
208
 
209
- gr.Markdown("""
210
- ---
211
- πŸ€– Model: `Zephyr-7B-Beta` Β· πŸ†“ Free via HuggingFace
212
- πŸ”‘ Get token: [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
213
- """)
214
 
215
  if __name__ == "__main__":
216
  demo.launch()
 
1
  import gradio as gr
2
  import os
3
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
4
+ import torch
5
+
6
+ MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
7
+
8
+ print("Loading model...")
9
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
10
+ pipe = pipeline(
11
+ "text-generation",
12
+ model=MODEL_ID,
13
+ torch_dtype=torch.float32,
14
+ device_map="auto"
15
+ )
16
+ print("Model loaded.")
17
+
18
+ SYSTEM = """You are an expert API architect. When given a product idea, recommend the best API stack with pricing and build order."""
19
+
20
+ def generate(prompt):
21
+ messages = [
22
+ {"role": "system", "content": SYSTEM},
23
+ {"role": "user", "content": prompt}
24
+ ]
25
+ formatted = tokenizer.apply_chat_template(
26
+ messages,
27
+ tokenize=False,
28
+ add_generation_prompt=True
29
+ )
30
+ out = pipe(
31
+ formatted,
32
+ max_new_tokens=800,
33
+ do_sample=True,
34
+ temperature=0.7,
35
+ return_full_text=False
36
+ )
37
+ return out[0]["generated_text"].strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
 
40
  def get_stack(idea, budget, level, market):
41
  if not idea.strip():
42
  return "⚠️ Please describe your product idea."
43
+ try:
44
+ prompt = f"""Product idea: {idea}
45
+ Budget: {budget} | Level: {level} | Market: {market}
46
 
47
+ Recommend 3-5 APIs using this format:
 
 
 
 
 
 
 
 
 
48
 
49
+ ## 🎯 Idea Summary
50
+ (one line)
51
 
52
+ ## πŸ”§ API Stack
53
+ ### [API Name] β€” [role]
54
+ - Pricing: (free tier + paid)
55
  - Docs: (URL)
56
+ - Difficulty: Easy/Medium/Hard
 
 
57
 
58
+ ## πŸ’° Cost Estimate
59
  - 100 users: $X/month
60
  - 1,000 users: $X/month
 
61
 
62
  ## ⚑ Build Order
63
+ 1. First: [API]
64
+ 2. Second: [API]
 
65
 
66
+ ## 🚨 Top Mistake
67
  (one paragraph)"""
68
+ return generate(prompt)
69
+ except Exception as e:
70
+ return f"❌ Error: {str(e)}"
 
 
71
 
72
 
73
  def ask_followup(question, prev):
74
  if not question.strip():
75
  return ""
76
  if not prev or prev.startswith("⚠️") or prev.startswith("❌"):
77
+ return "⚠️ Generate a recommendation first."
78
+ try:
79
+ prompt = f"Previous recommendation:\n{prev[:500]}\n\nFollow-up: {question}\n\nAnswer concisely."
80
+ return generate(prompt)
81
+ except Exception as e:
82
+ return f"❌ Error: {str(e)}"
 
 
 
 
 
 
83
 
84
 
85
  EXAMPLES = [
86
+ ["A notes app with AI summarization", "$50/month", "Intermediate", "Students"],
87
+ ["SMS marketing for restaurants", "$30/month", "Beginner", "Restaurant owners"],
88
+ ["AI job matching platform", "$100/month", "Advanced", "Tech recruiters"],
89
+ ["Podcast transcription tool", "$20/month", "Beginner", "Podcasters"],
90
+ ["Crypto portfolio tracker", "$0 (free only)", "Intermediate", "Retail investors"],
91
  ]
92
 
93
  css = """
 
98
  with gr.Blocks(css=css, title="API Stack Finder") as demo:
99
  gr.Markdown("""
100
  # πŸ”§ API Stack Finder
101
+ **Describe your product idea β†’ Get the perfect API stack**
102
 
103
+ Powered by **TinyLlama** β€” runs locally inside this Space, no external API needed.
104
  """)
105
 
106
  with gr.Row():
107
  with gr.Column(scale=3):
108
  idea_input = gr.Textbox(
109
  label="Describe your product idea",
110
+ placeholder="e.g. A freelancer marketplace with instant payments...",
111
  lines=4
112
  )
113
  with gr.Column(scale=1):
114
  budget_input = gr.Dropdown(
115
+ choices=["$0 (free only)", "$10/month", "$30/month",
116
+ "$50/month", "$100/month", "$500/month", "Unlimited"],
 
 
117
  value="$30/month",
118
  label="Monthly API budget"
119
  )
 
131
  gr.Markdown("**Try an example:**")
132
  with gr.Row():
133
  for ex in EXAMPLES:
134
+ gr.Button(ex[0][:30] + "...", size="sm").click(
135
  lambda e=ex: (e[0], e[1], e[2], e[3]),
136
  outputs=[idea_input, budget_input, level_input, market_input]
137
  )
 
141
 
142
  gr.Markdown("---")
143
  gr.Markdown("### πŸ’¬ Ask a follow-up")
 
144
  with gr.Row():
145
  followup_input = gr.Textbox(
146
  label="Follow-up question",
 
148
  scale=4
149
  )
150
  followup_btn = gr.Button("Ask", scale=1, variant="secondary")
 
151
  followup_output = gr.Markdown()
152
 
153
+ submit_btn.click(get_stack,
 
154
  inputs=[idea_input, budget_input, level_input, market_input],
155
+ outputs=output)
156
+ followup_btn.click(ask_followup,
 
 
157
  inputs=[followup_input, output],
158
+ outputs=followup_output)
 
159
 
160
+ gr.Markdown("---\nπŸ€– Model: `TinyLlama-1.1B-Chat` Β· Runs fully inside HuggingFace Space")
 
 
 
 
161
 
162
  if __name__ == "__main__":
163
  demo.launch()