feat: round output JSON floats to 2dp + unify ensure_ascii for asr/asrx

This commit is contained in:
Accusys
2026-08-16 06:38:39 +08:00
parent 39e9ce4c3b
commit 5e6a7b7d51
18 changed files with 249 additions and 45 deletions
+33 -10
View File
@@ -18,6 +18,7 @@ Configuration:
import sys import sys
import json import json
import os import os
import math
import time import time
import argparse import argparse
import signal import signal
@@ -28,6 +29,28 @@ from faster_whisper import WhisperModel
PROCESSOR_VERSION = "2.1" PROCESSOR_VERSION = "2.1"
MODEL_SIZE = "small" MODEL_SIZE = "small"
DEVICE = "cpu" DEVICE = "cpu"
def segment_confidence(segment) -> float:
"""Derive a 0-1 confidence from faster-whisper's avg_logprob.
faster-whisper segments do NOT expose a `confidence` attribute, so the old
getattr(segment, "confidence", 0.0) always returned 0. avg_logprob is the
average log-probability per token (negative); exp() maps it to (0, 1].
"""
logprob = getattr(segment, "avg_logprob", -0.1)
return min(1.0, math.exp(logprob))
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
COMPUTE_TYPE = "int8" COMPUTE_TYPE = "int8"
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -213,7 +236,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
"segments": [] "segments": []
} }
with open(output_path, "w") as f: with open(output_path, "w") as f:
json.dump(output, f, indent=2) json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False)
if publisher: if publisher:
publisher.complete("asr", "0 segments (no audio)") publisher.complete("asr", "0 segments (no audio)")
sys.stderr.write("ASR: No audio stream, skipping transcription\n") sys.stderr.write("ASR: No audio stream, skipping transcription\n")
@@ -347,21 +370,21 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
seg_end = start_t + segment.end seg_end = start_t + segment.end
scene_idx = find_scene_idx((seg_start + seg_end) / 2) scene_idx = find_scene_idx((seg_start + seg_end) / 2)
scene_segments.append({ scene_segments.append({
"start_time": seg_start, "start_time": round(seg_start, 2),
"end_time": seg_end, "end_time": round(seg_end, 2),
"start_frame": int(round(seg_start * fps)), "start_frame": int(round(seg_start * fps)),
"end_frame": int(round(seg_end * fps)), "end_frame": int(round(seg_end * fps)),
"text": segment.text.strip(), "text": segment.text.strip(),
"scene_number": scene_idx + 1, "scene_number": scene_idx + 1,
"language": seg_language, "language": seg_language,
"confidence": getattr(segment, "confidence", 0.0), "confidence": round(segment_confidence(segment), 2),
}) })
total_segments += 1 total_segments += 1
# 當前 scene 結果寫入 .asr.tmp # 當前 scene 結果寫入 .asr.tmp
all_segments.extend(scene_segments) all_segments.extend(scene_segments)
with open(tmp_path, "w") as f: with open(tmp_path, "w") as f:
json.dump({"language": transcript_language or "", "segments": all_segments}, f) json.dump(round_json_numbers({"language": transcript_language or "", "segments": all_segments}), f, ensure_ascii=False)
if total_segments % 100 == 0: if total_segments % 100 == 0:
if publisher: if publisher:
@@ -387,7 +410,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
# Write final output with status # Write final output with status
with open(tmp_path, "w") as f: with open(tmp_path, "w") as f:
json.dump({"status": status, "language": info_language, "segments": all_segments}, f) json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
else: else:
# 無 CUT 資料,直接轉錄(原有流程) # 無 CUT 資料,直接轉錄(原有流程)
segments, info = transcribe_with_fallback(model, video_path, publisher) segments, info = transcribe_with_fallback(model, video_path, publisher)
@@ -397,12 +420,12 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
all_segments = [] all_segments = []
for segment in segments: for segment in segments:
all_segments.append({ all_segments.append({
"start_time": segment.start, "start_time": round(segment.start, 2),
"end_time": segment.end, "end_time": round(segment.end, 2),
"start_frame": int(round(segment.start * fps)), "start_frame": int(round(segment.start * fps)),
"end_frame": int(round(segment.end * fps)), "end_frame": int(round(segment.end * fps)),
"text": segment.text.strip(), "text": segment.text.strip(),
"confidence": getattr(segment, "confidence", 0.0), "confidence": round(segment_confidence(segment), 2),
}) })
total_segments += 1 total_segments += 1
if total_segments % 100 == 0: if total_segments % 100 == 0:
@@ -416,7 +439,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
status = "silent_audio" status = "silent_audio"
with open(tmp_path, "w") as f: with open(tmp_path, "w") as f:
json.dump({"status": status, "language": info_language, "segments": all_segments}, f) json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
if publisher: if publisher:
publisher.info("asr", f"ASR_LANGUAGE:{info_language}") publisher.info("asr", f"ASR_LANGUAGE:{info_language}")
+12 -1
View File
@@ -87,10 +87,21 @@ def _cleanup(tmp_dir):
shutil.rmtree(tmp_dir, ignore_errors=True) shutil.rmtree(tmp_dir, ignore_errors=True)
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
def _atomic_write(path: str, data: dict): def _atomic_write(path: str, data: dict):
tmp = path + ".tmp" tmp = path + ".tmp"
with open(tmp, "w") as f: with open(tmp, "w") as f:
json.dump(data, f, indent=2) json.dump(round_json_numbers(data), f, indent=2, ensure_ascii=False)
os.rename(tmp, path) os.rename(tmp, path)
+14 -3
View File
@@ -21,6 +21,17 @@ from urllib.request import Request, urlopen
from urllib.error import URLError from urllib.error import URLError
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
def _load_audio(path): def _load_audio(path):
"""載入音頻文件,回傳 (wav_numpy, sample_rate)""" """載入音頻文件,回傳 (wav_numpy, sample_rate)"""
import soundfile as sf import soundfile as sf
@@ -115,7 +126,7 @@ def _save_checkpoint(path: str, data: dict):
tmp = path + ".tmp" tmp = path + ".tmp"
Path(tmp).parent.mkdir(parents=True, exist_ok=True) Path(tmp).parent.mkdir(parents=True, exist_ok=True)
with open(tmp, "w", encoding="utf-8") as f: with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False) json.dump(round_json_numbers(data), f, indent=2, ensure_ascii=False)
os.replace(tmp, path) os.replace(tmp, path)
@@ -408,7 +419,7 @@ class SelfASRXFixed:
if output_path: if output_path:
Path(output_path).parent.mkdir(parents=True, exist_ok=True) Path(output_path).parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f: with open(output_path, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False) json.dump(round_json_numbers(result), f, indent=2, ensure_ascii=False)
print(f"\n[SelfASRX] Saved to: {output_path}") print(f"\n[SelfASRX] Saved to: {output_path}")
print(f"\n[SelfASRX] Done! {len(segments)} segments, " print(f"\n[SelfASRX] Done! {len(segments)} segments, "
@@ -541,7 +552,7 @@ class SelfASRXFixed:
if output_path: if output_path:
Path(output_path).parent.mkdir(parents=True, exist_ok=True) Path(output_path).parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f: with open(output_path, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False) json.dump(round_json_numbers(result), f, indent=2, ensure_ascii=False)
print(f"\n[SelfASRX] Saved to: {output_path}") print(f"\n[SelfASRX] Saved to: {output_path}")
print(f"\n[SelfASRX] Done! {len(segments)} segments, " print(f"\n[SelfASRX] Done! {len(segments)} segments, "
+12 -1
View File
@@ -29,6 +29,17 @@ FACES_COLLECTION = "_faces"
BATCH_SIZE = 1000 BATCH_SIZE = 1000
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
def qdrant_scroll(filter_dict, limit=BATCH_SIZE, offset=None, with_payload=None): def qdrant_scroll(filter_dict, limit=BATCH_SIZE, offset=None, with_payload=None):
"""Scroll Qdrant collection with filter.""" """Scroll Qdrant collection with filter."""
body = {"limit": limit, "filter": filter_dict, "with_vector": False} body = {"limit": limit, "filter": filter_dict, "with_vector": False}
@@ -261,7 +272,7 @@ def build_trace_profiles(file_uuid=None, dry_run=False):
# Write trace_profile.json # Write trace_profile.json
with open(profile_path, "w") as f: with open(profile_path, "w") as f:
json.dump(profile, f, indent=2, ensure_ascii=False) json.dump(round_json_numbers(profile), f, indent=2, ensure_ascii=False)
total_profiles += 1 total_profiles += 1
+6 -6
View File
@@ -205,8 +205,8 @@ def rebuild_scenes(
"scene_number": len(scenes) + 1, "scene_number": len(scenes) + 1,
"start_frame": prev_frame, "start_frame": prev_frame,
"end_frame": end_frame - 1, "end_frame": end_frame - 1,
"start_time": prev_time, "start_time": round(prev_time, 2),
"end_time": t - (1.0 / fps) if fps > 0 else t, "end_time": round(t - (1.0 / fps) if fps > 0 else t, 2),
} }
) )
prev_time = t prev_time = t
@@ -220,8 +220,8 @@ def rebuild_scenes(
"scene_number": len(scenes) + 1, "scene_number": len(scenes) + 1,
"start_frame": prev_frame, "start_frame": prev_frame,
"end_frame": last_frame - 1, "end_frame": last_frame - 1,
"start_time": prev_time, "start_time": round(prev_time, 2),
"end_time": duration, "end_time": round(duration, 2),
} }
) )
@@ -265,7 +265,7 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""):
"start_frame": 0, "start_frame": 0,
"end_frame": total_frames - 1, "end_frame": total_frames - 1,
"start_time": 0.0, "start_time": 0.0,
"end_time": duration, "end_time": round(duration, 2),
} }
] ]
if publisher: if publisher:
@@ -275,7 +275,7 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""):
result = { result = {
"frame_count": total_frames, "frame_count": total_frames,
"fps": fps, "fps": round(fps, 2),
"scenes": scenes, "scenes": scenes,
} }
+12 -1
View File
@@ -33,6 +33,17 @@ from sklearn.cluster import AgglomerativeClustering
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher from redis_publisher import RedisPublisher
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
UUID = os.getenv("UUID", "quick_preview") UUID = os.getenv("UUID", "quick_preview")
OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output") OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output")
OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.face_clustered.json") OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.face_clustered.json")
@@ -616,7 +627,7 @@ def main():
output_data["speaker_person_mapping"] = speaker_mapping output_data["speaker_person_mapping"] = speaker_mapping
with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f: with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False) json.dump(round_json_numbers(output_data), f, indent=2, ensure_ascii=False)
print(f"Saved clustered data to {OUTPUT_JSON_PATH}") print(f"Saved clustered data to {OUTPUT_JSON_PATH}")
publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters") publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters")
+16 -2
View File
@@ -52,6 +52,20 @@ def classify_pose(roll: float, yaw: float) -> str:
return "three_quarter" return "three_quarter"
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only).
Intentionally leaves Qdrant push payloads untouched (they use raw values).
"""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
class FaceProcessorVision: class FaceProcessorVision:
def __init__(self, video_path: str, output_path: str, uuid: str = "", def __init__(self, video_path: str, output_path: str, uuid: str = "",
sample_interval: int = 3, publisher: RedisPublisher = None): sample_interval: int = 3, publisher: RedisPublisher = None):
@@ -329,13 +343,13 @@ class FaceProcessorVision:
output = { output = {
"status": status, "status": status,
"frame_count": len(frames_list), "frame_count": len(frames_list),
"fps": self.fps, "fps": round(self.fps, 2),
"frames": frames_list, "frames": frames_list,
"total_faces": total_faces, "total_faces": total_faces,
} }
with open(self.output_path, "w") as f: with open(self.output_path, "w") as f:
json.dump(output, f, indent=2, ensure_ascii=False) json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False)
# Push embeddings to Qdrant _faces collection # Push embeddings to Qdrant _faces collection
if all_embeddings: if all_embeddings:
+12 -1
View File
@@ -27,6 +27,17 @@ SWIFT_OCR_ALT = os.path.join(
SWIFT_PROGRESS_RE = re.compile(r"\[SwiftOCR\] Progress:\s*(\d+)%") SWIFT_PROGRESS_RE = re.compile(r"\[SwiftOCR\] Progress:\s*(\d+)%")
def _round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: _round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_round_json_numbers(v) for v in obj]
return obj
def process_ocr( def process_ocr(
video_path: str, video_path: str,
output_path: str, output_path: str,
@@ -121,7 +132,7 @@ if __name__ == "__main__":
publisher) publisher)
with open(args.output_path, "w") as f: with open(args.output_path, "w") as f:
json.dump(result, f, indent=2) json.dump(_round_json_numbers(result), f, indent=2)
print(f"OCR: {len(result.get('frames', []))} frames with text") print(f"OCR: {len(result.get('frames', []))} frames with text")
if publisher: if publisher:
publisher.complete("ocr", f"{len(result.get('frames',[]))} frames") publisher.complete("ocr", f"{len(result.get('frames',[]))} frames")
+13 -3
View File
@@ -27,6 +27,16 @@ SWIFT_POSE_ALT = os.path.join(
SWIFT_POSE_PROGRESS_RE = re.compile(r"\[SwiftPose\] Progress:\s*(\d+)%") SWIFT_POSE_PROGRESS_RE = re.compile(r"\[SwiftPose\] Progress:\s*(\d+)%")
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
def process_pose( def process_pose(
video_path: str, video_path: str,
output_path: str, output_path: str,
@@ -67,7 +77,7 @@ def process_pose(
# Write interpolated output # Write interpolated output
with open(output_path, 'w') as f: with open(output_path, 'w') as f:
json.dump(interpolated_data, f) json.dump(round_json_numbers(interpolated_data), f)
# Delete .json.tmp file so executor.rs won't restore it # Delete .json.tmp file so executor.rs won't restore it
if os.path.exists(tmp_path): if os.path.exists(tmp_path):
@@ -294,7 +304,7 @@ def _fallback(video_path, output_path, uuid, sample_interval):
if len(frames) == 0: if len(frames) == 0:
result["status"] = "no_face" result["status"] = "no_face"
with open(output_path, "w") as f: with open(output_path, "w") as f:
json.dump(result, f, indent=2) json.dump(round_json_numbers(result), f, indent=2)
return result return result
@@ -320,7 +330,7 @@ if __name__ == "__main__":
result = process_pose(args.video_path, args.output_path, args.uuid, result = process_pose(args.video_path, args.output_path, args.uuid,
args.sample_interval, publisher, target_frames) args.sample_interval, publisher, target_frames)
with open(args.output_path, "w") as f: with open(args.output_path, "w") as f:
json.dump(result, f, indent=2) json.dump(round_json_numbers(result), f, indent=2)
print(f"Pose: {len(result.get('frames', []))} frames with poses") print(f"Pose: {len(result.get('frames', []))} frames with poses")
if publisher: if publisher:
publisher.complete("pose", f"{len(result.get('frames',[]))} frames") publisher.complete("pose", f"{len(result.get('frames',[]))} frames")
@@ -2,6 +2,13 @@
""" """
Select Face Reference Vectors V3 - With Trace Support Select Face Reference Vectors V3 - With Trace Support
⚠️ DEPRECATED / NOT FUNCTIONAL ⚠️
The `--face-json video.face_traced.json` path relied on embeddings stored in
face_traced.json. That file no longer contains embeddings (they live in the Qdrant
`_faces` collection only). If you need face embeddings, load them from Qdrant via
`qdrant_faces.get_file_faces(file_uuid, with_vector=True)` and build the face list
from there. Kept for reference only.
Purpose: Purpose:
1. Select reference vectors from specific trace_id (same person) 1. Select reference vectors from specific trace_id (same person)
2. Ensure multi-angle coverage within trace 2. Ensure multi-angle coverage within trace
+22 -1
View File
@@ -32,6 +32,27 @@ OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/outp
SCHEMA = os.environ.get("DATABASE_SCHEMA", "public") SCHEMA = os.environ.get("DATABASE_SCHEMA", "public")
def strip_embeddings_and_round(obj):
"""Remove face embeddings from face_traced.json and round floats to 2 dp.
Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the
file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded
from Qdrant before tracking), so stripping at write time is safe: all downstream
consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead.
"""
if isinstance(obj, dict):
return {
k: strip_embeddings_and_round(v)
for k, v in obj.items()
if not (k == "embedding")
}
if isinstance(obj, list):
return [strip_embeddings_and_round(v) for v in obj]
if isinstance(obj, float):
return round(obj, 2)
return obj
def merge_traces_within_cuts(face_data: dict, cut_scenes: list) -> dict: def merge_traces_within_cuts(face_data: dict, cut_scenes: list) -> dict:
"""Merge traces within the same cut - DISABLED (no embeddings).""" """Merge traces within the same cut - DISABLED (no embeddings)."""
# TODO: Reimplement with Qdrant _faces collection # TODO: Reimplement with Qdrant _faces collection
@@ -160,7 +181,7 @@ def run_face_tracker(
face_data["metadata"] = metadata face_data["metadata"] = metadata
with open(traced_json_path, "w") as f: with open(traced_json_path, "w") as f:
json.dump(face_data, f, indent=2, ensure_ascii=False) json.dump(strip_embeddings_and_round(face_data), f, indent=2, ensure_ascii=False)
trace_count = len(face_data.get("traces", {})) trace_count = len(face_data.get("traces", {}))
print(f"[TRACE] Completed: {trace_count} traces -> {traced_json_path}") print(f"[TRACE] Completed: {trace_count} traces -> {traced_json_path}")
+2 -2
View File
@@ -129,7 +129,7 @@ struct SwiftOCR: ParsableCommand {
"y": Int((1.0 - bb.origin.y - bb.size.height) * CGFloat(cgH)), "y": Int((1.0 - bb.origin.y - bb.size.height) * CGFloat(cgH)),
"width": Int(bb.size.width * CGFloat(cgW)), "width": Int(bb.size.width * CGFloat(cgW)),
"height": Int(bb.size.height * CGFloat(cgH)), "height": Int(bb.size.height * CGFloat(cgH)),
"confidence": conf "confidence": Double(round(conf * 100)) / 100
] ]
texts.append(item) texts.append(item)
} }
@@ -137,7 +137,7 @@ struct SwiftOCR: ParsableCommand {
if !texts.isEmpty { if !texts.isEmpty {
ocrFrames.append([ ocrFrames.append([
"frame": frameNumber, "frame": frameNumber,
"timestamp": timestamp, "timestamp": Double(round(timestamp * 100)) / 100,
"texts": texts "texts": texts
]) ])
} }
+5 -5
View File
@@ -155,9 +155,9 @@ struct SwiftPose: ParsableCommand {
let py = CGFloat(h) - point.location.y * CGFloat(h) let py = CGFloat(h) - point.location.y * CGFloat(h)
keypoints.append([ keypoints.append([
"name": rawName.isEmpty ? "\(joint)" : rawName, "name": rawName.isEmpty ? "\(joint)" : rawName,
"x": px, "x": Double(round(px * 100)) / 100,
"y": py, "y": Double(round(py * 100)) / 100,
"confidence": point.confidence, "confidence": Double(round(point.confidence * 100)) / 100,
]) ])
if point.confidence > 0.1 { if point.confidence > 0.1 {
minX = min(minX, px) minX = min(minX, px)
@@ -186,7 +186,7 @@ struct SwiftPose: ParsableCommand {
if !persons.isEmpty { if !persons.isEmpty {
poseFrames.append([ poseFrames.append([
"frame": frameNum, "frame": frameNum,
"timestamp": timestamp, "timestamp": Double(round(timestamp * 100)) / 100,
"persons": persons, "persons": persons,
]) ])
} }
@@ -201,7 +201,7 @@ struct SwiftPose: ParsableCommand {
// Write output // Write output
let outputDict: [String: Any] = [ let outputDict: [String: Any] = [
"frame_count": poseFrames.count, "frame_count": poseFrames.count,
"fps": fps, "fps": Double(round(fps * 100)) / 100,
"frames": poseFrames, "frames": poseFrames,
] ]
if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) { if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) {
+9 -1
View File
@@ -1,5 +1,13 @@
#!/opt/homebrew/bin/python3.11 #!/opt/homebrew/bin/python3.11
"""Update face_detections embeddings from face_traced.json""" """Update face_detections embeddings from face_traced.json
⚠️ DEPRECATED / NOT FUNCTIONAL ⚠️
face_traced.json no longer contains the `embedding` field (embeddings live in the
Qdrant `_faces` collection only). This script reads embeddings from face_traced.json,
so it will find none. If you need to (re)populate embeddings, read them from Qdrant
`_faces` via `qdrant_faces.get_file_faces(file_uuid, with_vector=True)` instead.
Kept for reference only.
"""
import json import json
import psycopg2 import psycopg2
+22 -1
View File
@@ -28,6 +28,27 @@ Output:
import json import json
import argparse import argparse
import numpy as np import numpy as np
def strip_embeddings_and_round(obj):
"""Remove face embeddings from face_traced.json and round floats to 2 dp.
Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the
file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded
from Qdrant before tracking), so stripping at write time is safe: all downstream
consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead.
"""
if isinstance(obj, dict):
return {
k: strip_embeddings_and_round(v)
for k, v in obj.items()
if not (k == "embedding")
}
if isinstance(obj, list):
return [strip_embeddings_and_round(v) for v in obj]
if isinstance(obj, float):
return round(obj, 2)
return obj
from typing import Dict, List, Set from typing import Dict, List, Set
from collections import defaultdict from collections import defaultdict
@@ -544,7 +565,7 @@ def main():
if not args.analyze_only: if not args.analyze_only:
output_path = args.output or args.face_json.replace(".json", "_traced.json") output_path = args.output or args.face_json.replace(".json", "_traced.json")
with open(output_path, "w") as f: with open(output_path, "w") as f:
json.dump(face_data, f, indent=2) json.dump(strip_embeddings_and_round(face_data), f, indent=2)
print(f"\n✅ Output saved to: {output_path}") print(f"\n✅ Output saved to: {output_path}")
+27 -1
View File
@@ -401,6 +401,30 @@ pub struct FaceTraceProfile {
pub status: String, // pending / bound / merged pub status: String, // pending / bound / merged
} }
/// Recursively round all float numbers in a JSON value to 2 decimal places.
/// Used for trace_profile.json output only; in-memory values are preserved.
pub(crate) fn round_json_value(v: &serde_json::Value) -> serde_json::Value {
match v {
serde_json::Value::Number(n) => {
if let Some(f) = n.as_f64() {
let rounded = (f * 100.0).round() / 100.0;
serde_json::Value::from(rounded)
} else {
v.clone()
}
}
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.iter().map(round_json_value).collect())
}
serde_json::Value::Object(map) => serde_json::Value::Object(
map.iter()
.map(|(k, val)| (k.clone(), round_json_value(val)))
.collect(),
),
_ => v.clone(),
}
}
impl FaceTraceProfile { impl FaceTraceProfile {
/// Directory: `output/{file_uuid}/{trace_id}/` /// Directory: `output/{file_uuid}/{trace_id}/`
pub fn trace_dir(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf { pub fn trace_dir(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf {
@@ -488,7 +512,8 @@ impl FaceTraceProfile {
// Write trace_profile.json // Write trace_profile.json
let json = let json =
serde_json::to_string_pretty(self).context("Failed to serialize FaceTraceProfile")?; serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?))
.context("Failed to serialize FaceTraceProfile")?;
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id); let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
std::fs::write(&profile_path, json) std::fs::write(&profile_path, json)
.with_context(|| format!("Failed to write {}", profile_path.display()))?; .with_context(|| format!("Failed to write {}", profile_path.display()))?;
@@ -636,6 +661,7 @@ mod tests {
profile.face_filter = Some(FaceFilterSettings { profile.face_filter = Some(FaceFilterSettings {
min_confidence: 85.0, min_confidence: 85.0,
min_size: 96, min_size: 96,
min_capture_quality: 0.0,
}); });
let json = serde_json::to_string(&profile).unwrap(); let json = serde_json::to_string(&profile).unwrap();
let restored: FileProfile = serde_json::from_str(&json).unwrap(); let restored: FileProfile = serde_json::from_str(&json).unwrap();
+20 -5
View File
@@ -10,6 +10,7 @@ const CUT_TIMEOUT: Duration = Duration::from_secs(3600);
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CutResult { pub struct CutResult {
pub frame_count: u64, pub frame_count: u64,
#[serde(serialize_with = "round_two")]
pub fps: f64, pub fps: f64,
pub scenes: Vec<CutScene>, pub scenes: Vec<CutScene>,
} }
@@ -19,10 +20,21 @@ pub struct CutScene {
pub scene_number: u32, pub scene_number: u32,
pub start_frame: u64, pub start_frame: u64,
pub end_frame: u64, pub end_frame: u64,
#[serde(serialize_with = "round_two")]
pub start_time: f64, pub start_time: f64,
#[serde(serialize_with = "round_two")]
pub end_time: f64, pub end_time: f64,
} }
/// Serialize an f64 rounded to 2 decimal places (JSON output only).
/// In-memory values are preserved; only the serialized form is rounded.
fn round_two<S>(v: &f64, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_f64((v * 100.0).round() / 100.0)
}
pub async fn process_cut( pub async fn process_cut(
video_path: &str, video_path: &str,
output_path: &str, output_path: &str,
@@ -157,8 +169,11 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
// Step 3: Build scenes from cut points // Step 3: Build scenes from cut points
let mut scenes: Vec<CutScene> = Vec::new(); let mut scenes: Vec<CutScene> = Vec::new();
let round_time = |t: f64| (t * 1000.0).round() / 1000.0;
let mut prev_time = 0.0; let mut prev_time = 0.0;
let mut prev_frame: u64 = 0; let mut prev_frame: u64 = 0;
let round_time = |t: f64| (t * 1000.0).round() / 1000.0;
for (i, &cut_time) in scene_times.iter().enumerate() { for (i, &cut_time) in scene_times.iter().enumerate() {
let end_frame = (cut_time * fps).round() as u64; let end_frame = (cut_time * fps).round() as u64;
@@ -169,8 +184,8 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
scene_number: (i + 1) as u32, scene_number: (i + 1) as u32,
start_frame: prev_frame, start_frame: prev_frame,
end_frame: end_frame.saturating_sub(1), end_frame: end_frame.saturating_sub(1),
start_time: prev_time, start_time: round_time(prev_time),
end_time: cut_time - (1.0 / fps), end_time: round_time(cut_time - (1.0 / fps)),
}); });
} }
@@ -184,8 +199,8 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
scene_number: (scenes.len() + 1) as u32, scene_number: (scenes.len() + 1) as u32,
start_frame: prev_frame, start_frame: prev_frame,
end_frame: total_frames.saturating_sub(1), end_frame: total_frames.saturating_sub(1),
start_time: prev_time, start_time: round_time(prev_time),
end_time: duration, end_time: round_time(duration),
}); });
} }
@@ -196,7 +211,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
start_frame: 0, start_frame: 0,
end_frame: total_frames.saturating_sub(1), end_frame: total_frames.saturating_sub(1),
start_time: 0.0, start_time: 0.0,
end_time: duration, end_time: round_time(duration),
}); });
} }
+5 -1
View File
@@ -1564,7 +1564,11 @@ async fn build_face_track_nodes_from_qdrant(
if kface_path.exists() { if kface_path.exists() {
trace_profile.key_face = Some("key_face.jpg".to_string()); trace_profile.key_face = Some("key_face.jpg".to_string());
} }
if let Ok(json) = serde_json::to_string_pretty(&trace_profile) { if let Ok(json) = serde_json::to_string_pretty(
&crate::core::file_profile::round_json_value(
&serde_json::to_value(&trace_profile).unwrap_or_default(),
),
) {
let _ = std::fs::write(&tp_path, json); let _ = std::fs::write(&tp_path, json);
if tp_path.exists() { if tp_path.exists() {
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid); tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);