musk12 commited on
Commit
401229c
·
verified ·
1 Parent(s): d501ddb

Upload 14 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ fastvlm_qwen2_q4km.gguf filter=lfs diff=lfs merge=lfs -text
37
+ libggml-base.so filter=lfs diff=lfs merge=lfs -text
38
+ libggml-base.so.0 filter=lfs diff=lfs merge=lfs -text
39
+ libggml-cpu.so filter=lfs diff=lfs merge=lfs -text
40
+ libggml-cpu.so.0 filter=lfs diff=lfs merge=lfs -text
41
+ libllama.so.0 filter=lfs diff=lfs merge=lfs -text
GOT.jpg ADDED
fastvlm_qwen2_q4km.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e3201e6785f3da21bd842946455f19b364c06a92d3440f9a2e63d02e26fd517
3
+ size 491395456
fastvlm_server ADDED
Binary file (26.2 kB). View file
 
gradio_3i1_new.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from PIL import Image
4
+ from io import BytesIO
5
+ import base64
6
+ import os
7
+ import time
8
+ import io
9
+ import threading
10
+ from faster_whisper import WhisperModel
11
+ import edge_tts
12
+ import tempfile
13
+ import asyncio
14
+ import httpx
15
+
16
+ API_URL = "http://127.0.0.1:8000"
17
+
18
+
19
+ async def run_inference(image: Image.Image, prompt: str):
20
+
21
+ print("IMAGE TYPE:", type(image))
22
+ print("PROMPT TYPE:", type(prompt))
23
+ print("PROMPT:", repr(prompt))
24
+
25
+ if isinstance(image, str):
26
+ image = Image.open(image).convert("RGB")
27
+
28
+ if image is None:
29
+ yield "Please upload an image."
30
+ return
31
+
32
+ if not prompt.strip():
33
+ prompt = "Describe this image in detail."
34
+
35
+ # Convert PIL image to bytes
36
+ buf = BytesIO()
37
+ image.save(buf, format="JPEG", quality=95)
38
+ buf.seek(0)
39
+
40
+ try:
41
+ async with httpx.AsyncClient(timeout=300) as client:
42
+ # 1. Stream the request so we don't block on the full payload
43
+ async with client.stream(
44
+ "POST",
45
+ f"{API_URL}/predict",
46
+ files={"image": ("image.jpg", buf, "image/jpeg")},
47
+ data={"prompt": prompt},
48
+ ) as response:
49
+
50
+ print("STATUS:", response.status_code)
51
+ print("HEADERS:", response.headers)
52
+
53
+ if response.status_code == 200:
54
+ partial_text = ""
55
+ # 2. Iterate over small token chunks as they are flushed by the FastAPI server
56
+ async for chunk in response.aiter_text(chunk_size=16):
57
+ # print("CHUNK:", repr(chunk))
58
+ if chunk:
59
+ partial_text += chunk
60
+ yield partial_text # CRITICAL: yield triggers token streaming in UI
61
+ else:
62
+ error_body = await response.aread()
63
+ yield f"API error {response.status_code}: {error_body.decode(errors='ignore')}"
64
+
65
+ except httpx.ConnectError:
66
+ yield "Cannot connect to API. Make sure api.py is running on port 8000."
67
+ except Exception as e:
68
+ yield f"Error: {str(e)}"
69
+
70
+ def process_static_image():
71
+
72
+ #Example prompts
73
+ EXAMPLE_PROMPTS = [
74
+ "Describe this image in detail.",
75
+ "What is happening in this image?",
76
+ "What objects can you see in this image?",
77
+ "Describe the mood and atmosphere of this image.",
78
+ "What is the main subject of this image?",
79
+ "Is there any text visible in this image?",
80
+ ]
81
+
82
+ gr.Markdown("**Upload an image and ask a question about it.**", elem_classes="header")
83
+
84
+ with gr.Row():
85
+ # Left column — inputs
86
+ with gr.Column(scale=1):
87
+ image_input = gr.Image(
88
+ type="pil",
89
+ label="Upload Image",
90
+ height=400,
91
+ )
92
+ prompt_input = gr.Textbox(
93
+ label="Prompt",
94
+ placeholder="Describe this image in detail.",
95
+ value="Describe this image in detail.",
96
+ lines=2,
97
+ )
98
+
99
+ with gr.Row():
100
+ submit_btn = gr.Button(
101
+ "🚀 Run Inference",
102
+ variant="primary",
103
+ scale=2
104
+ )
105
+ clear_btn = gr.Button(
106
+ "🗑 Clear",
107
+ variant="secondary",
108
+ scale=1
109
+ )
110
+
111
+ # Example prompts setup
112
+ gr.Markdown("**Quick prompts:**")
113
+ with gr.Row():
114
+ for p in EXAMPLE_PROMPTS[:3]:
115
+ gr.Button(p, size="sm").click(
116
+ fn=lambda x=p: x,
117
+ outputs=prompt_input
118
+ )
119
+ with gr.Row():
120
+ for p in EXAMPLE_PROMPTS[3:]:
121
+ gr.Button(p, size="sm").click(
122
+ fn=lambda x=p: x,
123
+ outputs=prompt_input
124
+ )
125
+
126
+ # Right column — output
127
+ with gr.Column(scale=1):
128
+ output_text = gr.Textbox(
129
+ label="Model Response",
130
+ lines=20,
131
+ max_lines=30,
132
+ )
133
+ gr.Markdown("""
134
+ <div class="model-info">
135
+ Vision encoder: MobileCLIP-L (FastViT, 125M params) → ONNX<br>
136
+ Language model: Qwen2-0.5B (Q4_K_M, 463MB) → GGUF<br>
137
+ Image tokens: 256 × 896-dim embeddings
138
+ </div>
139
+ """)
140
+
141
+ # Examples section
142
+ gr.Markdown("### 📸 Try with example image")
143
+ if os.path.exists("GOT.jpg"):
144
+ gr.Examples(
145
+ examples=[
146
+ ["GOT.jpg", "Describe what you see in this image in detail."],
147
+ ["GOT.jpg", "What is the mood and atmosphere of this scene?"],
148
+ ["GOT.jpg", "Who appears to be the main character and what are they doing?"],
149
+ ],
150
+ inputs=[image_input, prompt_input]
151
+ )
152
+
153
+ # Event handlers
154
+ submit_btn.click(
155
+ fn=run_inference, inputs=[image_input, prompt_input],
156
+ outputs=output_text, show_progress=True,
157
+ )
158
+
159
+ prompt_input.submit(
160
+ fn=run_inference, inputs=[image_input, prompt_input],
161
+ outputs=output_text, show_progress=True,
162
+ )
163
+
164
+ clear_btn.click(
165
+ fn=lambda: (None, "Describe this image in detail.", ""),
166
+ outputs=[image_input, prompt_input, output_text],
167
+ )
168
+
169
+
170
+ # ==========================================
171
+ # 3. TAB 2: LIVE CAMERA SNAPSHOT
172
+ # ==========================================
173
+
174
+ def live_camera_inference():
175
+
176
+ PROMPT_PRESETS = [
177
+ "Describe briefly.",
178
+ "What's in my hand?",
179
+ "What am I doing?",
180
+ "Any text visible?",
181
+ ]
182
+
183
+ def _status_html(state: str, ttft: float = 0.0, total: float = 0.0) -> str:
184
+ # kbd = "background:#2d2d44;padding:1px 6px;border-radius:3px;color:#cdd6f4;font-size:11px;"
185
+ base = "font:12px/1.5 'JetBrains Mono',monospace;padding:7px 14px;border-radius:4px;text-align:center;letter-spacing:.04em;"
186
+ if state == "idle":
187
+ return (f'<div class="cam-status-bar idle" style="{base}background:#1a1a2e;color:#6c7086;">')
188
+ if state == "processing":
189
+ return (f'<div class="cam-status-bar busy" style="{base}background:#1a1a2e;color:#f9e2af;">'
190
+ f'⏳ PROCESSING — please wait…</div>')
191
+ if state == "done":
192
+ return (f'<div class="cam-status-bar idle" style="{base}background:#1a1a2e;color:#a6e3a1;">'
193
+ f'✔ &nbsp;TTFT <strong>{ttft:.0f} ms</strong> &nbsp;·&nbsp; total <strong>{total:.0f} ms</strong>')
194
+ return ""
195
+
196
+ gr.Markdown("## 🎥 Live Camera Analytics", elem_classes="header")
197
+
198
+ with gr.Row():
199
+ with gr.Column(scale=1, min_width=400):
200
+ # Clean snapshot webcam — no streaming, no record button loop
201
+ webcam = gr.Image(
202
+ sources=["webcam"],
203
+ streaming=False,
204
+ type="pil",
205
+ label="Click the 📷 icon to capture & analyse",
206
+ height=360,
207
+ )
208
+ status_bar = gr.HTML(value=_status_html("idle"))
209
+
210
+ with gr.Column(scale=1):
211
+ response_box = gr.Textbox(
212
+ label="📝 Model Output",
213
+ lines=7,
214
+ max_lines=12,
215
+ interactive=False,
216
+ placeholder="Click the camera icon in the feed to capture and analyse…",
217
+ )
218
+ prompt_selector = gr.Radio(
219
+ choices=PROMPT_PRESETS,
220
+ value=PROMPT_PRESETS[0],
221
+ label="🎯 Select Prompt",
222
+ )
223
+
224
+ is_busy = gr.State(False)
225
+
226
+ async def on_capture(frame, busy, selected_prompt):
227
+ if busy or frame is None:
228
+ yield gr.skip(), gr.skip(), gr.skip()
229
+ return
230
+
231
+ yield _status_html("processing"), True, "⏳ Analysing frame…"
232
+
233
+ t_start = time.time()
234
+ ttft_ms = 0.0
235
+ final_text = ""
236
+
237
+ try:
238
+ async for partial in run_inference(frame, selected_prompt):
239
+ if partial:
240
+ if not final_text:
241
+ ttft_ms = (time.time() - t_start) * 1000
242
+ final_text = partial
243
+ total_ms = (time.time() - t_start) * 1000
244
+ caption = final_text.strip() or "Model returned an empty response."
245
+ except Exception as exc:
246
+ total_ms = (time.time() - t_start) * 1000
247
+ caption = f"⚠ Error: {exc}"
248
+
249
+ yield _status_html("done", ttft=ttft_ms, total=total_ms), False, caption
250
+
251
+ webcam.change(
252
+ fn=on_capture,
253
+ inputs=[webcam, is_busy, prompt_selector],
254
+ outputs=[status_bar, is_busy, response_box],
255
+ queue=True,
256
+ )
257
+
258
+
259
+
260
+ # --- Improved Inference Processing ---
261
+ def run_inference_voice(image: Image.Image, prompt: str):
262
+ if isinstance(image, str):
263
+ image = Image.open(image).convert("RGB")
264
+
265
+ if image is None:
266
+ yield "Please upload an image."
267
+ return
268
+
269
+ if not prompt.strip():
270
+ prompt = "Describe this image in detail."
271
+
272
+ buf = BytesIO()
273
+ image.save(buf, format="JPEG", quality=85) # Reduced quality slightly to 85% to save bandwidth & memory
274
+ buf.seek(0)
275
+
276
+ try:
277
+ response = requests.post(
278
+ f"{API_URL}/predict",
279
+ files={"image": ("image.jpg", buf, "image/jpeg")},
280
+ data={"prompt": prompt},
281
+ stream=True,
282
+ timeout=300
283
+ )
284
+
285
+ if response.status_code == 200:
286
+ partial_text = ""
287
+ # FIX: Increased chunk_size to 128 bytes to significantly reduce yield frequency
288
+ for chunk in response.iter_content(chunk_size=128, decode_unicode=True):
289
+ if chunk:
290
+ partial_text += chunk
291
+ yield partial_text
292
+ else:
293
+ yield f"API error {response.status_code}: {response.text}"
294
+
295
+ except requests.exceptions.ConnectionError:
296
+ yield "Cannot connect to API. Make sure api.py is running on port 8000."
297
+ except Exception as e:
298
+ yield f"Error: {str(e)}"
299
+
300
+
301
+
302
+ whisper_model = WhisperModel("tiny", device="cpu", compute_type="int8", cpu_threads=2)
303
+
304
+ def transcribe_audio(audio_path):
305
+
306
+ if audio_path is None:
307
+ return None
308
+
309
+ segments, _ = whisper_model.transcribe(audio_path)
310
+
311
+ return " ".join(
312
+ segment.text
313
+ for segment in segments
314
+ )
315
+
316
+ def handle_audio_transcription(audio_path, fallback_prompt):
317
+
318
+ voice_prompt = transcribe_audio(audio_path)
319
+
320
+ if voice_prompt and voice_prompt.strip():
321
+ return voice_prompt.strip()
322
+
323
+ return fallback_prompt
324
+
325
+
326
+ async def text_to_speech_edge(text):
327
+ try:
328
+ if not text or not text.strip():
329
+ return None
330
+
331
+ clean_text = text.replace("Streaming error:", "").strip()
332
+
333
+ # Premium Natural Voice: 'en-US-ChristopherNeural' (Male) ya 'en-US-EmmaNeural' (Female)
334
+ voice = "en-US-ChristopherNeural"
335
+ output_filename = "response_voice.mp3"
336
+
337
+ # Edge TTS Communicate object pipeline
338
+ communicate = edge_tts.Communicate(clean_text, voice)
339
+ await communicate.save(output_filename)
340
+
341
+ return output_filename
342
+ except Exception as e:
343
+ print(f"Edge TTS Conversion Error: {str(e)}")
344
+ return None
345
+
346
+
347
+ def live_camera_voice_infer():
348
+
349
+
350
+ gr.Markdown("### 🎙️ Voice Prompt & Image Analysis", elem_classes="header")
351
+
352
+ with gr.Row():
353
+ with gr.Column(scale=1, min_width=300):
354
+ # Clean snapshot webcam — no streaming, no record button loop
355
+ webcam = gr.Image(
356
+ sources=["webcam"],
357
+ streaming=False,
358
+ type="pil",
359
+ label="Click the 📷 icon to capture & analyse",
360
+ height=300,
361
+ )
362
+
363
+ input_audio = gr.Audio(
364
+ sources=["microphone", "upload"],
365
+ type="filepath",
366
+ label="Record or Upload Audio Prompt"
367
+ )
368
+
369
+ submit_btn = gr.Button("Submit", variant="primary")
370
+
371
+ with gr.Column(scale=1):
372
+
373
+ with gr.Column():
374
+ # Outputs
375
+ output_text = gr.Textbox(label="Model Response", interactive=False)
376
+ output_audio = gr.Audio(label="Response Audio (TTS)", interactive=False, autoplay=True)
377
+
378
+
379
+ async def process_voice_and_predict(image, audio_path):
380
+ final_prompt = handle_audio_transcription(audio_path, fallback_prompt="Describe this image in detail.")
381
+
382
+ last_text = ""
383
+ async for text_out in run_inference(image, final_prompt):
384
+ if text_out:
385
+ last_text = text_out
386
+ yield last_text, gr.skip()
387
+
388
+ if last_text.strip():
389
+ print(f"Generating Premium Edge TTS Audio...")
390
+ audio_file = await text_to_speech_edge(last_text)
391
+ yield last_text, audio_file
392
+
393
+ # Click event trigger
394
+ submit_btn.click(
395
+ fn=process_voice_and_predict,
396
+ inputs=[webcam, input_audio],
397
+ outputs=[output_text, output_audio],
398
+ queue=True
399
+ )
400
+
401
+
402
+ def live_camera_continous_inference():
403
+ gr.Markdown("### 🎥 Live Camera Frame Analytics", elem_classes="header")
404
+
405
+ PROMPT_PRESETS = [
406
+ "Describe this image in one brief sentence.",
407
+ "What is in my hand?",
408
+ "Identify the main objects visible here.",
409
+ "What is the person doing in this frame?",
410
+ "Is there any text or book visible?"
411
+ ]
412
+
413
+ with gr.Row():
414
+ # LEFT COLUMN: Live Camera Feed with continuous streaming & System Kill Button
415
+ with gr.Column(scale=1, min_width=400):
416
+ webcam = gr.Image(sources=["webcam"], streaming=True, type="pil", label="Live Camera Feed", height=380)
417
+ stream_state = gr.State(False)
418
+
419
+ with gr.Row():
420
+ toggle_btn = gr.Button("▶ Start Live Analytics", variant="primary", scale=2)
421
+ kill_cam_btn = gr.Button("🛑 Kill Camera UI", variant="stop", scale=1)
422
+
423
+ # RIGHT COLUMN: Preset Selector, JSON Metric Monitor & Text Panel
424
+ with gr.Column(scale=1):
425
+ prompt_selector = gr.Radio(
426
+ choices=PROMPT_PRESETS,
427
+ value=PROMPT_PRESETS[0],
428
+ label="🎯 Choose Active VLM Directive / Prompt"
429
+ )
430
+
431
+ response_box = gr.Textbox(
432
+ label="VLM Caption Output (Updates every 4 seconds)",
433
+ lines=5,
434
+ max_lines=7,
435
+ interactive=False,
436
+ placeholder="System Paused. Click 'Start Live Analytics' to begin..."
437
+ )
438
+
439
+ ttft_display = gr.JSON(
440
+ label="⏱️ Hardware Latency Monitor",
441
+ value={"TTFT (Time to First Token)": "0.00 ms", "Total Pipeline Execution": "0.00 ms"}
442
+ )
443
+
444
+
445
+ # State variables time tracking ke liye
446
+ last_run = gr.State(0.0)
447
+
448
+ # Core Snapshot Execution Function
449
+ async def on_frame(frame, last_run_time, is_streaming, selected_prompt):
450
+ now = time.time()
451
+
452
+ if not is_streaming:
453
+ return gr.skip(), last_run_time, gr.skip()
454
+
455
+ if frame is None or (now - last_run_time) < 4.0:
456
+ return gr.skip(), last_run_time, gr.skip()
457
+
458
+ print(f"--- [!] 4 SECONDS PASSED: FETCHING FOR PROMPT: '{selected_prompt}' ---")
459
+
460
+ request_start_time = time.time()
461
+ ttft_recorded = 0.0
462
+ final_caption = ""
463
+
464
+ try:
465
+ inference_stream = run_inference(frame, selected_prompt)
466
+
467
+ async for partial in inference_stream:
468
+ if partial:
469
+ if not final_caption:
470
+ ttft_recorded = (time.time() - request_start_time) * 1000
471
+ final_caption = partial
472
+
473
+ # Formulating clean dictionary output for gr.JSON component
474
+ latency_metrics = {
475
+ "TTFT (Time to First Token)": f"{ttft_recorded:.2f} ms" if ttft_recorded > 0 else "N/A",
476
+ "Total Pipeline Execution": f"{(time.time() - request_start_time)*1000:.2f} ms"
477
+ }
478
+
479
+ if final_caption.strip():
480
+ return final_caption, now, latency_metrics
481
+ else:
482
+ return "Model generated an empty response.", now, latency_metrics
483
+
484
+ except Exception as e:
485
+ return f"Streaming error: {str(e)}", now, {"Error Status": f"Pipeline Failure: {str(e)}"}
486
+
487
+ # Analytics Toggle Controller Function
488
+ def toggle_stream(current_state):
489
+ new_state = not current_state
490
+ if new_state:
491
+ return new_state, gr.update(value="⏹ Stop Live Analytics", variant="stop"), "Starting API pipeline..."
492
+ else:
493
+ return new_state, gr.update(value="▶ Start Live Analytics", variant="primary"), "System Paused."
494
+
495
+ # Completely kills and purges the webcam element state container
496
+ def absolute_kill_switch():
497
+ return (
498
+ False,
499
+ gr.update(value="▶ Start Live Analytics", variant="primary"),
500
+ "System Disconnected & Purged.",
501
+ gr.update(value=None),
502
+ {"System Health Monitor": "Offline / Purged / UI Killed"}
503
+ )
504
+
505
+ # Connect UI Interactions
506
+ toggle_btn.click(
507
+ fn=toggle_stream,
508
+ inputs=[stream_state],
509
+ outputs=[stream_state, toggle_btn, response_box]
510
+ )
511
+
512
+ # Connect the explicit hard kill switch button interface
513
+ kill_cam_btn.click(
514
+ fn=absolute_kill_switch,
515
+ inputs=[],
516
+ outputs=[stream_state, toggle_btn, response_box, webcam, ttft_display]
517
+ )
518
+
519
+ # Connect continuous streaming data injection channel pipeline loops
520
+ webcam.stream(
521
+ fn=on_frame,
522
+ inputs=[webcam, last_run, stream_state, prompt_selector],
523
+ outputs=[response_box, last_run, ttft_display],
524
+ show_progress="hidden",
525
+ queue=True,
526
+ concurrency_limit=1,
527
+ concurrency_id="cam_stream"
528
+ )
529
+
530
+
531
+
532
+ #Gradio UI
533
+ def build_ui():
534
+
535
+
536
+ with gr.Blocks(
537
+ title="FastVLM — Inference on CPU",
538
+ theme=gr.themes.Soft(),
539
+ css="""
540
+ .header { text-align: center; margin-bottom: 20px; }
541
+ .model-info { font-size: 0.85em; color: #666; }
542
+ """
543
+ ) as demo:
544
+
545
+ # Header
546
+ gr.Markdown("""
547
+ # FastVLM — Inference on CPU
548
+ **MobileCLIP-L (FastViT) + Qwen2-0.5B** — Fast multimodal(Vision Language Model) inference pipeline**
549
+ """)
550
+
551
+ with gr.Tabs():
552
+
553
+ # TAB 1: Normal Image Upload
554
+ with gr.Tab("Image Upload"):
555
+ process_static_image()
556
+
557
+ # TAB 2: Live Camera Stream
558
+ with gr.Tab("FastVLM Live Camera"):
559
+ live_camera_inference()
560
+
561
+ # TAB 3: Audio Input / Voice Prompt
562
+ with gr.Tab("live_camera_voice_infer"):
563
+ live_camera_voice_infer()
564
+
565
+ with gr.Tab("Continous text generation"):
566
+ live_camera_continous_inference()
567
+
568
+ return demo
569
+
570
+ if __name__ == "__main__":
571
+ demo = build_ui()
572
+ demo.launch(
573
+ server_name="0.0.0.0",
574
+ server_port=7860,
575
+ share=False,
576
+ show_error=True,
577
+ max_threads=40,
578
+ show_api=False,
579
+ )
580
+
libggml-base.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2441fc98584345f2cda7479606b2a9677197aed0a71e0582d6977e530e9107d0
3
+ size 754616
libggml-base.so.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2441fc98584345f2cda7479606b2a9677197aed0a71e0582d6977e530e9107d0
3
+ size 754616
libggml-cpu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e2c8e8368cb88696e1a4ba260ba7f9f52332d70af446b84322beb42f701d446
3
+ size 1308376
libggml-cpu.so.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e2c8e8368cb88696e1a4ba260ba7f9f52332d70af446b84322beb42f701d446
3
+ size 1308376
libggml.so ADDED
Binary file (60.6 kB). View file
 
libggml.so.0 ADDED
Binary file (60.6 kB). View file
 
libllama.so ADDED
File without changes
libllama.so.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:954845f0a99b54d2a0f0f9dcc4175875dc75e1480be88e5d8a02e3bb228f86a9
3
+ size 3648064
stream_api.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import struct
4
+ import tempfile
5
+ import subprocess
6
+ import numpy as np
7
+ from PIL import Image
8
+ from io import BytesIO
9
+ import onnxruntime as ort
10
+ from fastapi import FastAPI, File, UploadFile, Form
11
+ from fastapi.responses import JSONResponse, StreamingResponse
12
+ import uvicorn
13
+ import asyncio
14
+ import time
15
+
16
+
17
+ # Config
18
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
19
+ # ONNX_PATH = os.path.join(BASE_DIR, "vision_encoder_fp32.onnx")
20
+ ONNX_PATH = os.path.join(BASE_DIR, "vision_projector_v1_standalone.onnx")
21
+ GGUF_PATH = os.path.join(BASE_DIR, "fastvlm_qwen2_q4km.gguf")
22
+ SERVER_BIN = os.path.join(BASE_DIR, "fastvlm_server")
23
+
24
+ app = FastAPI(title="Custom FastVLM onnx gguf API",
25
+ description="Vision Language Model inference using MobileCLIP + Qwen2",
26
+ version="1.0.0")
27
+
28
+
29
+ # Load ONNX session once at startup
30
+ ort_session = None
31
+
32
+ @app.on_event("startup")
33
+ async def load_models():
34
+ global ort_session
35
+ print("Loading ONNX vision encoder...")
36
+
37
+ session_options = ort.SessionOptions()
38
+ session_options.enable_mem_pattern = False
39
+ session_options.add_session_config_entry("session.use_ort_model_bytes_for_initializers", "0")
40
+
41
+ ort_session = ort.InferenceSession(ONNX_PATH, sess_options=session_options, providers=["CPUExecutionProvider"])
42
+
43
+ print("Providers:", ort_session.get_providers())
44
+
45
+ print("ONNX session ready ✅")
46
+
47
+ await start_llm_server()
48
+
49
+ @app.on_event("shutdown")
50
+ async def shutdown():
51
+ if llm_process:
52
+ llm_process.stdin.close()
53
+ await llm_process.wait()
54
+ print("[api] LLM server stopped")
55
+
56
+ #Preprocessing
57
+ def expand_2_square(image: Image.Image):
58
+ w, h = image.size
59
+ if w == h:
60
+ return image
61
+
62
+ size = max(w, h)
63
+ result = Image.new("RGB", (size, size), (0,0,0))
64
+
65
+ x_offset = (size - w) // 2
66
+ y_offset = (size - h) // 2
67
+
68
+ result.paste(image, (x_offset, y_offset))
69
+
70
+ return result
71
+
72
+ def preprocess_image(image: Image.Image) -> np.ndarray:
73
+ image = image.convert("RGB")
74
+ image = expand_2_square(image)
75
+
76
+ TARGET_SIZE = 512
77
+
78
+ w, h = image.size
79
+ scale = 1024 / min(w, h)
80
+ # image = image.resize((round(w * scale), round(h * scale)), Image.BICUBIC)
81
+ image = image.resize((round(w * scale), round(h * scale)), Image.Resampling.BILINEAR)
82
+
83
+ w, h = image.size
84
+ left = (w - TARGET_SIZE) // 2
85
+ top = (h - TARGET_SIZE) // 2
86
+ image = image.crop((left, top, left + TARGET_SIZE, top + TARGET_SIZE))
87
+
88
+ arr = np.array(image, dtype=np.float32) / 255.0
89
+ return arr.transpose(2, 0, 1)[np.newaxis] # (1, 3, 1024, 1024)
90
+
91
+
92
+ def encode_image(image : Image.Image):
93
+
94
+ t0 = time.perf_counter()
95
+
96
+ pixel_values = preprocess_image(image)
97
+
98
+ t1 = time.perf_counter()
99
+
100
+ embeddings = ort_session.run(["image_embeddings"], {"pixel_values": pixel_values})[0]
101
+
102
+ t2 = time.perf_counter()
103
+
104
+ print(
105
+ f"[VISION] preprocess: {(t1-t0)*1000:.1f} ms"
106
+ )
107
+
108
+ print(
109
+ f"[VISION] onnx inference: {(t2-t1)*1000:.1f} ms"
110
+ )
111
+
112
+ return embeddings[0] # (256, 896)
113
+
114
+ def save_embeddings(embeddings: np.ndarray) -> str:
115
+ with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f:
116
+ path = f.name
117
+ n_tokens, n_embd = embeddings.shape
118
+
119
+ # Write header: two int32 values
120
+ f.write(struct.pack("ii", int(n_tokens), int(n_embd)))
121
+
122
+ # Write float32 data
123
+ f.write(embeddings.astype(np.float32).tobytes())
124
+ return path
125
+
126
+
127
+ llm_process = None
128
+ llm_lock = asyncio.Lock() # one request at a time (server is single-threaded)
129
+
130
+ async def start_llm_server():
131
+ global llm_process
132
+ env = {
133
+ **os.environ,
134
+ "LD_LIBRARY_PATH": BASE_DIR + ":" + os.environ.get("LD_LIBRARY_PATH", "")
135
+ }
136
+ llm_process = await asyncio.create_subprocess_exec(
137
+ SERVER_BIN, GGUF_PATH,
138
+ stdin=asyncio.subprocess.PIPE,
139
+ stdout=asyncio.subprocess.PIPE,
140
+ stderr=asyncio.subprocess.PIPE,
141
+ env=env,
142
+ cwd=BASE_DIR
143
+ )
144
+ print("[api] Waiting for LLM server to load model...")
145
+ while True:
146
+ line = await llm_process.stderr.readline()
147
+ line = line.decode("utf-8", errors="ignore").strip()
148
+ print(f"[llm] {line}")
149
+ if "READY" in line:
150
+ break
151
+ if llm_process.returncode is not None:
152
+ raise RuntimeError("LLM server died during startup")
153
+ print("[api] LLM server ready ✅")
154
+
155
+ async def run_llm_stream(embed_path: str, prompt: str, request_start: float):
156
+ """
157
+ Send request to persistent LLM server via stdin pipe.
158
+ Stream response tokens from stdout until ---END--- sentinel.
159
+ Model stays loaded between requests — no per-request startup cost.
160
+ """
161
+ async with llm_lock: # serialize: server handles one request at a time
162
+ llm_start = time.perf_counter()
163
+ first_token = True
164
+
165
+ try:
166
+ # Send request: embd_path\nprompt\n
167
+ llm_process.stdin.write(
168
+ (embed_path + "\n").encode()
169
+ )
170
+ llm_process.stdin.write(
171
+ (prompt + "\n").encode()
172
+ )
173
+ await llm_process.stdin.drain()
174
+
175
+ print(
176
+ f"[TIMING] request sent to server: "
177
+ f"{(time.perf_counter()-llm_start)*1000:.1f} ms"
178
+ )
179
+
180
+ # Stream response until ---END--- sentinel
181
+ buffer = ""
182
+ while True:
183
+ chunk = await llm_process.stdout.read(16)
184
+ if not chunk:
185
+ # Server died
186
+ print("[api] LLM server stdout closed unexpectedly")
187
+ break
188
+
189
+ text = chunk.decode("utf-8", errors="ignore")
190
+ buffer += text
191
+
192
+ # Check if sentinel is in buffer
193
+ if "---END---" in buffer:
194
+ # Yield everything before the sentinel
195
+ before, _ = buffer.split("---END---", 1)
196
+ if before:
197
+ if first_token:
198
+ now = time.perf_counter()
199
+ print(
200
+ f"[TIMING] TTFT from request start: "
201
+ f"{(now-request_start)*1000:.1f} ms"
202
+ )
203
+ print(
204
+ f"[TIMING] LLM first token delay: "
205
+ f"{(now-llm_start)*1000:.1f} ms"
206
+ )
207
+ first_token = False
208
+ yield before
209
+ break
210
+
211
+ # Yield buffered text that definitely isn't the sentinel
212
+ # Keep last 12 chars buffered in case sentinel is split
213
+ # across chunks ("---END" + "---\n")
214
+ safe = buffer[:-12]
215
+ if safe:
216
+ if first_token and safe.strip():
217
+ now = time.perf_counter()
218
+ print(
219
+ f"[TIMING] TTFT from request start: "
220
+ f"{(now-request_start)*1000:.1f} ms"
221
+ )
222
+ print(
223
+ f"[TIMING] LLM first token delay: "
224
+ f"{(now-llm_start)*1000:.1f} ms"
225
+ )
226
+ first_token = False
227
+ yield safe
228
+ buffer = buffer[-12:]
229
+
230
+ except Exception as e:
231
+ print(f"[api] Streaming error: {e}")
232
+ yield f"\n[Error: {e}]"
233
+
234
+ finally:
235
+ if os.path.exists(embed_path):
236
+ os.unlink(embed_path)
237
+
238
+ #Routes
239
+
240
+ @app.get("/")
241
+ def root():
242
+ return {
243
+ "name": "FastVLM API",
244
+ "status": "running",
245
+ "model": "MobileCLIP-L + Qwen2-0.5B",
246
+ "endpoints": ["/predict", "/health"]
247
+ }
248
+
249
+ @app.get("/health")
250
+ def health():
251
+ return {
252
+ "status": "ok",
253
+ "onnx_loaded": ort_session is not None,
254
+ "gguf_exists": os.path.exists(GGUF_PATH),
255
+ "binary_exists": os.path.exists(SERVER_BIN),
256
+ }
257
+
258
+ @app.post("/predict")
259
+ async def predict(image: UploadFile = File(...), prompt: str = Form(default="Describe this image in detail.")):
260
+
261
+ try:
262
+ t0 = time.perf_counter()
263
+
264
+ # Load image
265
+ img_bytes = await image.read()
266
+ img = Image.open(BytesIO(img_bytes)).convert("RGB")
267
+
268
+ # img = img.resize((224, 224), Image.Resampling.BILINEAR)
269
+
270
+ t1 = time.perf_counter()
271
+ print(f"[TIMING] image load: {(t1-t0)*1000:.1f} ms")
272
+
273
+ # Encode with ONNX
274
+ embeddings = encode_image(img)
275
+
276
+ print("Actual Input Shape to ONNX:", embeddings.shape)
277
+
278
+ t2 = time.perf_counter()
279
+ print(f"[TIMING] vision encoder: {(t2-t1)*1000:.1f} ms")
280
+
281
+ # Save embeddings to temp file
282
+ embd_path = save_embeddings(embeddings)
283
+
284
+ t3 = time.perf_counter()
285
+ print(f"[TIMING] save embeddings: {(t3-t2)*1000:.1f} ms")
286
+
287
+ headers = {
288
+ "X-Status": "ok",
289
+ "X-Prompt": prompt.encode('utf-8').decode('latin-1'),
290
+ "X-Model": "custom-onnx-fastvlm-0.5b"
291
+ }
292
+
293
+ # try:
294
+ # # Run LLM
295
+ # response = run_llm_stream(embd_path, prompt)
296
+ # finally:
297
+ # os.unlink(embd_path)
298
+
299
+
300
+
301
+ return StreamingResponse(
302
+ run_llm_stream(embd_path, prompt, t0),
303
+ media_type="text/plain",
304
+ headers=headers
305
+ )
306
+
307
+ except Exception as e:
308
+ return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
309
+
310
+ if __name__ == "__main__":
311
+ uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=False)
vision_projector.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f233f82a0eea137d0a45ae601d1a5e2eb8fea1f0d69d0194c06401cc34f8a51c
3
+ size 239431842