bilalnaveed commited on
Commit
5291dfc
Β·
verified Β·
1 Parent(s): b78d77c

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +468 -127
app.py CHANGED
@@ -1,12 +1,17 @@
1
  """
2
- Naveed AI - Gradio Interface for Hugging Face Spaces
3
- Real-time chat with streaming, code snippets, and embed widget.
 
4
  """
5
 
6
  import gradio as gr
7
  import time
8
  import os
 
 
 
9
  from pathlib import Path
 
10
 
11
  # -- Load Model ---------------------------------------------------------------
12
  from config import get_config
@@ -16,41 +21,201 @@ from conversation import Conversation
16
  config = get_config()
17
  chatbot = ChatBot(config)
18
 
19
- print("Loading Naveed AI model...")
20
- chatbot.initialize(model_id="qwen2.5-1.5b", auto_download=True, warmup=True)
21
- print("Naveed AI ready!")
22
-
23
 
24
- # -- Chat Function (streaming) ------------------------------------------------
25
- def chat_fn(message, history):
26
- """Stream response token-by-token."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  if not message.strip():
28
- return
29
 
30
  # Build conversation from history
31
  conv = Conversation(config=config)
32
- for user_msg, ai_msg in history:
33
- conv.add_user_message(user_msg)
34
- if ai_msg:
35
- conv.add_assistant_message(ai_msg)
 
36
  conv.add_user_message(message)
37
 
38
- messages = conv.get_chat_messages()
39
 
40
  # Stream tokens
41
  partial = ""
42
- for token in chatbot.engine.chat_generate(messages, stream=True):
43
  partial += token
44
- yield partial
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
 
 
 
 
 
 
46
 
47
- # -- Code Snippets -------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  SPACE_URL = "https://bilalnaveed-naveedai.hf.space"
49
 
50
  PYTHON_CODE = '''# pip install gradio_client
51
  from gradio_client import Client
52
 
 
53
  client = Client("bilalnaveed/Naveedai")
 
 
54
  result = client.predict(
55
  message="Hello, who are you?",
56
  api_name="/chat"
@@ -58,153 +223,329 @@ result = client.predict(
58
  print(result)
59
  '''
60
 
61
- JAVASCRIPT_CODE = '''// Use Naveed AI from any website
62
- const response = await fetch("https://bilalnaveed-naveedai.hf.space/api/predict", {
63
- method: "POST",
64
- headers: { "Content-Type": "application/json" },
65
- body: JSON.stringify({
66
- data: ["Hello, who are you?"]
67
- })
68
- });
69
- const result = await response.json();
70
- console.log(result.data[0]);
71
- '''
72
-
73
- CURL_CODE = '''curl -X POST https://bilalnaveed-naveedai.hf.space/api/predict \\
 
 
 
 
74
  -H "Content-Type: application/json" \\
75
- -d '{"data": ["Hello, who are you?"]}'
76
  '''
77
 
78
- EMBED_IFRAME = '''<!-- Add Naveed AI chatbot to any website -->
79
  <iframe
80
- src="https://bilalnaveed-naveedai.hf.space"
81
  frameborder="0"
82
  width="100%"
83
- height="600"
84
- style="border-radius: 12px; border: 1px solid #333;"
 
85
  ></iframe>
86
  '''
87
 
88
- EMBED_WIDGET = '''<!-- Gradio Web Component (auto-loads) -->
89
- <script
90
- type="module"
91
- src="https://gradio.s3-us-west-2.amazonaws.com/4.44.1/gradio.js"
92
- ></script>
93
- <gradio-app src="https://bilalnaveed-naveedai.hf.space"></gradio-app>
94
  '''
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  # -- Build Gradio UI ----------------------------------------------------------
98
  with gr.Blocks(
99
- title="Naveed AI",
100
- theme=gr.themes.Base(
101
- primary_hue="purple",
102
- neutral_hue="gray",
 
103
  font=gr.themes.GoogleFont("Inter"),
104
  ),
105
- css="""
106
- .contain { max-width: 900px; margin: auto; }
107
- footer { display: none !important; }
108
- """
109
  ) as demo:
110
 
111
  # Header
112
- gr.Markdown(
113
- """
114
- <div style="text-align:center; padding: 20px 0 10px;">
115
- <h1 style="font-size:2.2em; margin:0;">Naveed AI</h1>
116
- <p style="color:#888; font-size:1.05em; margin-top:4px;">
117
- Created by <strong>Naveed Khan</strong> β€” Intelligent AI Assistant for Education
118
- </p>
119
- </div>
120
- """
121
- )
122
 
123
  with gr.Tabs():
124
 
125
- # Tab 1: Chat
126
- with gr.TabItem("Chat"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  gr.ChatInterface(
128
  fn=chat_fn,
 
 
129
  chatbot=gr.Chatbot(
130
- height=500,
131
- placeholder="<div style='text-align:center;color:#888;padding:40px;'>"
132
- "<h2>How can I help you today?</h2>"
133
- "<p>I am Naveed AI, ask me anything!</p></div>",
134
- label="Naveed AI",
 
 
 
 
135
  show_copy_button=True,
 
136
  ),
137
  textbox=gr.Textbox(
138
- placeholder="Message Naveed AI...",
139
  container=False,
140
  scale=7,
141
  ),
142
  title="",
143
- retry_btn="Retry",
144
- undo_btn="Undo",
145
- clear_btn="Clear",
146
  examples=[
147
- "Who are you?",
148
- "What is artificial intelligence?",
149
- "Write a Python function to check prime numbers",
150
- "Explain machine learning in simple words",
 
 
151
  ],
152
  )
153
 
154
- # Tab 2: API Code Snippets
155
- with gr.TabItem("Use API"):
156
- gr.Markdown("### Use Naveed AI in your own projects\nCopy any code snippet below to call Naveed AI from your app.")
157
-
158
- with gr.Accordion("Python", open=True):
159
- gr.Code(value=PYTHON_CODE, language="python", label="Python Client")
160
-
161
- with gr.Accordion("JavaScript", open=False):
162
- gr.Code(value=JAVASCRIPT_CODE, language="javascript", label="JavaScript Fetch")
163
-
164
- with gr.Accordion("cURL", open=False):
165
- gr.Code(value=CURL_CODE, language="shell", label="cURL Command")
166
-
167
- # Tab 3: Embed on Website
168
- with gr.TabItem("Embed"):
169
- gr.Markdown("### Embed Naveed AI on any website\nCopy the code and paste into your HTML page.")
170
-
171
- with gr.Accordion("iframe Embed (Simple)", open=True):
172
- gr.Code(value=EMBED_IFRAME, language="html", label="iframe Code")
173
-
174
- with gr.Accordion("Gradio Widget (Advanced)", open=False):
175
- gr.Code(value=EMBED_WIDGET, language="html", label="Gradio Web Component")
176
-
177
- gr.Markdown(
178
- "**Live URL:** [https://bilalnaveed-naveedai.hf.space](https://bilalnaveed-naveedai.hf.space)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  )
180
 
181
- # Tab 4: About
182
- with gr.TabItem("About"):
183
- gr.Markdown(
184
- """
185
- ### About Naveed AI
186
-
187
- | Detail | Info |
188
- |--------|------|
189
- | **Created by** | Naveed Khan |
190
- | **Purpose** | Educational AI Assistant |
191
- | **Model** | Qwen2.5-1.5B-Instruct (4-bit quantized) |
192
- | **Parameters** | 1.5 Billion |
193
- | **Engine** | llama-cpp-python (GGUF) |
194
- | **Inference** | CPU, ~15-30 tokens/sec |
195
-
196
- ### Features
197
- - Real-time streaming chat
198
- - API access (Python, JavaScript, cURL)
199
- - Embeddable widget for any website
200
- - Context-aware conversation memory
201
- - Fast 4-bit quantized inference
202
-
203
- ---
204
- *Built by Naveed Khan for learning and education.*
205
- """
206
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
  # -- Launch --------------------------------------------------------------------
209
  if __name__ == "__main__":
210
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
1
  """
2
+ Naveed AI β€” Advanced Intelligent Assistant
3
+ Built by Naveed Khan | Speech-to-Text β€’ Image Reading β€’ Thinking Mode β€’ Emoji Responses
4
+ Completely free forever β€” embed on any website!
5
  """
6
 
7
  import gradio as gr
8
  import time
9
  import os
10
+ import re
11
+ import json
12
+ import base64
13
  from pathlib import Path
14
+ from typing import Optional
15
 
16
  # -- Load Model ---------------------------------------------------------------
17
  from config import get_config
 
21
  config = get_config()
22
  chatbot = ChatBot(config)
23
 
24
+ # Detect HuggingFace Spaces environment
25
+ IS_HF_SPACE = os.environ.get("SPACE_ID") is not None
 
 
26
 
27
+ print("πŸš€ Loading Naveed AI model...")
28
+ chatbot.initialize(model_id="qwen2.5-1.5b", auto_download=True, warmup=True)
29
+ print("βœ… Naveed AI ready!")
30
+
31
+
32
+ # -- HuggingFace Inference API helpers ----------------------------------------
33
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
34
+
35
+
36
+ def call_hf_api(api_url: str, payload: dict = None, files: dict = None):
37
+ """Call HuggingFace free inference API."""
38
+ import requests
39
+ headers = {}
40
+ if HF_TOKEN:
41
+ headers["Authorization"] = f"Bearer {HF_TOKEN}"
42
+
43
+ try:
44
+ if files:
45
+ resp = requests.post(api_url, headers=headers, files=files, timeout=120)
46
+ elif payload:
47
+ headers["Content-Type"] = "application/json"
48
+ resp = requests.post(api_url, headers=headers, json=payload, timeout=120)
49
+ else:
50
+ resp = requests.post(api_url, headers=headers, timeout=120)
51
+
52
+ if resp.status_code == 200:
53
+ return resp.json()
54
+ else:
55
+ return {"error": f"API error {resp.status_code}: {resp.text[:200]}"}
56
+ except Exception as e:
57
+ return {"error": str(e)}
58
+
59
+
60
+ # -- Format thinking blocks ---------------------------------------------------
61
+ def format_thinking(text: str) -> str:
62
+ """Format <think>...</think> blocks into styled display."""
63
+ def replace_think(match):
64
+ thought = match.group(1).strip()
65
+ return (
66
+ "\n\nπŸ’­ **Thinking Process:**\n"
67
+ f"> {thought}\n\n"
68
+ "---\n\n"
69
+ "βœ… **Answer:**\n"
70
+ )
71
+ return re.sub(r'<think>(.*?)</think>', replace_think, text, flags=re.DOTALL)
72
+
73
+
74
+ # -- Chat Function (streaming with thinking mode) -----------------------------
75
+ def chat_fn(message, history, thinking_mode):
76
+ """Stream response token-by-token with optional thinking mode."""
77
  if not message.strip():
78
+ return ""
79
 
80
  # Build conversation from history
81
  conv = Conversation(config=config)
82
+ for h in history:
83
+ if h["role"] == "user":
84
+ conv.add_user_message(h["content"])
85
+ elif h["role"] == "assistant":
86
+ conv.add_assistant_message(h["content"])
87
  conv.add_user_message(message)
88
 
89
+ messages = conv.get_chat_messages(thinking_mode=thinking_mode)
90
 
91
  # Stream tokens
92
  partial = ""
93
+ for token in chatbot.engine.chat_generate(messages, stream=True, thinking_mode=thinking_mode):
94
  partial += token
95
+ display = format_thinking(partial)
96
+ yield display
97
+
98
+
99
+ # -- Speech-to-Text Function --------------------------------------------------
100
+ def speech_to_text(audio_path):
101
+ """Convert speech to text using HuggingFace Whisper API."""
102
+ if audio_path is None:
103
+ return "🎀 Please record or upload audio first."
104
+
105
+ try:
106
+ API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3-turbo"
107
+
108
+ with open(audio_path, "rb") as f:
109
+ audio_data = f.read()
110
+
111
+ result = call_hf_api(
112
+ API_URL,
113
+ files={"file": ("audio.wav", audio_data, "audio/wav")},
114
+ )
115
 
116
+ if isinstance(result, dict) and "error" in result:
117
+ API_URL2 = "https://api-inference.huggingface.co/models/openai/whisper-small"
118
+ result = call_hf_api(
119
+ API_URL2,
120
+ files={"file": ("audio.wav", audio_data, "audio/wav")},
121
+ )
122
 
123
+ if isinstance(result, dict):
124
+ if "text" in result:
125
+ return f"πŸ“ **Transcribed Text:**\n\n{result['text'].strip()}"
126
+ elif "error" in result:
127
+ return f"⚠️ API busy, please try again in a moment.\n\nError: {result['error']}"
128
+
129
+ return f"πŸ“ **Transcribed Text:**\n\n{result}"
130
+
131
+ except Exception as e:
132
+ return f"❌ Error: {str(e)}\n\nπŸ’‘ Tip: Try a shorter audio clip or WAV format."
133
+
134
+
135
+ # -- Image Reading Function ---------------------------------------------------
136
+ def read_image(image, question):
137
+ """Analyze image using HuggingFace free vision API."""
138
+ if image is None:
139
+ return "πŸ–ΌοΈ Please upload an image first."
140
+
141
+ if not question or not question.strip():
142
+ question = "Describe this image in detail. What do you see?"
143
+
144
+ try:
145
+ import io
146
+ from PIL import Image as PILImage
147
+ import numpy as np
148
+
149
+ if isinstance(image, np.ndarray):
150
+ img = PILImage.fromarray(image)
151
+ elif isinstance(image, str):
152
+ img = PILImage.open(image)
153
+ else:
154
+ img = image
155
+
156
+ buffer = io.BytesIO()
157
+ img.save(buffer, format="PNG")
158
+ img_bytes = buffer.getvalue()
159
+
160
+ # Try BLIP-2 for image captioning
161
+ API_URL = "https://api-inference.huggingface.co/models/Salesforce/blip2-opt-2.7b"
162
+ result = call_hf_api(API_URL, files={"file": ("image.png", img_bytes, "image/png")})
163
+
164
+ caption = ""
165
+ if isinstance(result, list) and len(result) > 0:
166
+ caption = result[0].get("generated_text", "")
167
+ elif isinstance(result, dict) and "generated_text" in result:
168
+ caption = result["generated_text"]
169
+ elif isinstance(result, dict) and "error" in result:
170
+ API_URL2 = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
171
+ result = call_hf_api(API_URL2, files={"file": ("image.png", img_bytes, "image/png")})
172
+ if isinstance(result, list) and len(result) > 0:
173
+ caption = result[0].get("generated_text", "")
174
+
175
+ if not caption:
176
+ return "⚠️ Could not analyze the image. The vision API may be loading β€” please try again in 30 seconds."
177
+
178
+ # Use our LLM to give a detailed answer based on the caption
179
+ analysis_prompt = [
180
+ {"role": "system", "content": (
181
+ "You are Naveed AI, an advanced image analysis assistant created by Naveed Khan. "
182
+ "You have been given an image description from a vision model. "
183
+ "Use this description to answer the user's question about the image. "
184
+ "Be detailed, helpful, and use emojis to make your response engaging. "
185
+ "Format your answer nicely with bullet points if needed."
186
+ )},
187
+ {"role": "user", "content": (
188
+ f"Image description: {caption}\n\n"
189
+ f"User's question: {question}\n\n"
190
+ "Please provide a detailed and helpful analysis."
191
+ )},
192
+ ]
193
+
194
+ response = ""
195
+ for token in chatbot.engine.chat_generate(analysis_prompt, stream=True):
196
+ response += token
197
+
198
+ return (
199
+ "πŸ–ΌοΈ **Image Analysis by Naveed AI**\n\n"
200
+ f"πŸ“Έ **Vision Caption:** {caption}\n\n"
201
+ "---\n\n"
202
+ f"πŸ€– **Detailed Analysis:**\n\n{response}"
203
+ )
204
+
205
+ except Exception as e:
206
+ return f"❌ Error analyzing image: {str(e)}\n\nπŸ’‘ Make sure the image is a valid PNG/JPG file."
207
+
208
+
209
+ # -- Code Snippets & Embed Codes ----------------------------------------------
210
  SPACE_URL = "https://bilalnaveed-naveedai.hf.space"
211
 
212
  PYTHON_CODE = '''# pip install gradio_client
213
  from gradio_client import Client
214
 
215
+ # Connect to Naveed AI (100%% FREE forever!)
216
  client = Client("bilalnaveed/Naveedai")
217
+
218
+ # Simple chat
219
  result = client.predict(
220
  message="Hello, who are you?",
221
  api_name="/chat"
 
223
  print(result)
224
  '''
225
 
226
+ JAVASCRIPT_CODE = '''// Naveed AI β€” FREE forever, no API key needed!
227
+ async function askNaveedAI(message) {
228
+ const resp = await fetch("SPACE_URL/api/predict", {
229
+ method: "POST",
230
+ headers: { "Content-Type": "application/json" },
231
+ body: JSON.stringify({ data: [message] })
232
+ });
233
+ const data = await resp.json();
234
+ return data.data[0];
235
+ }
236
+
237
+ // Usage
238
+ askNaveedAI("What is machine learning?").then(console.log);
239
+ '''.replace("SPACE_URL", SPACE_URL)
240
+
241
+ CURL_CODE = f'''# Call Naveed AI from terminal (FREE forever!)
242
+ curl -X POST {SPACE_URL}/api/predict \\
243
  -H "Content-Type: application/json" \\
244
+ -d '{{"data": ["Hello, who are you?"]}}'
245
  '''
246
 
247
+ EMBED_IFRAME = f'''<!-- Naveed AI Chatbot β€” FREE FOREVER! Paste into any HTML page -->
248
  <iframe
249
+ src="{SPACE_URL}"
250
  frameborder="0"
251
  width="100%"
252
+ height="700"
253
+ style="border-radius:16px; border:2px solid #7c3aed; box-shadow:0 8px 32px rgba(124,58,237,0.2);"
254
+ allow="microphone"
255
  ></iframe>
256
  '''
257
 
258
+ EMBED_WIDGET = f'''<!-- Naveed AI Gradio Widget β€” auto-loads! -->
259
+ <script type="module"
260
+ src="https://gradio.s3-us-west-2.amazonaws.com/4.44.1/gradio.js">
261
+ </script>
262
+ <gradio-app src="{SPACE_URL}" eager></gradio-app>
 
263
  '''
264
 
265
+ EMBED_FLOATING = f'''<!-- Naveed AI Floating Chat Button β€” ADVANCED! -->
266
+ <style>
267
+ #naveed-ai-btn {{
268
+ position:fixed; bottom:24px; right:24px; z-index:9999;
269
+ width:64px; height:64px; border-radius:50%;
270
+ background:linear-gradient(135deg,#7c3aed,#3b82f6);
271
+ border:none; cursor:pointer;
272
+ box-shadow:0 4px 20px rgba(124,58,237,0.4);
273
+ display:flex; align-items:center; justify-content:center;
274
+ font-size:28px; transition:transform .2s;
275
+ }}
276
+ #naveed-ai-btn:hover {{ transform:scale(1.1); }}
277
+ #naveed-ai-popup {{
278
+ display:none; position:fixed; bottom:100px; right:24px; z-index:9999;
279
+ width:420px; height:600px; border-radius:16px; overflow:hidden;
280
+ box-shadow:0 8px 40px rgba(0,0,0,0.3); border:2px solid #7c3aed;
281
+ }}
282
+ #naveed-ai-popup.open {{ display:block; }}
283
+ #naveed-ai-popup iframe {{ width:100%; height:100%; border:none; }}
284
+ </style>
285
+ <button id="naveed-ai-btn"
286
+ onclick="document.getElementById('naveed-ai-popup').classList.toggle('open')">πŸ€–</button>
287
+ <div id="naveed-ai-popup">
288
+ <iframe src="{SPACE_URL}"></iframe>
289
+ </div>
290
+ '''
291
+
292
+
293
+ # -- Custom CSS ---------------------------------------------------------------
294
+ CUSTOM_CSS = """
295
+ .gradio-container {
296
+ max-width: 1100px !important;
297
+ margin: auto !important;
298
+ font-family: 'Inter', system-ui, -apple-system, sans-serif !important;
299
+ }
300
+ footer { display: none !important; }
301
+
302
+ .header-banner {
303
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
304
+ border-radius: 16px; padding: 24px; margin-bottom: 16px;
305
+ border: 1px solid #7c3aed33; text-align: center;
306
+ }
307
+ .header-banner h1 {
308
+ background: linear-gradient(135deg, #7c3aed, #3b82f6, #06b6d4);
309
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent;
310
+ font-size: 2.4em; margin: 0; font-weight: 800;
311
+ }
312
+ .header-banner p { color: #94a3b8; margin: 4px 0 0; font-size: 1.05em; }
313
+
314
+ .feature-card {
315
+ background: #1e293b; border: 1px solid #334155;
316
+ border-radius: 12px; padding: 16px; margin: 8px 0;
317
+ }
318
+ .status-online {
319
+ display: inline-block; width: 8px; height: 8px;
320
+ border-radius: 50%; background: #22c55e; margin-right: 6px;
321
+ animation: pulse 2s infinite;
322
+ }
323
+ @keyframes pulse { 0%,100%{opacity:1;} 50%{opacity:0.5;} }
324
+ """
325
+
326
 
327
  # -- Build Gradio UI ----------------------------------------------------------
328
  with gr.Blocks(
329
+ title="Naveed AI β€” Advanced AI Assistant",
330
+ theme=gr.themes.Soft(
331
+ primary_hue="violet",
332
+ secondary_hue="blue",
333
+ neutral_hue="slate",
334
  font=gr.themes.GoogleFont("Inter"),
335
  ),
336
+ css=CUSTOM_CSS,
337
+ analytics_enabled=False,
 
 
338
  ) as demo:
339
 
340
  # Header
341
+ gr.HTML("""
342
+ <div class="header-banner">
343
+ <h1>🧠 Naveed AI</h1>
344
+ <p>
345
+ <span class="status-online"></span>
346
+ Advanced AI Assistant by <strong>Naveed Khan</strong> β€”
347
+ Speech-to-Text β€’ Image Reading β€’ Thinking Mode β€’ 100% Free Forever
348
+ </p>
349
+ </div>
350
+ """)
351
 
352
  with gr.Tabs():
353
 
354
+ # ── TAB 1: CHAT ──
355
+ with gr.TabItem("πŸ’¬ Chat"):
356
+ with gr.Row():
357
+ with gr.Column(scale=1):
358
+ thinking_toggle = gr.Checkbox(
359
+ label="🧠 Thinking Mode",
360
+ value=False,
361
+ info="Enable deep reasoning β€” AI shows its thought process",
362
+ )
363
+ gr.Markdown("""
364
+ <div class="feature-card">
365
+ <strong>πŸ’‘ Tips:</strong><br>
366
+ β€’ Ask complex questions for best results<br>
367
+ β€’ Enable Thinking Mode for math & logic<br>
368
+ β€’ Responses include emojis & formatting<br>
369
+ β€’ I remember our conversation context
370
+ </div>
371
+ """)
372
+
373
  gr.ChatInterface(
374
  fn=chat_fn,
375
+ type="messages",
376
+ additional_inputs=[thinking_toggle],
377
  chatbot=gr.Chatbot(
378
+ height=520,
379
+ placeholder=(
380
+ "<div style='text-align:center;color:#888;padding:40px;'>"
381
+ "<h2>🧠 Naveed AI</h2>"
382
+ "<p style='font-size:1.1em;'>How can I help you today?</p>"
383
+ "<p style='font-size:0.9em;color:#666;'>"
384
+ "Ask anything β€’ Code β€’ Math β€’ Analysis β€’ Creative Writing"
385
+ "</p></div>"
386
+ ),
387
  show_copy_button=True,
388
+ render_markdown=True,
389
  ),
390
  textbox=gr.Textbox(
391
+ placeholder="Message Naveed AI... (try: 'Who created you?')",
392
  container=False,
393
  scale=7,
394
  ),
395
  title="",
396
+ retry_btn="πŸ”„ Retry",
397
+ undo_btn="↩️ Undo",
398
+ clear_btn="πŸ—‘οΈ Clear",
399
  examples=[
400
+ ["Who are you and who created you?"],
401
+ ["Explain machine learning like I'm 10 years old πŸ§’"],
402
+ ["Write a Python function to check if a number is prime"],
403
+ ["What is quantum computing? πŸ”¬"],
404
+ ["Help me write a professional email"],
405
+ ["Solve: If 3x + 7 = 22, what is x?"],
406
  ],
407
  )
408
 
409
+ # ── TAB 2: SPEECH TO TEXT ──
410
+ with gr.TabItem("🎀 Speech to Text"):
411
+ gr.Markdown("""
412
+ ### 🎀 Speech-to-Text β€” Powered by Whisper
413
+ Record your voice or upload an audio file and Naveed AI will transcribe it!
414
+
415
+ **Supported:** WAV, MP3, M4A, FLAC, OGG, WebM &nbsp;|&nbsp; **Languages:** 90+
416
+ """)
417
+ with gr.Row():
418
+ with gr.Column():
419
+ audio_input = gr.Audio(
420
+ sources=["microphone", "upload"],
421
+ type="filepath",
422
+ label="πŸŽ™οΈ Record or Upload Audio",
423
+ )
424
+ stt_btn = gr.Button("πŸ“ Transcribe", variant="primary", size="lg")
425
+ with gr.Column():
426
+ stt_output = gr.Markdown("*Your transcription will appear here...*")
427
+
428
+ stt_btn.click(fn=speech_to_text, inputs=[audio_input], outputs=[stt_output])
429
+
430
+ gr.Markdown("""
431
+ ---
432
+ πŸ’‘ **Tip:** Copy the transcribed text and paste it in the **Chat** tab for an AI response!
433
+ """)
434
+
435
+ # ── TAB 3: IMAGE READING ──
436
+ with gr.TabItem("πŸ–ΌοΈ Image Reading"):
437
+ gr.Markdown("""
438
+ ### πŸ–ΌοΈ Image Analysis β€” AI Vision
439
+ Upload any image and Naveed AI will analyze, describe, and answer questions about it!
440
+ """)
441
+ with gr.Row():
442
+ with gr.Column():
443
+ image_input = gr.Image(type="pil", label="πŸ“Έ Upload Image", height=350)
444
+ image_question = gr.Textbox(
445
+ placeholder="Ask about the image... (optional)",
446
+ label="❓ Your Question",
447
+ lines=2,
448
+ )
449
+ vision_btn = gr.Button("πŸ” Analyze Image", variant="primary", size="lg")
450
+ with gr.Column():
451
+ vision_output = gr.Markdown(
452
+ "*Upload an image and click Analyze!*"
453
+ )
454
+
455
+ vision_btn.click(
456
+ fn=read_image,
457
+ inputs=[image_input, image_question],
458
+ outputs=[vision_output],
459
  )
460
 
461
+ gr.Markdown("""
462
+ ---
463
+ 🎯 **What can I analyze?** Photos β€’ Screenshots β€’ Charts β€’ Documents β€’ Art β€’ Nature β€’ Objects
464
+ """)
465
+
466
+ # ── TAB 4: API & EMBED ──
467
+ with gr.TabItem("πŸ”Œ API & Embed"):
468
+ gr.Markdown("""
469
+ ### πŸ”Œ Use Naveed AI β€” 100% FREE Forever!
470
+ Integrate into your projects. **No API key. No limits. No cost. Ever.**
471
+ """)
472
+ with gr.Tabs():
473
+ with gr.TabItem("🐍 Python"):
474
+ gr.Code(value=PYTHON_CODE, language="python")
475
+ with gr.TabItem("🌐 JavaScript"):
476
+ gr.Code(value=JAVASCRIPT_CODE, language="javascript")
477
+ with gr.TabItem("πŸ“Ÿ cURL"):
478
+ gr.Code(value=CURL_CODE, language="shell")
479
+
480
+ gr.Markdown("---\n### πŸ“¦ Embed on Your Website")
481
+ with gr.Tabs():
482
+ with gr.TabItem("πŸ“Ί iframe"):
483
+ gr.Code(value=EMBED_IFRAME, language="html")
484
+ with gr.TabItem("⚑ Widget"):
485
+ gr.Code(value=EMBED_WIDGET, language="html")
486
+ with gr.TabItem("πŸ’¬ Floating Button"):
487
+ gr.Code(value=EMBED_FLOATING, language="html")
488
+
489
+ gr.Markdown(f"""
490
+ ---
491
+ 🌐 **Live:** [{SPACE_URL}]({SPACE_URL})
492
+
493
+ βœ… Unlimited messages β€’ Speech-to-Text β€’ Image Analysis β€’ Thinking Mode β€’
494
+ Full API β€’ Embeddable β€’ No API key β€’ No sign-up
495
+ """)
496
+
497
+ # ── TAB 5: ABOUT ──
498
+ with gr.TabItem("ℹ️ About"):
499
+ gr.Markdown(f"""
500
+ ### 🧠 About Naveed AI
501
+
502
+ | Detail | Info |
503
+ |--------|------|
504
+ | **🏷️ Name** | Naveed AI |
505
+ | **πŸ‘¨β€πŸ’» Creator** | **Naveed Khan** |
506
+ | **🎯 Purpose** | Advanced AI Assistant |
507
+ | **πŸ€– Model** | Qwen2.5-1.5B-Instruct (Q4 GGUF) |
508
+ | **βš™οΈ Engine** | llama-cpp-python |
509
+ | **πŸ’Ύ Params** | 1.5 Billion |
510
+ | **πŸ’° Cost** | FREE Forever |
511
+
512
+ ---
513
+
514
+ ### ✨ Features
515
+
516
+ | Feature | Status |
517
+ |---------|--------|
518
+ | πŸ’¬ AI Chat | βœ… Live |
519
+ | 🧠 Thinking Mode | βœ… Live |
520
+ | 🎀 Speech-to-Text | βœ… Live |
521
+ | πŸ–ΌοΈ Image Reading | βœ… Live |
522
+ | 😊 Emoji Responses | βœ… Live |
523
+ | πŸ”Œ Free API | βœ… Live |
524
+ | πŸ“¦ Embed Widget | βœ… Live |
525
+ | πŸ’¬ Floating Button | βœ… Live |
526
+ | 🌍 90+ Languages | βœ… Live |
527
+
528
+ ---
529
+
530
+ ### πŸ‘¨β€πŸ’» About the Creator
531
+
532
+ **Naveed Khan** is an AI developer passionate about making AI accessible to everyone.
533
+ Naveed AI is completely free, open, and embeddable β€” no sign-up, no API keys, no limits.
534
+
535
+ > *"AI should be free and accessible to everyone."* β€” Naveed Khan
536
+
537
+ ---
538
+ <p style="text-align:center;color:#666;font-size:0.9em;">
539
+ Built with ❀️ by Naveed Khan | 🌐 <a href="{SPACE_URL}">{SPACE_URL}</a>
540
+ </p>
541
+ """)
542
+
543
 
544
  # -- Launch --------------------------------------------------------------------
545
  if __name__ == "__main__":
546
+ demo.launch(
547
+ server_name="0.0.0.0",
548
+ server_port=7860,
549
+ share=False,
550
+ show_error=True,
551
+ )