-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
650 lines (586 loc) · 25.9 KB
/
Copy pathapp.py
File metadata and controls
650 lines (586 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import os, re, json, base64, shutil, tempfile, subprocess
from typing import List
from flask import Flask, request, render_template, jsonify, Response, stream_with_context, abort
import requests
from dotenv import load_dotenv
load_dotenv()
from tools import TOOL_DEFINITIONS, execute_tool
def _require_env(name: str) -> str:
val = os.getenv(name)
if not val:
raise RuntimeError(f"Missing required environment variable: {name}")
return val
def _int_env(name: str, default: int) -> int:
raw = os.getenv(name)
if raw is None:
return default
try:
return int(raw)
except ValueError:
raise RuntimeError(f"Environment variable {name} must be an integer (got {raw!r}).")
OLLAMA_BASE_URL = _require_env("OLLAMA_BASE_URL")
OLLAMA_MODEL = _require_env("OLLAMA_MODEL")
MAX_UPLOAD_MB = _int_env("MAX_UPLOAD_MB", 10)
MAX_VIDEO_UPLOAD_MB = _int_env("MAX_VIDEO_UPLOAD_MB", 50)
VIDEO_FRAMES = _int_env("VIDEO_FRAMES", 8)
VIDEO_FRAME_WIDTH = _int_env("VIDEO_FRAME_WIDTH", 768)
ANALYSIS_NUM_CTX = _int_env("ANALYSIS_NUM_CTX", 32768)
TOOL_MAX_ITERATIONS = _int_env("TOOL_MAX_ITERATIONS", 5)
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = max(MAX_UPLOAD_MB, MAX_VIDEO_UPLOAD_MB) * 1024 * 1024
ALLOWED_EXTS = {".txt"}
VIDEO_EXTS = {".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v"}
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
def _ollama_chat(messages, stream=False, options=None, model=None, tools=None):
payload = {
"model": model or OLLAMA_MODEL,
"messages": messages,
"stream": stream,
"options": options or {}
}
if tools:
payload["tools"] = tools
return requests.post(f"{OLLAMA_BASE_URL}/api/chat", json=payload, stream=stream, timeout=600)
def _enforce_upload_limit(limit_mb: int):
length = request.content_length
if length is not None and length > limit_mb * 1024 * 1024:
abort(413, description=f"Upload exceeds the {limit_mb} MB limit.")
def _read_txt_from_upload(file_storage):
name = (file_storage.filename or "").lower()
if not any(name.endswith(ext) for ext in ALLOWED_EXTS):
abort(400, description="Only .txt files are allowed.")
data = file_storage.read()
if len(data) > MAX_UPLOAD_MB * 1024 * 1024:
abort(413, description=f"Text file exceeds the {MAX_UPLOAD_MB} MB limit.")
return data.decode("utf-8", errors="replace")
def _read_image_b64(file_storage):
name = (file_storage.filename or "").lower()
ext = os.path.splitext(name)[1]
if ext not in IMAGE_EXTS:
abort(400, description="Unsupported image type. Allowed: " + ", ".join(sorted(IMAGE_EXTS)))
data = file_storage.read()
if not data:
abort(400, description="Empty image file.")
return base64.b64encode(data).decode("ascii")
def _image_messages(b64: str, task: str = "") -> List[dict]:
sys = ("You are a careful image analyst. Describe the image accurately: the setting, "
"key objects, people, any visible text, and notable details.")
user_text = task.strip() if task else "Describe this image."
return [
{"role": "system", "content": sys},
{"role": "user", "content": user_text, "images": [b64]},
]
def _probe_duration(path: str) -> float:
try:
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path],
capture_output=True, text=True, timeout=30
)
return float(out.stdout.strip())
except Exception:
return 0.0
def _extract_video_frames(file_storage, num_frames: int = VIDEO_FRAMES,
width: int = VIDEO_FRAME_WIDTH) -> List[str]:
name = (file_storage.filename or "").lower()
ext = os.path.splitext(name)[1]
if ext not in VIDEO_EXTS:
abort(400, description="Unsupported video type. Allowed: " + ", ".join(sorted(VIDEO_EXTS)))
if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:
abort(500, description="ffmpeg/ffprobe are required for video analysis but were not found on the server.")
tmpdir = tempfile.mkdtemp(prefix="vid_")
frames: List[str] = []
try:
in_path = os.path.join(tmpdir, "input" + ext)
file_storage.save(in_path)
duration = _probe_duration(in_path)
if duration and duration > 0:
timestamps = [duration * (i + 0.5) / num_frames for i in range(num_frames)]
else:
timestamps = [0.0]
for idx, ts in enumerate(timestamps):
out_path = os.path.join(tmpdir, f"frame_{idx:03d}.jpg")
cmd = ["ffmpeg", "-nostdin", "-loglevel", "error", "-ss", f"{ts:.3f}",
"-i", in_path, "-frames:v", "1",
"-vf", f"scale='min({width},iw)':-2", "-q:v", "3", out_path]
try:
subprocess.run(cmd, capture_output=True, timeout=60, check=False)
except Exception:
continue
if os.path.exists(out_path) and os.path.getsize(out_path) > 0:
with open(out_path, "rb") as fh:
frames.append(base64.b64encode(fh.read()).decode("ascii"))
if not frames:
abort(400, description="Could not extract any frames from the video.")
return frames
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def _video_messages(frames: List[str], task: str = "") -> List[dict]:
sys = ("You are a careful video analyst. You are given a sequence of still frames "
"sampled in chronological order from a short video. Reason about what happens "
"across the clip - describe the setting, key objects, people, actions, any visible "
"text, and how things change from frame to frame. Present one coherent account of "
"the video rather than describing each frame in isolation.")
user_text = task.strip() if task else "Describe what is happening in this video."
user_text += (f"\n\n(The {len(frames)} attached images are frames sampled evenly "
"from the video, in chronological order.)")
return [
{"role": "system", "content": sys},
{"role": "user", "content": user_text, "images": frames},
]
def _resolve_frame_count(raw) -> int:
if not raw:
return VIDEO_FRAMES
try:
return max(1, min(32, int(raw)))
except (TypeError, ValueError):
return VIDEO_FRAMES
def _chunk_text(text: str, max_chars: int = 6000) -> List[str]:
chunks = []
start = 0
n = len(text)
while start < n:
end = min(start + max_chars, n)
cut = text.rfind("\n\n", start, end)
if cut == -1 or cut <= start + int(max_chars * 0.5):
cut = end
chunks.append(text[start:cut].strip())
start = cut
return [c for c in chunks if c]
def _summarize_chunk(chunk: str, extra_instruction: str = "", model=None) -> str:
sys = "You are a precise summarizer. Extract the key ideas succinctly."
if extra_instruction:
sys += " " + extra_instruction.strip()
r = _ollama_chat(
[
{"role": "system", "content": sys},
{"role": "user", "content": f"Summarize the following text:\n\n{chunk}"}
],
stream=False,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": 512},
model=model
)
r.raise_for_status()
return r.json().get("message", {}).get("content", "").strip()
def _final_synthesis(summaries: List[str], user_task: str = "Provide a concise overall summary with key themes, insights, and any notable entities/dates.", model=None) -> str:
joined = "\n\n---\n\n".join(summaries)
r = _ollama_chat(
[
{"role": "system", "content": "You are an expert analyst. Synthesize multiple summaries into one clear, structured brief."},
{"role": "user", "content": f"{user_task}\n\nHere are section summaries:\n\n{joined}"}
],
stream=False,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
)
r.raise_for_status()
return r.json().get("message", {}).get("content", "").strip()
def _raise_for_status_streaming(r):
if r.status_code >= 400:
try:
r.content
except Exception:
pass
r.raise_for_status()
def _ollama_error_message(e: requests.RequestException) -> str:
resp = getattr(e, "response", None)
if resp is None:
return f"Upstream Ollama request failed: {e}"
detail = ""
try:
body = resp.json()
if isinstance(body, dict):
detail = str(body.get("error") or "").strip()
except Exception:
try:
detail = (resp.text or "").strip()
except Exception:
detail = ""
if detail:
return f"Ollama returned HTTP {resp.status_code}: {detail[:1000]}"
return f"Ollama returned HTTP {resp.status_code}: {resp.reason or 'error'}"
@app.errorhandler(requests.RequestException)
def handle_upstream_error(e):
return jsonify({"error": _ollama_error_message(e)}), 502
@app.get("/")
def home():
return render_template("index.html", model=OLLAMA_MODEL, num_ctx_max=ANALYSIS_NUM_CTX)
CHAT_SYSTEM_PROMPT = (
"You are a helpful assistant. Write all mathematical notation as LaTeX, "
"using $...$ delimiters for inline math and $$...$$ delimiters for display "
"math. Never copy {\\displaystyle ...} wrappers, MathML, or other raw math "
"markup from web pages or tool results; rewrite any formula you quote as "
"clean delimited LaTeX."
)
def _with_system_prompt(messages):
if any(isinstance(m, dict) and m.get("role") == "system" for m in messages):
return messages
return [{"role": "system", "content": CHAT_SYSTEM_PROMPT}] + list(messages)
@app.post("/api/chat-sync")
def chat_sync():
data = request.get_json(force=True) or {}
messages = _with_system_prompt(data.get("messages") or [])
options = data.get("options") or {}
model = data.get("model") or OLLAMA_MODEL
r = _ollama_chat(messages, stream=False, options=options, model=model)
r.raise_for_status()
j = r.json()
return jsonify({
"role": j.get("message", {}).get("role", "assistant"),
"content": j.get("message", {}).get("content", ""),
"raw": j
})
@app.post("/api/chat-stream")
def chat_stream():
data = request.get_json(force=True) or {}
messages = _with_system_prompt(data.get("messages") or [])
options = data.get("options") or {}
model = data.get("model") or OLLAMA_MODEL
def sse_from_ollama():
try:
with _ollama_chat(messages, stream=True, options=options, model=model) as r:
_raise_for_status_streaming(r)
for line in r.iter_lines():
if not line:
continue
try:
j = json.loads(line.decode("utf-8"))
except Exception:
continue
if "message" in j and "content" in j["message"]:
yield f"data: {json.dumps({'delta': j['message']['content'], 'done': False})}\n\n"
if j.get("done"):
yield "data: {\"done\": true}\n\n"
except requests.RequestException as e:
yield f"data: {json.dumps({'error': _ollama_error_message(e)})}\n\n"
headers = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive"}
return Response(stream_with_context(sse_from_ollama()), headers=headers)
KNOWN_TOOL_NAMES = sorted(t["function"]["name"] for t in TOOL_DEFINITIONS)
_TEXT_TOOL_CALL_RE = re.compile(
r"\s*(?:\[TOOL_CALLS\])?\s*(" + "|".join(map(re.escape, KNOWN_TOOL_NAMES)) + r")\[ARGS\]\s*"
)
_TEXT_CALL_SNIFF_CHARS = 64
def _parse_text_tool_calls(content):
if not content:
return None
calls = []
decoder = json.JSONDecoder()
pos = 0
while True:
m = _TEXT_TOOL_CALL_RE.match(content, pos)
if not m:
break
try:
args, pos = decoder.raw_decode(content, m.end())
except ValueError:
return None
if not isinstance(args, dict):
return None
calls.append({"function": {"name": m.group(1), "arguments": args}})
while pos < len(content) and content[pos] in " \t\r\n,":
pos += 1
if not calls or content[pos:].strip():
return None
return calls
def _tool_loop_events(messages, options, model):
convo = list(messages)
for _ in range(TOOL_MAX_ITERATIONS):
content_parts = []
tool_calls = []
mode = "buffer"
buffered = ""
with _ollama_chat(convo, stream=True, options=options, model=model, tools=TOOL_DEFINITIONS) as r:
_raise_for_status_streaming(r)
for line in r.iter_lines():
if not line:
continue
try:
j = json.loads(line.decode("utf-8"))
except Exception:
continue
msg = j.get("message") or {}
piece = msg.get("content") or ""
if piece:
content_parts.append(piece)
if mode == "buffer":
buffered += piece
if _TEXT_TOOL_CALL_RE.match(buffered):
mode = "swallow"
elif len(buffered) >= _TEXT_CALL_SNIFF_CHARS:
mode = "stream"
yield {"delta": buffered}
elif mode == "stream":
yield {"delta": piece}
for tc in msg.get("tool_calls") or []:
tool_calls.append(tc)
if j.get("done"):
break
content = "".join(content_parts)
if not tool_calls:
parsed = _parse_text_tool_calls(content)
if parsed:
tool_calls = parsed
content = ""
if mode != "stream" and content:
yield {"delta": content}
if not tool_calls:
yield {"done": True}
return
convo.append({"role": "assistant", "content": content, "tool_calls": tool_calls})
for tc in tool_calls:
fn = tc.get("function") or {}
name = fn.get("name", "")
arguments = fn.get("arguments") or {}
yield {"tool_call": {"name": name, "arguments": arguments}}
result = execute_tool(name, arguments)
yield {"tool_result": {"name": name, "content": result}}
convo.append({"role": "tool", "tool_name": name, "content": result})
yield {"done": True, "stopped": "max_iterations"}
def _assemble_tool_trace(events):
trace = []
stopped = None
for ev in events:
if "delta" in ev:
if trace and trace[-1].get("type") == "text":
trace[-1]["text"] += ev["delta"]
else:
trace.append({"type": "text", "text": ev["delta"]})
elif "tool_call" in ev:
trace.append({"type": "tool",
"name": ev["tool_call"]["name"],
"arguments": ev["tool_call"]["arguments"]})
elif "tool_result" in ev:
for item in reversed(trace):
if item.get("type") == "tool" and "result" not in item:
item["result"] = ev["tool_result"]["content"]
break
elif ev.get("done"):
stopped = ev.get("stopped")
content = "\n\n".join(
item["text"].strip() for item in trace
if item.get("type") == "text" and item["text"].strip()
)
return content, trace, stopped
@app.post("/api/chat-tools-sync")
def chat_tools_sync():
data = request.get_json(force=True) or {}
messages = _with_system_prompt(data.get("messages") or [])
options = data.get("options") or {}
model = data.get("model") or OLLAMA_MODEL
content, trace, stopped = _assemble_tool_trace(_tool_loop_events(messages, options, model))
out = {"role": "assistant", "content": content, "trace": trace}
if stopped:
out["stopped"] = stopped
return jsonify(out)
@app.post("/api/chat-tools-stream")
def chat_tools_stream():
data = request.get_json(force=True) or {}
messages = _with_system_prompt(data.get("messages") or [])
options = data.get("options") or {}
model = data.get("model") or OLLAMA_MODEL
def run():
try:
for ev in _tool_loop_events(messages, options, model):
yield f"data: {json.dumps(ev)}\n\n"
except requests.RequestException as e:
yield f"data: {json.dumps({'error': _ollama_error_message(e)})}\n\n"
headers = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive"}
return Response(stream_with_context(run()), headers=headers)
@app.get("/api/models")
def list_models():
r = requests.get(f"{OLLAMA_BASE_URL}/api/tags", timeout=30)
r.raise_for_status()
return jsonify(r.json())
@app.post("/api/analyze-file")
def analyze_file_sync():
_enforce_upload_limit(MAX_UPLOAD_MB)
if "file" not in request.files:
abort(400, description="Missing file.")
f = request.files["file"]
task = request.form.get("task", "").strip()
model = request.form.get("model") or None
text = _read_txt_from_upload(f)
chunks = _chunk_text(text, max_chars=6000)
if len(chunks) == 1:
sys = "You are a precise analyst."
prompt = f"{task or 'Summarize the main points clearly.'}\n\nText:\n{text}"
r = _ollama_chat(
[{"role": "system", "content": sys},
{"role": "user", "content": prompt}],
stream=False,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
)
r.raise_for_status()
out = r.json().get("message", {}).get("content", "").strip()
return jsonify({"result": out, "chunks": 1})
summaries = [_summarize_chunk(c, extra_instruction=task, model=model) for c in chunks]
final = _final_synthesis(summaries, user_task=task or "Provide a concise overall summary with key themes, insights, and notable entities/dates.", model=model)
return jsonify({"result": final, "chunks": len(chunks)})
@app.post("/api/analyze-file-stream")
def analyze_file_stream():
_enforce_upload_limit(MAX_UPLOAD_MB)
if "file" not in request.files:
abort(400, description="Missing file.")
f = request.files["file"]
task = request.form.get("task", "").strip()
model = request.form.get("model") or None
text = _read_txt_from_upload(f)
chunks = _chunk_text(text, max_chars=6000)
def run():
try:
if len(chunks) == 1:
sys = "You are a precise analyst."
prompt = f"{task or 'Summarize the main points clearly.'}\n\nText:\n{chunks[0]}"
with _ollama_chat(
[{"role": "system", "content": sys},
{"role": "user", "content": prompt}],
stream=True,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
) as r:
_raise_for_status_streaming(r)
assembled = []
for line in r.iter_lines():
if not line:
continue
try: j = json.loads(line.decode("utf-8"))
except Exception: continue
if "message" in j and "content" in j["message"]:
delta = j["message"]["content"]
assembled.append(delta)
yield f"data: {json.dumps({'stage':'final','delta':delta})}\n\n"
if j.get("done"):
text_final = "".join(assembled)
yield f"data: {json.dumps({'stage':'final','text':text_final})}\n\n"
yield "data: {\"done\": true}\n\n"
return
yield f"data: {json.dumps({'stage':'final','text':''.join(assembled)})}\n\n"
yield "data: {\"done\": true}\n\n"
return
summaries = []
N = len(chunks)
for i, c in enumerate(chunks, start=1):
s = _summarize_chunk(c, extra_instruction=task, model=model)
summaries.append(s)
yield f"data: {json.dumps({'stage':'chunk','index':i,'of':N,'summary':s})}\n\n"
final = _final_synthesis(summaries, user_task=task or "Provide a concise overall summary with key themes, insights, and notable entities/dates.", model=model)
yield f"data: {json.dumps({'stage':'final','text':final})}\n\n"
yield "data: {\"done\": true}\n\n"
except requests.RequestException as e:
yield f"data: {json.dumps({'error': _ollama_error_message(e)})}\n\n"
headers = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive"}
return Response(stream_with_context(run()), headers=headers)
@app.post("/api/analyze-image")
def analyze_image_sync():
_enforce_upload_limit(MAX_UPLOAD_MB)
if "file" not in request.files:
abort(400, description="Missing file.")
f = request.files["file"]
task = request.form.get("task", "").strip()
model = request.form.get("model") or None
b64 = _read_image_b64(f)
r = _ollama_chat(
_image_messages(b64, task),
stream=False,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
)
r.raise_for_status()
out = r.json().get("message", {}).get("content", "").strip()
return jsonify({"result": out})
@app.post("/api/analyze-image-stream")
def analyze_image_stream():
_enforce_upload_limit(MAX_UPLOAD_MB)
if "file" not in request.files:
abort(400, description="Missing file.")
f = request.files["file"]
task = request.form.get("task", "").strip()
model = request.form.get("model") or None
messages = _image_messages(_read_image_b64(f), task)
def run():
try:
with _ollama_chat(
messages,
stream=True,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
) as r:
_raise_for_status_streaming(r)
for line in r.iter_lines():
if not line:
continue
try:
j = json.loads(line.decode("utf-8"))
except Exception:
continue
if "message" in j and "content" in j["message"]:
yield f"data: {json.dumps({'delta': j['message']['content']})}\n\n"
if j.get("done"):
yield "data: {\"done\": true}\n\n"
return
except requests.RequestException as e:
yield f"data: {json.dumps({'error': _ollama_error_message(e)})}\n\n"
headers = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive"}
return Response(stream_with_context(run()), headers=headers)
@app.post("/api/analyze-video")
def analyze_video_sync():
_enforce_upload_limit(MAX_VIDEO_UPLOAD_MB)
if "file" not in request.files:
abort(400, description="Missing file.")
f = request.files["file"]
task = request.form.get("task", "").strip()
model = request.form.get("model") or None
num_frames = _resolve_frame_count(request.form.get("frames"))
frames = _extract_video_frames(f, num_frames=num_frames)
r = _ollama_chat(
_video_messages(frames, task),
stream=False,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
)
r.raise_for_status()
out = r.json().get("message", {}).get("content", "").strip()
return jsonify({"result": out, "frames": len(frames)})
@app.post("/api/analyze-video-stream")
def analyze_video_stream():
_enforce_upload_limit(MAX_VIDEO_UPLOAD_MB)
if "file" not in request.files:
abort(400, description="Missing file.")
f = request.files["file"]
task = request.form.get("task", "").strip()
model = request.form.get("model") or None
num_frames = _resolve_frame_count(request.form.get("frames"))
frames = _extract_video_frames(f, num_frames=num_frames)
messages = _video_messages(frames, task)
def run():
yield f"data: {json.dumps({'stage':'frames','frames':len(frames)})}\n\n"
try:
with _ollama_chat(
messages,
stream=True,
options={"temperature": 0.2, "num_ctx": ANALYSIS_NUM_CTX, "num_predict": -1},
model=model
) as r:
_raise_for_status_streaming(r)
for line in r.iter_lines():
if not line:
continue
try:
j = json.loads(line.decode("utf-8"))
except Exception:
continue
if "message" in j and "content" in j["message"]:
yield f"data: {json.dumps({'delta': j['message']['content']})}\n\n"
if j.get("done"):
yield "data: {\"done\": true}\n\n"
return
except requests.RequestException as e:
yield f"data: {json.dumps({'error': _ollama_error_message(e)})}\n\n"
headers = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive"}
return Response(stream_with_context(run()), headers=headers)
if __name__ == "__main__":
host = os.getenv("HOST", "127.0.0.1")
port = _int_env("PORT", 8000)
debug = os.getenv("FLASK_DEBUG", "").strip().lower() in ("1", "true", "yes", "on")
app.run(host=host, port=port, debug=debug)