File size: 11,661 Bytes
fb12ddc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# HF_Space_hipVS/ingest.py
# =========================
# Ingestion pipeline β€” embeds images/frames DIRECTLY with Qwen3-VL or CLIP.
# No captioning step. The vision-language model encodes images and text
# into the same vector space natively.
#
# CAGRA is rebuilt on every insert (optimized for query, not ingestion).

import logging
import os
import shutil
import subprocess
import tempfile
import time
from pathlib import Path

from PIL import Image as PILImage

from config import (
    EMBED_DIM,
    FRAME_EVERY_SEC,
    IMAGE_EXTENSIONS,
    VIDEO_EXTENSIONS,
    get_project_dir,
    DEFAULT_PROJECT,
)
from embedding import embed_image, embed_image_bytes
from vector_store import get_store

logger = logging.getLogger(__name__)


# ── Helpers ──────────────────────────────────────────────────────────────────

def fmt_time(seconds: float) -> str:
    m, s = divmod(int(seconds), 60)
    return f"{m:02d}:{s:02d}"


def check_ffmpeg() -> bool:
    try:
        subprocess.run(["ffprobe", "-version"], capture_output=True, timeout=5)
        return True
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return False


HAS_FFMPEG = check_ffmpeg()


def get_duration(video_path: str) -> float:
    try:
        r = subprocess.run(
            ["ffprobe", "-v", "error",
             "-show_entries", "format=duration",
             "-of", "default=noprint_wrappers=1:nokey=1",
             video_path],
            capture_output=True, text=True, timeout=30,
        )
        return float(r.stdout.strip())
    except Exception as e:
        logger.warning(f"ffprobe error: {e}")
        return 0.0


def extract_frame(video_path: str, timestamp_sec: float, out_path: str) -> bool:
    result = subprocess.run(
        ["ffmpeg", "-y",
         "-ss", f"{timestamp_sec:.3f}",
         "-i", video_path,
         "-frames:v", "1",
         "-q:v", "2",
         "-vf", "scale=640:-1",
         out_path],
        capture_output=True, timeout=30,
    )
    return result.returncode == 0 and os.path.exists(out_path) and os.path.getsize(out_path) > 0


def get_image_meta(path: Path) -> dict:
    stat = path.stat()
    size = f"{round(stat.st_size / 1024, 1)}KB"
    try:
        with PILImage.open(path) as img:
            res = f"{img.width}x{img.height}"
    except Exception:
        res = "unknown"
    return {
        "file_path": str(path.resolve()),
        "file_name": path.name,
        "file_size": size,
        "resolution": res,
    }


# ── Image Ingestion ─────────────────────────────────────────────────────────

def ingest_images(project: str = DEFAULT_PROJECT, progress_callback=None) -> tuple[int, str]:
    """Ingest all images from a project's images/ directory."""
    proj_dir = get_project_dir(project)
    image_dir = proj_dir / "images"
    store = get_store(project, "image_index")

    files = sorted(
        f for f in image_dir.iterdir()
        if f.suffix.lower() in IMAGE_EXTENSIONS
    )[:200]

    if not files:
        return 0, f"No images found in {image_dir}"

    store.clear()
    log = [f"[{project}] Found {len(files)} images\n"]

    import numpy as np
    all_vectors = []
    all_ids = []
    all_meta = []

    for i, p in enumerate(files):
        meta = get_image_meta(p)
        try:
            img = PILImage.open(p)
            vec = embed_image(img)  # direct multimodal embed, no captioning
            all_vectors.append(vec)
            all_ids.append(meta["file_name"])
            all_meta.append(meta)
            log.append(f"  [{i+1}/{len(files)}] {p.name} ({meta['resolution']})")
        except Exception as e:
            log.append(f"  [{i+1}/{len(files)}] {p.name}: FAILED ({e})")

        if progress_callback:
            progress_callback((i + 1) / len(files), desc=f"Embedding {p.name}...")

    if all_vectors:
        vectors = np.stack(all_vectors)
        store.add(vectors, all_ids, all_meta)  # CAGRA rebuilt inside add()

    log.append(f"\n{len(all_vectors)} images indexed ({store.mode})")
    return len(all_vectors), "\n".join(log)


def ingest_single_image(file_path: str, project: str = DEFAULT_PROJECT) -> tuple[bool, str]:
    """Ingest a single uploaded image. CAGRA is rebuilt."""
    path = Path(file_path)
    proj_dir = get_project_dir(project)
    dest = proj_dir / "images" / path.name
    shutil.copy2(str(path), str(dest))

    store = get_store(project, "image_index")
    meta = get_image_meta(dest)

    try:
        img = PILImage.open(dest)
        vec = embed_image(img)
        store.append_and_rebuild(vec, meta["file_name"], meta)
        return True, f"Indexed: {path.name} ({meta['resolution']})"
    except Exception as e:
        return False, f"Failed: {path.name} -- {e}"


def ingest_image_from_pil(
    image: PILImage.Image,
    file_name: str,
    extra_meta: dict | None = None,
    project: str = DEFAULT_PROJECT,
) -> tuple[bool, str]:
    """Ingest a PIL Image directly (used by seed_data). No CAGRA rebuild per-image."""
    proj_dir = get_project_dir(project)
    dest = proj_dir / "images" / file_name
    store = get_store(project, "image_index")
    
    try:
        if not dest.exists():
            image.save(str(dest))
        
        vec = embed_image(image)
        meta = {
            "file_name": file_name,
            "file_path": str(dest.resolve()),
            **(extra_meta or {})
        }
        store.append(vec, file_name, meta)  # no rebuild β€” seed_data calls rebuild at end
        return True, file_name
    except Exception as e:
        return False, str(e)


# ── Video Ingestion ─────────────────────────────────────────────────────────

def ingest_videos(project: str = DEFAULT_PROJECT, progress_callback=None) -> tuple[int, str]:
    """Ingest all videos from a project's videos/ directory."""
    if not HAS_FFMPEG:
        return 0, "ffmpeg not found -- install ffmpeg for video ingestion."

    proj_dir = get_project_dir(project)
    video_dir = proj_dir / "videos"
    store = get_store(project, "video_index")

    frames_root = proj_dir / "videos" / "frames"
    frames_root.mkdir(parents=True, exist_ok=True)

    files = sorted(
        f for f in video_dir.iterdir()
        if f.suffix.lower() in VIDEO_EXTENSIONS
    )
    if not files:
        return 0, f"No videos found in {video_dir}"

    store.clear()
    log = [f"[{project}] Found {len(files)} video(s) -- frame interval: {FRAME_EVERY_SEC}s\n"]
    total = 0

    for video_path in files:
        video_str = str(video_path.resolve())
        duration = get_duration(video_str)
        if duration <= 0:
            log.append(f"  Skipping {video_path.name} (duration unreadable)")
            continue

        timestamps = [0.5]
        t = float(FRAME_EVERY_SEC)
        while t < duration:
            timestamps.append(round(t, 2))
            t += FRAME_EVERY_SEC
        if (duration - 1.0) not in timestamps:
            timestamps.append(round(max(0, duration - 1.0), 2))
        timestamps = sorted(set(timestamps))

        log.append(f"  {video_path.name} ({duration:.1f}s -> {len(timestamps)} frames)")

        with tempfile.TemporaryDirectory() as tmp_dir:
            for idx, ts in enumerate(timestamps):
                frame_path = os.path.join(tmp_dir, f"frame_{idx:05d}.jpg")
                if not extract_frame(video_str, ts, frame_path):
                    continue

                try:
                    with open(frame_path, "rb") as f:
                        frame_data = f.read()
                    
                    # Save frame permanently
                    perm_frame_path = frames_root / f"{video_path.name}_{ts:.2f}.jpg"
                    shutil.copy2(frame_path, str(perm_frame_path))
                    
                    vec = embed_image_bytes(frame_data)
                    frame_meta = {
                        "video_path": video_str,
                        "video_name": video_path.name,
                        "frame_path": str(perm_frame_path.resolve()),
                        "timestamp_sec": ts,
                        "timestamp_label": fmt_time(ts),
                        "duration_total": round(duration, 2),
                    }
                    store.append(vec, f"{video_path.name}@{ts}", frame_meta)
                    total += 1
                    time.sleep(0.05)
                except Exception as e:
                    log.append(f"    ts={fmt_time(ts)}: FAILED ({e})")

                if progress_callback:
                    progress_callback(
                        (idx + 1) / len(timestamps),
                        desc=f"{video_path.name} frame {idx+1}/{len(timestamps)}",
                    )

        log.append(f"    Done ({len(timestamps)} frames)")

    # Rebuild CAGRA once for all videos
    if store.has_data():
        store.rebuild_gpu_index()
        store._persist()

    log.append(f"\n{total} video frames indexed ({store.mode})")
    return total, "\n".join(log)


def ingest_single_video(file_path: str, project: str = DEFAULT_PROJECT, progress_callback=None) -> tuple[int, str]:
    """Ingest a single uploaded video. CAGRA rebuilt at end."""
    path = Path(file_path)
    proj_dir = get_project_dir(project)
    dest = proj_dir / "videos" / path.name
    shutil.copy2(str(path), str(dest))

    if not HAS_FFMPEG:
        return 0, "ffmpeg not found"

    store = get_store(project, "video_index")
    video_str = str(dest.resolve())
    duration = get_duration(video_str)
    if duration <= 0:
        return 0, f"Could not read duration for {path.name}"

    frames_root = proj_dir / "videos" / "frames"
    frames_root.mkdir(parents=True, exist_ok=True)

    timestamps = [0.5]
    t = float(FRAME_EVERY_SEC)
    while t < duration:
        timestamps.append(round(t, 2))
        t += FRAME_EVERY_SEC
    timestamps = sorted(set(timestamps))
    count = 0

    with tempfile.TemporaryDirectory() as tmp_dir:
        for idx, ts in enumerate(timestamps):
            frame_path = os.path.join(tmp_dir, f"frame_{idx:05d}.jpg")
            if not extract_frame(video_str, ts, frame_path):
                continue
            try:
                with open(frame_path, "rb") as f:
                    frame_data = f.read()
                
                # Save frame permanently
                perm_frame_path = frames_root / f"{path.name}_{ts:.2f}.jpg"
                shutil.copy2(frame_path, str(perm_frame_path))

                vec = embed_image_bytes(frame_data)
                frame_meta = {
                    "video_path": video_str,
                    "video_name": path.name,
                    "frame_path": str(perm_frame_path.resolve()),
                    "timestamp_sec": ts,
                    "timestamp_label": fmt_time(ts),
                    "duration_total": round(duration, 2),
                }
                store.append(vec, f"{path.name}@{ts}", frame_meta)
                count += 1
            except Exception as e:
                logger.error(f"Frame embed error: {e}")

            if progress_callback:
                progress_callback((idx + 1) / len(timestamps))

    # Rebuild CAGRA after all frames
    if store.has_data():
        store.rebuild_gpu_index()
        store._persist()

    return count, f"{count} frames indexed for {path.name} ({duration:.1f}s)"