clipdex 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clipdex/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """clipdex: AI-powered footage search index for filmmakers."""
2
+
3
+ from .cli import __version__, main
4
+
5
+ __all__ = ["__version__", "main"]
clipdex/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main() or 0)
clipdex/cli.py ADDED
@@ -0,0 +1,912 @@
1
+ #!/usr/bin/env python3
2
+ """clipdex — AI-powered footage search index for filmmakers.
3
+
4
+ Index your entire footage library with Ollama vision models.
5
+ Search with natural language across all your clips.
6
+
7
+ Usage:
8
+ clipdex index <path> [--model MODEL] [--hosts HOSTS] [--interval SECS] [--force]
9
+ clipdex search <query> [--limit N] [--json] [--model MODEL] [--host HOST]
10
+ clipdex list [--path PATH] [--tags TAG] [--json]
11
+ clipdex info <file>
12
+ clipdex stats
13
+ clipdex reindex <file_or_id>
14
+ clipdex export [--format FORMAT] [--output FILE]
15
+ clipdex config [--db PATH] [--model MODEL] [--hosts HOSTS]
16
+
17
+ Zero dependencies beyond Python stdlib + ffmpeg + Ollama.
18
+ """
19
+
20
+ import argparse
21
+ import base64
22
+ import hashlib
23
+ import http.client
24
+ import json
25
+ import os
26
+ import re
27
+ import signal
28
+ import sqlite3
29
+ import subprocess
30
+ import sys
31
+ import tempfile
32
+ import threading
33
+ import time
34
+ import urllib.parse
35
+ import urllib.request
36
+ from concurrent.futures import ThreadPoolExecutor, as_completed
37
+ from pathlib import Path
38
+
39
+ __version__ = "0.2.0"
40
+
41
+ VIDEO_EXTS = {
42
+ ".mp4", ".mov", ".avi", ".mkv", ".webm", ".m4v", ".mxf",
43
+ ".mpg", ".mpeg", ".wmv", ".flv", ".ts", ".mts", ".m2ts",
44
+ ".3gp", ".ogv", ".r3d", ".braw", ".ari", ".dng",
45
+ }
46
+
47
+ DEFAULT_MODEL = "llama3.2-vision"
48
+ DEFAULT_DB = os.path.expanduser("~/.clipdex/index.db")
49
+ DEFAULT_HOSTS = "http://localhost:11434"
50
+ KEYFRAME_INTERVAL = 30 # seconds between keyframes
51
+ MAX_WORKERS = 4
52
+
53
+
54
+ # ── Database ──────────────────────────────────────────────────────────────────
55
+
56
+ def get_db(db_path=None):
57
+ db_path = db_path or _load_config().get("db", DEFAULT_DB)
58
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
59
+ conn = sqlite3.connect(db_path)
60
+ conn.row_factory = sqlite3.Row
61
+ conn.execute("PRAGMA journal_mode=WAL")
62
+ conn.execute("PRAGMA foreign_keys=ON")
63
+ conn.executescript("""
64
+ CREATE TABLE IF NOT EXISTS files (
65
+ id INTEGER PRIMARY KEY,
66
+ path TEXT UNIQUE NOT NULL,
67
+ filename TEXT NOT NULL,
68
+ size INTEGER,
69
+ duration REAL,
70
+ width INTEGER,
71
+ height INTEGER,
72
+ codec TEXT,
73
+ fps REAL,
74
+ hash TEXT,
75
+ indexed_at TEXT DEFAULT (datetime('now')),
76
+ updated_at TEXT DEFAULT (datetime('now'))
77
+ );
78
+ CREATE TABLE IF NOT EXISTS frames (
79
+ id INTEGER PRIMARY KEY,
80
+ file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
81
+ timestamp REAL NOT NULL,
82
+ description TEXT,
83
+ tags TEXT, -- JSON array
84
+ shot_type TEXT,
85
+ mood TEXT,
86
+ model TEXT,
87
+ host TEXT,
88
+ created_at TEXT DEFAULT (datetime('now')),
89
+ UNIQUE(file_id, timestamp)
90
+ );
91
+ CREATE INDEX IF NOT EXISTS idx_frames_file ON frames(file_id);
92
+ CREATE INDEX IF NOT EXISTS idx_frames_desc ON frames(description);
93
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
94
+ """)
95
+ return conn
96
+
97
+
98
+ # ── Config ────────────────────────────────────────────────────────────────────
99
+
100
+ CONFIG_PATH = os.path.expanduser("~/.clipdex/config.json")
101
+
102
+ def _load_config():
103
+ if os.path.exists(CONFIG_PATH):
104
+ with open(CONFIG_PATH) as f:
105
+ return json.load(f)
106
+ return {}
107
+
108
+ def _save_config(cfg):
109
+ os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
110
+ with open(CONFIG_PATH, "w") as f:
111
+ json.dump(cfg, f, indent=2)
112
+
113
+
114
+ # ── FFmpeg helpers ────────────────────────────────────────────────────────────
115
+
116
+ def get_video_metadata(filepath):
117
+ """Extract video metadata using ffprobe."""
118
+ try:
119
+ result = subprocess.run(
120
+ ["ffprobe", "-v", "quiet", "-print_format", "json",
121
+ "-show_format", "-show_streams", filepath],
122
+ capture_output=True, text=True, timeout=30
123
+ )
124
+ data = json.loads(result.stdout)
125
+ video_stream = next(
126
+ (s for s in data.get("streams", []) if s.get("codec_type") == "video"),
127
+ {}
128
+ )
129
+ fmt = data.get("format", {})
130
+ return {
131
+ "duration": float(fmt.get("duration", 0)),
132
+ "size": int(fmt.get("size", 0)),
133
+ "width": int(video_stream.get("width", 0)),
134
+ "height": int(video_stream.get("height", 0)),
135
+ "codec": video_stream.get("codec_name", "unknown"),
136
+ "fps": _parse_fps(video_stream.get("r_frame_rate", "0/1")),
137
+ }
138
+ except Exception as e:
139
+ print(f" ⚠ ffprobe failed: {e}", file=sys.stderr)
140
+ return None
141
+
142
+
143
+ def _parse_fps(rate_str):
144
+ try:
145
+ num, den = rate_str.split("/")
146
+ return round(int(num) / int(den), 2) if int(den) else 0
147
+ except (ValueError, ZeroDivisionError):
148
+ return 0
149
+
150
+
151
+ def extract_keyframes(filepath, interval, tmpdir):
152
+ """Extract keyframes at regular intervals. Returns list of (timestamp, image_path)."""
153
+ meta = get_video_metadata(filepath)
154
+ if not meta or meta["duration"] <= 0:
155
+ return [], None
156
+
157
+ duration = meta["duration"]
158
+ timestamps = []
159
+ t = 0
160
+ while t < duration:
161
+ timestamps.append(t)
162
+ t += interval
163
+ # Always grab the last quarter if we haven't
164
+ if duration - timestamps[-1] > interval * 0.5:
165
+ timestamps.append(duration - 1)
166
+
167
+ frames = []
168
+ for ts in timestamps:
169
+ outpath = os.path.join(tmpdir, f"frame_{ts:.1f}.jpg")
170
+ try:
171
+ subprocess.run(
172
+ ["ffmpeg", "-ss", str(ts), "-i", filepath,
173
+ "-vframes", "1", "-q:v", "2", "-y", outpath],
174
+ capture_output=True, timeout=30
175
+ )
176
+ if os.path.exists(outpath) and os.path.getsize(outpath) > 0:
177
+ frames.append((ts, outpath))
178
+ except Exception:
179
+ continue
180
+
181
+ return frames, meta
182
+
183
+
184
+ def file_hash(filepath, chunk_size=65536):
185
+ """Fast partial hash for change detection."""
186
+ h = hashlib.blake2b(digest_size=16)
187
+ size = os.path.getsize(filepath)
188
+ h.update(str(size).encode())
189
+ with open(filepath, "rb") as f:
190
+ h.update(f.read(chunk_size))
191
+ if size > chunk_size * 2:
192
+ f.seek(size // 2)
193
+ h.update(f.read(chunk_size))
194
+ if size > chunk_size:
195
+ f.seek(-chunk_size, 2)
196
+ h.update(f.read(chunk_size))
197
+ return h.hexdigest()
198
+
199
+
200
+ # ── Ollama vision ─────────────────────────────────────────────────────────────
201
+
202
+ FRAME_PROMPT = """Analyze this film frame. Provide a concise JSON response:
203
+ {
204
+ "description": "One sentence describing the visual content, subjects, action, and setting",
205
+ "tags": ["tag1", "tag2", "tag3"],
206
+ "shot_type": "wide|medium|close-up|extreme-close-up|aerial|pov|over-shoulder|insert|establishing",
207
+ "mood": "one or two words for the emotional tone"
208
+ }
209
+ Respond ONLY with valid JSON. No markdown, no explanation."""
210
+
211
+
212
+ def describe_frame(image_path, model, host):
213
+ """Send a frame to Ollama vision model and get structured description."""
214
+ with open(image_path, "rb") as f:
215
+ img_b64 = base64.b64encode(f.read()).decode()
216
+
217
+ payload = json.dumps({
218
+ "model": model,
219
+ "prompt": FRAME_PROMPT,
220
+ "images": [img_b64],
221
+ "stream": False,
222
+ "options": {"temperature": 0.1, "num_predict": 256},
223
+ }).encode()
224
+
225
+ url = urllib.parse.urlparse(host)
226
+ try:
227
+ if url.scheme == "https":
228
+ conn = http.client.HTTPSConnection(url.hostname, url.port or 443, timeout=120)
229
+ else:
230
+ conn = http.client.HTTPConnection(url.hostname, url.port or 11434, timeout=120)
231
+ conn.request("POST", "/api/generate", body=payload,
232
+ headers={"Content-Type": "application/json"})
233
+ resp = conn.getresponse()
234
+ if resp.status != 200:
235
+ return None
236
+ data = json.loads(resp.read().decode())
237
+ return _parse_vision_response(data.get("response", ""))
238
+ except Exception as e:
239
+ return None
240
+ finally:
241
+ try:
242
+ conn.close()
243
+ except Exception:
244
+ pass
245
+
246
+
247
+ def _parse_vision_response(text):
248
+ """Extract JSON from model response, handling markdown fences."""
249
+ text = text.strip()
250
+ # Strip markdown code fences
251
+ if text.startswith("```"):
252
+ text = re.sub(r"^```(?:json)?\s*", "", text)
253
+ text = re.sub(r"\s*```$", "", text)
254
+ try:
255
+ parsed = json.loads(text)
256
+ if not isinstance(parsed, dict):
257
+ raise ValueError("vision response is not a JSON object")
258
+ tags = parsed.get("tags", [])
259
+ if isinstance(tags, str):
260
+ tags = [t.strip() for t in tags.split(",") if t.strip()]
261
+ elif not isinstance(tags, list):
262
+ tags = []
263
+ return {
264
+ "description": str(parsed.get("description", "")),
265
+ "tags": [str(t) for t in tags],
266
+ "shot_type": str(parsed.get("shot_type", "")),
267
+ "mood": str(parsed.get("mood", "")),
268
+ }
269
+ except (json.JSONDecodeError, ValueError):
270
+ # Fallback: use raw text as description
271
+ return {
272
+ "description": text[:500],
273
+ "tags": [],
274
+ "shot_type": "",
275
+ "mood": "",
276
+ }
277
+
278
+
279
+ # ── Fleet-aware host selection ────────────────────────────────────────────────
280
+
281
+ class HostPool:
282
+ """Round-robin host pool with health checking."""
283
+
284
+ def __init__(self, hosts_str):
285
+ self.hosts = [h.strip() for h in hosts_str.split(",") if h.strip()]
286
+ self.healthy = list(self.hosts)
287
+ self.lock = threading.Lock()
288
+ self._idx = 0
289
+ self._check_health()
290
+
291
+ def _check_health(self):
292
+ healthy = []
293
+ for host in self.hosts:
294
+ try:
295
+ url = urllib.parse.urlparse(host)
296
+ conn = http.client.HTTPConnection(url.hostname, url.port or 11434, timeout=5)
297
+ conn.request("GET", "/api/tags")
298
+ resp = conn.getresponse()
299
+ if resp.status == 200:
300
+ healthy.append(host)
301
+ conn.close()
302
+ except Exception:
303
+ pass
304
+ with self.lock:
305
+ self.healthy = healthy if healthy else self.hosts[:1]
306
+
307
+ def next(self):
308
+ with self.lock:
309
+ if not self.healthy:
310
+ return self.hosts[0]
311
+ host = self.healthy[self._idx % len(self.healthy)]
312
+ self._idx += 1
313
+ return host
314
+
315
+ def count(self):
316
+ with self.lock:
317
+ return len(self.healthy)
318
+
319
+
320
+ # ── Index command ─────────────────────────────────────────────────────────────
321
+
322
+ def cmd_index(args):
323
+ target = os.path.abspath(args.path)
324
+ if not os.path.exists(target):
325
+ print(f"Error: path not found: {target}", file=sys.stderr)
326
+ return 1
327
+
328
+ cfg = _load_config()
329
+ model = args.model or cfg.get("model", DEFAULT_MODEL)
330
+ hosts_str = args.hosts or cfg.get("hosts", DEFAULT_HOSTS)
331
+ interval = args.interval or cfg.get("interval", KEYFRAME_INTERVAL)
332
+ force = args.force
333
+
334
+ pool = HostPool(hosts_str)
335
+ print(f"clipdex v{__version__}")
336
+ print(f" Model: {model}")
337
+ print(f" Hosts: {pool.count()} node(s) healthy")
338
+ print(f" Interval: {interval}s between keyframes")
339
+ print()
340
+
341
+ # Discover video files
342
+ videos = []
343
+ if os.path.isfile(target):
344
+ if Path(target).suffix.lower() in VIDEO_EXTS:
345
+ videos.append(target)
346
+ else:
347
+ for root, _, files in os.walk(target):
348
+ for f in files:
349
+ if Path(f).suffix.lower() in VIDEO_EXTS:
350
+ videos.append(os.path.join(root, f))
351
+ videos.sort()
352
+
353
+ if not videos:
354
+ print("No video files found.")
355
+ return 0
356
+
357
+ print(f"Found {len(videos)} video file(s)")
358
+ print()
359
+
360
+ conn = get_db()
361
+ indexed = 0
362
+ skipped = 0
363
+ errors = 0
364
+
365
+ for i, vpath in enumerate(videos, 1):
366
+ fname = os.path.basename(vpath)
367
+ print(f"[{i}/{len(videos)}] {fname}")
368
+
369
+ # Check if already indexed
370
+ existing = conn.execute("SELECT id, hash FROM files WHERE path = ?", (vpath,)).fetchone()
371
+ fhash = file_hash(vpath)
372
+
373
+ if existing and not force:
374
+ if existing["hash"] == fhash:
375
+ print(f" ✓ Already indexed (use --force to reindex)")
376
+ skipped += 1
377
+ continue
378
+ else:
379
+ print(f" ↻ File changed, reindexing...")
380
+ conn.execute("DELETE FROM frames WHERE file_id = ?", (existing["id"],))
381
+ conn.execute("DELETE FROM files WHERE id = ?", (existing["id"],))
382
+ conn.commit()
383
+
384
+ with tempfile.TemporaryDirectory() as tmpdir:
385
+ # Extract keyframes
386
+ print(f" Extracting keyframes...")
387
+ frames, meta = extract_keyframes(vpath, interval, tmpdir)
388
+ if not frames or not meta:
389
+ print(f" ✗ Failed to extract frames")
390
+ errors += 1
391
+ continue
392
+
393
+ # Insert file record
394
+ conn.execute(
395
+ """INSERT OR REPLACE INTO files (path, filename, size, duration, width, height, codec, fps, hash)
396
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
397
+ (vpath, fname, meta["size"], meta["duration"], meta["width"],
398
+ meta["height"], meta["codec"], meta["fps"], fhash)
399
+ )
400
+ conn.commit()
401
+ file_id = conn.execute("SELECT id FROM files WHERE path = ?", (vpath,)).fetchone()["id"]
402
+
403
+ # Describe frames with Ollama vision
404
+ dur_str = _format_duration(meta["duration"])
405
+ print(f" {len(frames)} frames from {dur_str} of footage")
406
+
407
+ def process_frame(frame_data):
408
+ ts, img_path = frame_data
409
+ host = pool.next()
410
+ result = describe_frame(img_path, model, host)
411
+ return ts, result, host
412
+
413
+ completed = 0
414
+ workers = min(MAX_WORKERS, pool.count() * 2)
415
+ with ThreadPoolExecutor(max_workers=workers) as executor:
416
+ futures = {executor.submit(process_frame, f): f for f in frames}
417
+ for future in as_completed(futures):
418
+ ts, result, host = future.result()
419
+ completed += 1
420
+ if result:
421
+ conn.execute(
422
+ """INSERT OR REPLACE INTO frames
423
+ (file_id, timestamp, description, tags, shot_type, mood, model, host)
424
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
425
+ (file_id, ts, result["description"],
426
+ json.dumps(result["tags"]), result["shot_type"],
427
+ result["mood"], model, host)
428
+ )
429
+ ts_str = _format_duration(ts)
430
+ desc_short = result["description"][:60]
431
+ print(f" [{completed}/{len(frames)}] {ts_str} — {desc_short}...")
432
+ else:
433
+ print(f" [{completed}/{len(frames)}] {_format_duration(ts)} — ✗ vision failed")
434
+
435
+ conn.commit()
436
+ indexed += 1
437
+ print()
438
+
439
+ print(f"Done: {indexed} indexed, {skipped} skipped, {errors} errors")
440
+ total_frames = conn.execute("SELECT COUNT(*) as c FROM frames").fetchone()["c"]
441
+ total_files = conn.execute("SELECT COUNT(*) as c FROM files").fetchone()["c"]
442
+ print(f"Library: {total_files} files, {total_frames} frames indexed")
443
+ conn.close()
444
+ return 0
445
+
446
+
447
+ # ── Search command ────────────────────────────────────────────────────────────
448
+
449
+ def cmd_search(args):
450
+ query = args.query
451
+ limit = args.limit or 20
452
+ cfg = _load_config()
453
+ conn = get_db()
454
+
455
+ # Phase 1: SQLite text search (fast, no API call)
456
+ keywords = query.lower().split()
457
+ conditions = []
458
+ params = []
459
+ for kw in keywords:
460
+ conditions.append("(LOWER(f.description) LIKE ? OR LOWER(f.tags) LIKE ? OR LOWER(f.shot_type) LIKE ? OR LOWER(f.mood) LIKE ?)")
461
+ params.extend([f"%{kw}%"] * 4)
462
+
463
+ where = " AND ".join(conditions)
464
+ sql = f"""
465
+ SELECT f.id, f.timestamp, f.description, f.tags, f.shot_type, f.mood,
466
+ v.path, v.filename, v.duration
467
+ FROM frames f
468
+ JOIN files v ON f.file_id = v.id
469
+ WHERE {where}
470
+ ORDER BY v.filename, f.timestamp
471
+ LIMIT ?
472
+ """
473
+ params.append(limit)
474
+ results = conn.execute(sql, params).fetchall()
475
+
476
+ if not results:
477
+ # Phase 2: If text search fails, try semantic search via Ollama
478
+ if not args.no_ai:
479
+ results = _semantic_search(conn, query, limit, cfg, args)
480
+
481
+ if not results:
482
+ print(f"No results for: {query}")
483
+ return 0
484
+
485
+ if args.json:
486
+ rows = [dict(r) for r in results]
487
+ print(json.dumps(rows, indent=2))
488
+ else:
489
+ print(f"Found {len(results)} result(s) for: {query}\n")
490
+ for r in results:
491
+ ts_str = _format_duration(r["timestamp"])
492
+ print(f" {r['filename']} @{ts_str}")
493
+ print(f" {r['description']}")
494
+ tags = json.loads(r["tags"]) if r["tags"] else []
495
+ if tags:
496
+ print(f" Tags: {', '.join(tags)}")
497
+ if r["shot_type"]:
498
+ print(f" Shot: {r['shot_type']} Mood: {r['mood']}")
499
+ print(f" → ffplay -ss {r['timestamp']:.1f} \"{r['path']}\"")
500
+ print()
501
+
502
+ conn.close()
503
+ return 0
504
+
505
+
506
+ def _semantic_search(conn, query, limit, cfg, args):
507
+ """Use Ollama to re-rank descriptions by semantic similarity."""
508
+ model = args.model or cfg.get("search_model", cfg.get("model", "llama3.2"))
509
+ host = args.host or cfg.get("hosts", DEFAULT_HOSTS).split(",")[0].strip()
510
+
511
+ # Get all frame descriptions
512
+ all_frames = conn.execute("""
513
+ SELECT f.id, f.timestamp, f.description, f.tags, f.shot_type, f.mood,
514
+ v.path, v.filename, v.duration
515
+ FROM frames f JOIN files v ON f.file_id = v.id
516
+ """).fetchall()
517
+
518
+ if not all_frames or len(all_frames) > 500:
519
+ return []
520
+
521
+ # Build a ranking prompt
522
+ descs = "\n".join(f"{i}: {r['description']}" for i, r in enumerate(all_frames))
523
+ prompt = f"""Given these frame descriptions, return the indices (comma-separated numbers) of frames that best match the search query: "{query}"
524
+
525
+ Return ONLY comma-separated numbers, nothing else. Max {limit} results, most relevant first.
526
+
527
+ Descriptions:
528
+ {descs}"""
529
+
530
+ payload = json.dumps({
531
+ "model": model,
532
+ "prompt": prompt,
533
+ "stream": False,
534
+ "options": {"temperature": 0, "num_predict": 100},
535
+ }).encode()
536
+
537
+ try:
538
+ url = urllib.parse.urlparse(host)
539
+ conn_http = http.client.HTTPConnection(url.hostname, url.port or 11434, timeout=60)
540
+ conn_http.request("POST", "/api/generate", body=payload,
541
+ headers={"Content-Type": "application/json"})
542
+ resp = conn_http.getresponse()
543
+ if resp.status != 200:
544
+ return []
545
+ data = json.loads(resp.read().decode())
546
+ indices_str = data.get("response", "").strip()
547
+ indices = [int(x.strip()) for x in re.findall(r"\d+", indices_str)]
548
+ return [all_frames[i] for i in indices if i < len(all_frames)][:limit]
549
+ except Exception:
550
+ return []
551
+
552
+
553
+ # ── List command ──────────────────────────────────────────────────────────────
554
+
555
+ def cmd_list(args):
556
+ conn = get_db()
557
+ sql = """
558
+ SELECT v.path, v.filename, v.duration, v.width, v.height, v.codec,
559
+ COUNT(f.id) as frame_count, v.indexed_at
560
+ FROM files v
561
+ LEFT JOIN frames f ON f.file_id = v.id
562
+ """
563
+ params = []
564
+ wheres = []
565
+
566
+ if args.path:
567
+ wheres.append("v.path LIKE ?")
568
+ params.append(f"%{args.path}%")
569
+
570
+ if args.tags:
571
+ wheres.append("f.tags LIKE ?")
572
+ params.append(f"%{args.tags}%")
573
+
574
+ if wheres:
575
+ sql += " WHERE " + " AND ".join(wheres)
576
+
577
+ sql += " GROUP BY v.id ORDER BY v.filename"
578
+ results = conn.execute(sql, params).fetchall()
579
+
580
+ if args.json:
581
+ print(json.dumps([dict(r) for r in results], indent=2))
582
+ else:
583
+ if not results:
584
+ print("No indexed files.")
585
+ return 0
586
+ print(f"{'File':<40} {'Duration':>10} {'Resolution':>12} {'Frames':>7} {'Indexed':>12}")
587
+ print("─" * 85)
588
+ for r in results:
589
+ dur = _format_duration(r["duration"]) if r["duration"] else "?"
590
+ res = f"{r['width']}x{r['height']}" if r["width"] else "?"
591
+ print(f"{r['filename']:<40} {dur:>10} {res:>12} {r['frame_count']:>7} {r['indexed_at'][:10]:>12}")
592
+
593
+ conn.close()
594
+ return 0
595
+
596
+
597
+ # ── Info command ──────────────────────────────────────────────────────────────
598
+
599
+ def cmd_info(args):
600
+ conn = get_db()
601
+ fpath = os.path.abspath(args.file)
602
+ row = conn.execute("SELECT * FROM files WHERE path = ?", (fpath,)).fetchone()
603
+ if not row:
604
+ # Try filename match
605
+ row = conn.execute("SELECT * FROM files WHERE filename LIKE ?",
606
+ (f"%{os.path.basename(args.file)}%",)).fetchone()
607
+ if not row:
608
+ print(f"File not indexed: {args.file}")
609
+ return 1
610
+
611
+ print(f"File: {row['filename']}")
612
+ print(f"Path: {row['path']}")
613
+ print(f"Duration: {_format_duration(row['duration'])}")
614
+ print(f"Resolution: {row['width']}x{row['height']}")
615
+ print(f"Codec: {row['codec']} FPS: {row['fps']}")
616
+ print(f"Size: {_format_size(row['size'])}")
617
+ print(f"Indexed: {row['indexed_at']}")
618
+ print()
619
+
620
+ frames = conn.execute(
621
+ "SELECT * FROM frames WHERE file_id = ? ORDER BY timestamp", (row["id"],)
622
+ ).fetchall()
623
+ print(f"Frames ({len(frames)}):")
624
+ for f in frames:
625
+ ts = _format_duration(f["timestamp"])
626
+ tags = json.loads(f["tags"]) if f["tags"] else []
627
+ print(f" @{ts} [{f['shot_type']}] {f['description']}")
628
+ if tags:
629
+ print(f" Tags: {', '.join(tags)} Mood: {f['mood']}")
630
+
631
+ conn.close()
632
+ return 0
633
+
634
+
635
+ # ── Stats command ─────────────────────────────────────────────────────────────
636
+
637
+ def cmd_stats(args):
638
+ conn = get_db()
639
+ files = conn.execute("SELECT COUNT(*) as c, SUM(duration) as d, SUM(size) as s FROM files").fetchone()
640
+ frames = conn.execute("SELECT COUNT(*) as c FROM frames").fetchone()
641
+ models = conn.execute("SELECT DISTINCT model FROM frames").fetchall()
642
+ shot_types = conn.execute(
643
+ "SELECT shot_type, COUNT(*) as c FROM frames WHERE shot_type != '' GROUP BY shot_type ORDER BY c DESC"
644
+ ).fetchall()
645
+ moods = conn.execute(
646
+ "SELECT mood, COUNT(*) as c FROM frames WHERE mood != '' GROUP BY mood ORDER BY c DESC LIMIT 10"
647
+ ).fetchall()
648
+ top_tags = conn.execute(
649
+ "SELECT tags FROM frames WHERE tags != '[]' AND tags IS NOT NULL"
650
+ ).fetchall()
651
+
652
+ # Count tags
653
+ tag_counts = {}
654
+ for row in top_tags:
655
+ for tag in json.loads(row["tags"]):
656
+ tag_counts[tag] = tag_counts.get(tag, 0) + 1
657
+ top_tags_sorted = sorted(tag_counts.items(), key=lambda x: -x[1])[:15]
658
+
659
+ print(f"clipdex Library Stats")
660
+ print(f"{'─' * 40}")
661
+ print(f" Files: {files['c']}")
662
+ print(f" Frames: {frames['c']}")
663
+ print(f" Duration: {_format_duration(files['d'] or 0)} total")
664
+ print(f" Size: {_format_size(files['s'] or 0)}")
665
+ print(f" Models: {', '.join(m['model'] for m in models) if models else 'none'}")
666
+ print()
667
+
668
+ if shot_types:
669
+ print("Shot Types:")
670
+ for st in shot_types:
671
+ bar = "█" * min(st["c"], 30)
672
+ print(f" {st['shot_type']:<20} {st['c']:>4} {bar}")
673
+ print()
674
+
675
+ if moods:
676
+ print("Top Moods:")
677
+ for m in moods:
678
+ print(f" {m['mood']:<20} {m['c']:>4}")
679
+ print()
680
+
681
+ if top_tags_sorted:
682
+ print("Top Tags:")
683
+ for tag, count in top_tags_sorted:
684
+ print(f" {tag:<20} {count:>4}")
685
+
686
+ conn.close()
687
+ return 0
688
+
689
+
690
+ # ── Export command ────────────────────────────────────────────────────────────
691
+
692
+ def cmd_export(args):
693
+ conn = get_db()
694
+ fmt = args.format or "csv"
695
+ results = conn.execute("""
696
+ SELECT v.filename, v.path, v.duration, f.timestamp, f.description,
697
+ f.tags, f.shot_type, f.mood
698
+ FROM frames f JOIN files v ON f.file_id = v.id
699
+ ORDER BY v.filename, f.timestamp
700
+ """).fetchall()
701
+
702
+ if not results:
703
+ print("Nothing to export.")
704
+ return 0
705
+
706
+ output = args.output
707
+
708
+ if fmt == "csv":
709
+ import csv
710
+ import io
711
+ buf = io.StringIO() if not output else open(output, "w", newline="")
712
+ writer = csv.writer(buf)
713
+ writer.writerow(["file", "path", "file_duration", "timestamp", "timecode",
714
+ "description", "tags", "shot_type", "mood"])
715
+ for r in results:
716
+ writer.writerow([
717
+ r["filename"], r["path"], f"{r['duration']:.1f}",
718
+ f"{r['timestamp']:.1f}", _format_duration(r["timestamp"]),
719
+ r["description"], r["tags"], r["shot_type"], r["mood"]
720
+ ])
721
+ if not output:
722
+ print(buf.getvalue())
723
+ else:
724
+ buf.close()
725
+ print(f"Exported {len(results)} frames to {output}")
726
+
727
+ elif fmt == "json":
728
+ data = [dict(r) for r in results]
729
+ text = json.dumps(data, indent=2)
730
+ if output:
731
+ with open(output, "w") as f:
732
+ f.write(text)
733
+ print(f"Exported {len(results)} frames to {output}")
734
+ else:
735
+ print(text)
736
+
737
+ elif fmt == "edl":
738
+ # Basic EDL for NLE import
739
+ lines = ["TITLE: clipdex export", ""]
740
+ for i, r in enumerate(results, 1):
741
+ tc_in = _secs_to_tc(r["timestamp"])
742
+ tc_out = _secs_to_tc(r["timestamp"] + 5)
743
+ lines.append(f"{i:03d} AX V C {tc_in} {tc_out} {tc_in} {tc_out}")
744
+ lines.append(f"* FROM CLIP NAME: {r['filename']}")
745
+ lines.append(f"* COMMENT: {r['description'][:80]}")
746
+ lines.append("")
747
+ text = "\n".join(lines)
748
+ if output:
749
+ with open(output, "w") as f:
750
+ f.write(text)
751
+ print(f"Exported {len(results)} frames to {output}")
752
+ else:
753
+ print(text)
754
+
755
+ conn.close()
756
+ return 0
757
+
758
+
759
+ # ── Config command ────────────────────────────────────────────────────────────
760
+
761
+ def cmd_config(args):
762
+ cfg = _load_config()
763
+ changed = False
764
+ if args.db:
765
+ cfg["db"] = os.path.abspath(args.db)
766
+ changed = True
767
+ if args.model:
768
+ cfg["model"] = args.model
769
+ changed = True
770
+ if args.hosts:
771
+ cfg["hosts"] = args.hosts
772
+ changed = True
773
+ if changed:
774
+ _save_config(cfg)
775
+ print("Config updated:")
776
+ else:
777
+ print("Current config:")
778
+ for k, v in cfg.items():
779
+ print(f" {k}: {v}")
780
+ if not cfg:
781
+ print(" (defaults)")
782
+ print(f" db: {DEFAULT_DB}")
783
+ print(f" model: {DEFAULT_MODEL}")
784
+ print(f" hosts: {DEFAULT_HOSTS}")
785
+ return 0
786
+
787
+
788
+ # ── Reindex command ───────────────────────────────────────────────────────────
789
+
790
+ def cmd_reindex(args):
791
+ conn = get_db()
792
+ target = args.file_or_id
793
+ # Try as file path
794
+ row = conn.execute("SELECT path FROM files WHERE path = ? OR filename LIKE ?",
795
+ (os.path.abspath(target), f"%{target}%")).fetchone()
796
+ if row:
797
+ # Remove and re-index
798
+ conn.execute("DELETE FROM frames WHERE file_id = (SELECT id FROM files WHERE path = ?)", (row["path"],))
799
+ conn.execute("DELETE FROM files WHERE path = ?", (row["path"],))
800
+ conn.commit()
801
+ conn.close()
802
+ args.path = row["path"]
803
+ args.force = True
804
+ return cmd_index(args)
805
+ else:
806
+ print(f"File not found in index: {target}")
807
+ conn.close()
808
+ return 1
809
+
810
+
811
+ # ── Helpers ───────────────────────────────────────────────────────────────────
812
+
813
+ def _format_duration(secs):
814
+ if not secs:
815
+ return "0:00"
816
+ h, rem = divmod(int(secs), 3600)
817
+ m, s = divmod(rem, 60)
818
+ if h:
819
+ return f"{h}:{m:02d}:{s:02d}"
820
+ return f"{m}:{s:02d}"
821
+
822
+
823
+ def _format_size(nbytes):
824
+ for unit in ["B", "KB", "MB", "GB", "TB"]:
825
+ if nbytes < 1024:
826
+ return f"{nbytes:.1f} {unit}"
827
+ nbytes /= 1024
828
+ return f"{nbytes:.1f} PB"
829
+
830
+
831
+ def _secs_to_tc(secs, fps=24):
832
+ h, rem = divmod(int(secs), 3600)
833
+ m, s = divmod(rem, 60)
834
+ f = int((secs % 1) * fps)
835
+ return f"{h:02d}:{m:02d}:{s:02d}:{f:02d}"
836
+
837
+
838
+ # ── CLI ───────────────────────────────────────────────────────────────────────
839
+
840
+ def main():
841
+ parser = argparse.ArgumentParser(
842
+ prog="clipdex",
843
+ description="AI-powered footage search index for filmmakers",
844
+ )
845
+ parser.add_argument("--version", action="version", version=f"clipdex {__version__}")
846
+ sub = parser.add_subparsers(dest="command")
847
+
848
+ # index
849
+ p_idx = sub.add_parser("index", help="Index video files with AI vision")
850
+ p_idx.add_argument("path", help="File or directory to index")
851
+ p_idx.add_argument("--model", "-m", help=f"Ollama vision model (default: {DEFAULT_MODEL})")
852
+ p_idx.add_argument("--hosts", help="Comma-separated Ollama hosts for fleet indexing")
853
+ p_idx.add_argument("--interval", "-i", type=int, help=f"Seconds between keyframes (default: {KEYFRAME_INTERVAL})")
854
+ p_idx.add_argument("--force", "-f", action="store_true", help="Reindex even if unchanged")
855
+
856
+ # search
857
+ p_search = sub.add_parser("search", help="Search indexed footage")
858
+ p_search.add_argument("query", help="Natural language search query")
859
+ p_search.add_argument("--limit", "-n", type=int, help="Max results (default: 20)")
860
+ p_search.add_argument("--json", "-j", action="store_true", help="JSON output")
861
+ p_search.add_argument("--no-ai", action="store_true", help="Skip AI semantic search fallback")
862
+ p_search.add_argument("--model", "-m", help="Model for semantic search")
863
+ p_search.add_argument("--host", help="Ollama host for semantic search")
864
+
865
+ # list
866
+ p_list = sub.add_parser("list", help="List indexed files")
867
+ p_list.add_argument("--path", help="Filter by path substring")
868
+ p_list.add_argument("--tags", help="Filter by tag")
869
+ p_list.add_argument("--json", "-j", action="store_true")
870
+
871
+ # info
872
+ p_info = sub.add_parser("info", help="Show details for an indexed file")
873
+ p_info.add_argument("file", help="File path or name")
874
+
875
+ # stats
876
+ sub.add_parser("stats", help="Show library statistics")
877
+
878
+ # reindex
879
+ p_re = sub.add_parser("reindex", help="Reindex a specific file")
880
+ p_re.add_argument("file_or_id", help="File path or name")
881
+
882
+ # export
883
+ p_exp = sub.add_parser("export", help="Export index data")
884
+ p_exp.add_argument("--format", "-f", choices=["csv", "json", "edl"], default="csv")
885
+ p_exp.add_argument("--output", "-o", help="Output file (default: stdout)")
886
+
887
+ # config
888
+ p_cfg = sub.add_parser("config", help="View or set configuration")
889
+ p_cfg.add_argument("--db", help="Database path")
890
+ p_cfg.add_argument("--model", help="Default vision model")
891
+ p_cfg.add_argument("--hosts", help="Comma-separated Ollama hosts")
892
+
893
+ args = parser.parse_args()
894
+ if not args.command:
895
+ parser.print_help()
896
+ return 0
897
+
898
+ commands = {
899
+ "index": cmd_index,
900
+ "search": cmd_search,
901
+ "list": cmd_list,
902
+ "info": cmd_info,
903
+ "stats": cmd_stats,
904
+ "reindex": cmd_reindex,
905
+ "export": cmd_export,
906
+ "config": cmd_config,
907
+ }
908
+ return commands[args.command](args)
909
+
910
+
911
+ if __name__ == "__main__":
912
+ sys.exit(main() or 0)
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.5
2
+ Name: clipdex
3
+ Version: 0.2.0
4
+ Summary: AI-powered footage search for filmmakers: index your video library with local vision models and search it in plain language.
5
+ Project-URL: Homepage, https://github.com/Obrais-cloud/clipdex
6
+ Project-URL: Issues, https://github.com/Obrais-cloud/clipdex/issues
7
+ Author: Brais Revaldería
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: dailies,editing,film,footage,ollama,post-production,search,video,vision
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Multimedia :: Video
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+
22
+ # clipdex
23
+
24
+ [![CI](https://github.com/Obrais-cloud/clipdex/actions/workflows/ci.yml/badge.svg)](https://github.com/Obrais-cloud/clipdex/actions/workflows/ci.yml)
25
+ [![PyPI](https://img.shields.io/pypi/v/clipdex)](https://pypi.org/project/clipdex/)
26
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
27
+ ![License](https://img.shields.io/badge/license-MIT-green)
28
+
29
+ **Search your footage like you search your email.** clipdex indexes a video library with a local vision model, then lets you find shots in plain language: "horse at sunset", "close-up hands", "all the wides from day 2".
30
+
31
+ Built by a working director/DP for real post-production: it runs entirely on your machines, so unreleased footage never leaves the building.
32
+
33
+ ```bash
34
+ pipx install clipdex
35
+ clipdex index ./footage
36
+ clipdex search "horse galloping"
37
+ ```
38
+
39
+ ```
40
+ day1_001.mov @0:30
41
+ Group of wild horses galloping across green hillside
42
+ Tags: horses, galloping, nature
43
+ Shot: wide Mood: energetic
44
+ -> ffplay -ss 30.0 "footage/day1_001.mov"
45
+ ```
46
+
47
+ ## Why
48
+
49
+ Editors and assistant editors lose hours scrubbing timelines to find "that shot". Commercial tools that solve this upload your media to a cloud, which is a non-starter for client work under NDA, documentary sources, or anything pre-release.
50
+
51
+ clipdex extracts keyframes, describes each one with an Ollama vision model (description, tags, shot type, mood), and stores it in a local SQLite index. No API keys, no uploads, no subscription.
52
+
53
+ ## Who it's for
54
+
55
+ - **Editors and AEs** logging dailies or digging through a documentary archive
56
+ - **Directors and DPs** pulling selects and references from past shoots
57
+ - **Small post houses** that want AI search without sending media to a third party
58
+
59
+ ## Requirements
60
+
61
+ - Python 3.10+
62
+ - [ffmpeg](https://ffmpeg.org/) (ffmpeg and ffprobe on your PATH)
63
+ - [Ollama](https://ollama.com/) with a vision model, for example `ollama pull llama3.2-vision`
64
+
65
+ Zero Python dependencies. Standard library only.
66
+
67
+ ## Install
68
+
69
+ ```bash
70
+ # Recommended
71
+ pipx install clipdex
72
+
73
+ # Or with pip
74
+ pip install clipdex
75
+
76
+ # Or run straight from a checkout, no install
77
+ git clone https://github.com/Obrais-cloud/clipdex.git
78
+ ln -s "$(pwd)/clipdex/clipdex" /usr/local/bin/clipdex
79
+ ```
80
+
81
+ ## Usage
82
+
83
+ ### Index footage
84
+
85
+ ```bash
86
+ clipdex index ./footage # directory, recursive
87
+ clipdex index ./footage/day1_001.mov # single file
88
+ clipdex index ./footage --model gemma3:4b # different vision model
89
+ clipdex index ./footage --interval 15 # keyframe every 15s (default 30)
90
+ clipdex index ./footage --force # reindex unchanged files too
91
+ ```
92
+
93
+ ### Index across several machines
94
+
95
+ Point clipdex at more than one Ollama host and it spreads frame analysis across them, skipping any node that fails a health check. Useful when a single workstation would take all night.
96
+
97
+ ```bash
98
+ clipdex index ./footage --hosts "http://mac-studio:11434,http://edit-bay-2:11434,http://render-node:11434"
99
+ ```
100
+
101
+ ### Search
102
+
103
+ ```bash
104
+ clipdex search "horse running"
105
+ clipdex search "close-up" --limit 5
106
+ clipdex search "aerial shot" --json # for scripts
107
+ clipdex search "horse" --no-ai # keyword match only, skip AI re-ranking
108
+ ```
109
+
110
+ Keyword matching runs first across descriptions, tags, moods and shot types. If it finds nothing, clipdex asks the model to rank frames semantically.
111
+
112
+ ### Export to your NLE
113
+
114
+ ```bash
115
+ clipdex export --format edl --output selects.edl # import into Premiere, Resolve, Avid
116
+ clipdex export --format csv --output shots.csv
117
+ clipdex export --format json
118
+ ```
119
+
120
+ ### Other commands
121
+
122
+ ```bash
123
+ clipdex list # every indexed file
124
+ clipdex list --tags "horse"
125
+ clipdex list --path "day1"
126
+ clipdex info day1_001.mov # details for one file
127
+ clipdex stats # library totals
128
+ clipdex reindex day1_001.mov
129
+ clipdex config --model gemma3:4b
130
+ clipdex config --db ~/projects/my-doc/index.db # one index per project
131
+ ```
132
+
133
+ ## How it works
134
+
135
+ 1. **Discover** video files by extension (.mp4, .mov, .mxf, .r3d, .braw and more)
136
+ 2. **Extract** keyframes at a fixed interval with ffmpeg
137
+ 3. **Describe** each frame with an Ollama vision model as structured JSON
138
+ 4. **Store** everything in SQLite (WAL mode)
139
+ 5. **Search** with keyword matching, falling back to AI ranking
140
+
141
+ Files are tracked by a fast partial hash (blake2b over head, middle and tail), so re-running `clipdex index` only processes new or changed media.
142
+
143
+ ## Config
144
+
145
+ Defaults live in `~/.clipdex/config.json`.
146
+
147
+ | Setting | Default | Description |
148
+ |---------|---------|-------------|
149
+ | `db` | `~/.clipdex/index.db` | SQLite database path |
150
+ | `model` | `llama3.2-vision` | Ollama vision model |
151
+ | `hosts` | `http://localhost:11434` | Comma-separated Ollama endpoints |
152
+ | `interval` | `30` | Seconds between keyframes |
153
+
154
+ ## Supported formats
155
+
156
+ MP4, MOV, AVI, MKV, WebM, M4V, MXF, MPEG, WMV, FLV, TS, MTS, M2TS, 3GP, OGV, R3D, BRAW, ARI, DNG. Camera-raw formats depend on your ffmpeg build.
157
+
158
+ ## Part of an open toolkit for film production
159
+
160
+ clipdex is one of a set of local-first, open-source tools for production and post, all running on Ollama with no API keys:
161
+
162
+ | Tool | What it does |
163
+ |------|--------------|
164
+ | **clipdex** | Natural-language search across a footage library |
165
+ | [cliplog](https://github.com/Obrais-cloud/cliplog) | Automatic shot log: detects cuts and describes every shot |
166
+ | [dailies](https://github.com/Obrais-cloud/dailies) | Dailies reports from a folder of footage: scenes, palettes, captions |
167
+ | [clipvault](https://github.com/Obrais-cloud/clipvault) | Semantic clip library with embeddings |
168
+ | [chromacut](https://github.com/Obrais-cloud/chromacut) | Color analysis: extracts the color narrative of a film |
169
+ | [scriptbreak](https://github.com/Obrais-cloud/scriptbreak) | Script breakdown from Fountain: cast, props, wardrobe, VFX per scene |
170
+ | [shotgen](https://github.com/Obrais-cloud/shotgen) | Shot list to animatic: storyboards and motion previews |
171
+
172
+ ## Contributing
173
+
174
+ Issues and pull requests are welcome, especially from editors and AEs with real workflows to support. Run the tests with:
175
+
176
+ ```bash
177
+ pip install pytest
178
+ pytest
179
+ ```
180
+
181
+ ## License
182
+
183
+ MIT
@@ -0,0 +1,8 @@
1
+ clipdex/__init__.py,sha256=DPePuJ-oG07QStpi6A79FWkjvUz2fvK-ycAQDkUDVbk,134
2
+ clipdex/__main__.py,sha256=hrGOcfQbkFw42RtnrY7luzmZOYGW5sugmNb4YiwmIr0,57
3
+ clipdex/cli.py,sha256=0w4ccPtG5xuTb_9mWjyCAUZbuuhlhNHjrDgJcNBJfqE,33372
4
+ clipdex-0.2.0.dist-info/METADATA,sha256=Wnf5dF-XpcuVubFn8tLEbizpikxVJ47pZTyeU9zRSN8,6987
5
+ clipdex-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ clipdex-0.2.0.dist-info/entry_points.txt,sha256=gUfpTgF01LYbq1esIy-WcVHrEZh7XVE20FAlOEG9sEM,45
7
+ clipdex-0.2.0.dist-info/licenses/LICENSE,sha256=sQ5b5NkYxD2gp2HQmM3Kk2sjkoY5MEZZpEoK4wuez4I,1074
8
+ clipdex-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ clipdex = clipdex.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brais Revaldería
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.