feat: round output JSON floats to 2dp + unify ensure_ascii for asr/asrx
This commit is contained in:
+33
-10
@@ -18,6 +18,7 @@ Configuration:
|
||||
import sys
|
||||
import json
|
||||
import os
|
||||
import math
|
||||
import time
|
||||
import argparse
|
||||
import signal
|
||||
@@ -28,6 +29,28 @@ from faster_whisper import WhisperModel
|
||||
PROCESSOR_VERSION = "2.1"
|
||||
MODEL_SIZE = "small"
|
||||
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"
|
||||
|
||||
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": []
|
||||
}
|
||||
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:
|
||||
publisher.complete("asr", "0 segments (no audio)")
|
||||
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
|
||||
scene_idx = find_scene_idx((seg_start + seg_end) / 2)
|
||||
scene_segments.append({
|
||||
"start_time": seg_start,
|
||||
"end_time": seg_end,
|
||||
"start_time": round(seg_start, 2),
|
||||
"end_time": round(seg_end, 2),
|
||||
"start_frame": int(round(seg_start * fps)),
|
||||
"end_frame": int(round(seg_end * fps)),
|
||||
"text": segment.text.strip(),
|
||||
"scene_number": scene_idx + 1,
|
||||
"language": seg_language,
|
||||
"confidence": getattr(segment, "confidence", 0.0),
|
||||
"confidence": round(segment_confidence(segment), 2),
|
||||
})
|
||||
total_segments += 1
|
||||
|
||||
# 當前 scene 結果寫入 .asr.tmp
|
||||
all_segments.extend(scene_segments)
|
||||
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 publisher:
|
||||
@@ -387,7 +410,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
|
||||
|
||||
# Write final output with status
|
||||
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:
|
||||
# 無 CUT 資料,直接轉錄(原有流程)
|
||||
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 = []
|
||||
for segment in segments:
|
||||
all_segments.append({
|
||||
"start_time": segment.start,
|
||||
"end_time": segment.end,
|
||||
"start_time": round(segment.start, 2),
|
||||
"end_time": round(segment.end, 2),
|
||||
"start_frame": int(round(segment.start * fps)),
|
||||
"end_frame": int(round(segment.end * fps)),
|
||||
"text": segment.text.strip(),
|
||||
"confidence": getattr(segment, "confidence", 0.0),
|
||||
"confidence": round(segment_confidence(segment), 2),
|
||||
})
|
||||
total_segments += 1
|
||||
if total_segments % 100 == 0:
|
||||
@@ -416,7 +439,7 @@ def run_asr(video_path, output_path, uuid: str = "", fps: float = None):
|
||||
status = "silent_audio"
|
||||
|
||||
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:
|
||||
publisher.info("asr", f"ASR_LANGUAGE:{info_language}")
|
||||
|
||||
@@ -87,10 +87,21 @@ def _cleanup(tmp_dir):
|
||||
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):
|
||||
tmp = path + ".tmp"
|
||||
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)
|
||||
|
||||
|
||||
|
||||
@@ -21,6 +21,17 @@ from urllib.request import Request, urlopen
|
||||
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):
|
||||
"""載入音頻文件,回傳 (wav_numpy, sample_rate)"""
|
||||
import soundfile as sf
|
||||
@@ -115,7 +126,7 @@ def _save_checkpoint(path: str, data: dict):
|
||||
tmp = path + ".tmp"
|
||||
Path(tmp).parent.mkdir(parents=True, exist_ok=True)
|
||||
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)
|
||||
|
||||
|
||||
@@ -408,7 +419,7 @@ class SelfASRXFixed:
|
||||
if output_path:
|
||||
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
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] Done! {len(segments)} segments, "
|
||||
@@ -541,7 +552,7 @@ class SelfASRXFixed:
|
||||
if output_path:
|
||||
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
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] Done! {len(segments)} segments, "
|
||||
|
||||
@@ -29,6 +29,17 @@ FACES_COLLECTION = "_faces"
|
||||
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):
|
||||
"""Scroll Qdrant collection with filter."""
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
@@ -205,8 +205,8 @@ def rebuild_scenes(
|
||||
"scene_number": len(scenes) + 1,
|
||||
"start_frame": prev_frame,
|
||||
"end_frame": end_frame - 1,
|
||||
"start_time": prev_time,
|
||||
"end_time": t - (1.0 / fps) if fps > 0 else t,
|
||||
"start_time": round(prev_time, 2),
|
||||
"end_time": round(t - (1.0 / fps) if fps > 0 else t, 2),
|
||||
}
|
||||
)
|
||||
prev_time = t
|
||||
@@ -220,8 +220,8 @@ def rebuild_scenes(
|
||||
"scene_number": len(scenes) + 1,
|
||||
"start_frame": prev_frame,
|
||||
"end_frame": last_frame - 1,
|
||||
"start_time": prev_time,
|
||||
"end_time": duration,
|
||||
"start_time": round(prev_time, 2),
|
||||
"end_time": round(duration, 2),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -265,7 +265,7 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""):
|
||||
"start_frame": 0,
|
||||
"end_frame": total_frames - 1,
|
||||
"start_time": 0.0,
|
||||
"end_time": duration,
|
||||
"end_time": round(duration, 2),
|
||||
}
|
||||
]
|
||||
if publisher:
|
||||
@@ -275,7 +275,7 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""):
|
||||
|
||||
result = {
|
||||
"frame_count": total_frames,
|
||||
"fps": fps,
|
||||
"fps": round(fps, 2),
|
||||
"scenes": scenes,
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,17 @@ from sklearn.cluster import AgglomerativeClustering
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
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")
|
||||
OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output")
|
||||
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
|
||||
|
||||
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}")
|
||||
publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters")
|
||||
|
||||
|
||||
@@ -52,6 +52,20 @@ def classify_pose(roll: float, yaw: float) -> str:
|
||||
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:
|
||||
def __init__(self, video_path: str, output_path: str, uuid: str = "",
|
||||
sample_interval: int = 3, publisher: RedisPublisher = None):
|
||||
@@ -329,13 +343,13 @@ class FaceProcessorVision:
|
||||
output = {
|
||||
"status": status,
|
||||
"frame_count": len(frames_list),
|
||||
"fps": self.fps,
|
||||
"fps": round(self.fps, 2),
|
||||
"frames": frames_list,
|
||||
"total_faces": total_faces,
|
||||
}
|
||||
|
||||
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
|
||||
if all_embeddings:
|
||||
|
||||
@@ -27,6 +27,17 @@ SWIFT_OCR_ALT = os.path.join(
|
||||
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(
|
||||
video_path: str,
|
||||
output_path: str,
|
||||
@@ -121,7 +132,7 @@ if __name__ == "__main__":
|
||||
publisher)
|
||||
|
||||
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")
|
||||
if publisher:
|
||||
publisher.complete("ocr", f"{len(result.get('frames',[]))} frames")
|
||||
|
||||
@@ -27,6 +27,16 @@ SWIFT_POSE_ALT = os.path.join(
|
||||
|
||||
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(
|
||||
video_path: str,
|
||||
output_path: str,
|
||||
@@ -67,7 +77,7 @@ def process_pose(
|
||||
|
||||
# Write interpolated output
|
||||
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
|
||||
if os.path.exists(tmp_path):
|
||||
@@ -294,7 +304,7 @@ def _fallback(video_path, output_path, uuid, sample_interval):
|
||||
if len(frames) == 0:
|
||||
result["status"] = "no_face"
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(result, f, indent=2)
|
||||
json.dump(round_json_numbers(result), f, indent=2)
|
||||
return result
|
||||
|
||||
|
||||
@@ -320,7 +330,7 @@ if __name__ == "__main__":
|
||||
result = process_pose(args.video_path, args.output_path, args.uuid,
|
||||
args.sample_interval, publisher, target_frames)
|
||||
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")
|
||||
if publisher:
|
||||
publisher.complete("pose", f"{len(result.get('frames',[]))} frames")
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
"""
|
||||
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:
|
||||
1. Select reference vectors from specific trace_id (same person)
|
||||
2. Ensure multi-angle coverage within trace
|
||||
|
||||
@@ -32,6 +32,27 @@ OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/outp
|
||||
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:
|
||||
"""Merge traces within the same cut - DISABLED (no embeddings)."""
|
||||
# TODO: Reimplement with Qdrant _faces collection
|
||||
@@ -160,7 +181,7 @@ def run_face_tracker(
|
||||
face_data["metadata"] = metadata
|
||||
|
||||
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", {}))
|
||||
print(f"[TRACE] Completed: {trace_count} traces -> {traced_json_path}")
|
||||
|
||||
@@ -129,7 +129,7 @@ struct SwiftOCR: ParsableCommand {
|
||||
"y": Int((1.0 - bb.origin.y - bb.size.height) * CGFloat(cgH)),
|
||||
"width": Int(bb.size.width * CGFloat(cgW)),
|
||||
"height": Int(bb.size.height * CGFloat(cgH)),
|
||||
"confidence": conf
|
||||
"confidence": Double(round(conf * 100)) / 100
|
||||
]
|
||||
texts.append(item)
|
||||
}
|
||||
@@ -137,7 +137,7 @@ struct SwiftOCR: ParsableCommand {
|
||||
if !texts.isEmpty {
|
||||
ocrFrames.append([
|
||||
"frame": frameNumber,
|
||||
"timestamp": timestamp,
|
||||
"timestamp": Double(round(timestamp * 100)) / 100,
|
||||
"texts": texts
|
||||
])
|
||||
}
|
||||
|
||||
@@ -155,9 +155,9 @@ struct SwiftPose: ParsableCommand {
|
||||
let py = CGFloat(h) - point.location.y * CGFloat(h)
|
||||
keypoints.append([
|
||||
"name": rawName.isEmpty ? "\(joint)" : rawName,
|
||||
"x": px,
|
||||
"y": py,
|
||||
"confidence": point.confidence,
|
||||
"x": Double(round(px * 100)) / 100,
|
||||
"y": Double(round(py * 100)) / 100,
|
||||
"confidence": Double(round(point.confidence * 100)) / 100,
|
||||
])
|
||||
if point.confidence > 0.1 {
|
||||
minX = min(minX, px)
|
||||
@@ -186,7 +186,7 @@ struct SwiftPose: ParsableCommand {
|
||||
if !persons.isEmpty {
|
||||
poseFrames.append([
|
||||
"frame": frameNum,
|
||||
"timestamp": timestamp,
|
||||
"timestamp": Double(round(timestamp * 100)) / 100,
|
||||
"persons": persons,
|
||||
])
|
||||
}
|
||||
@@ -201,7 +201,7 @@ struct SwiftPose: ParsableCommand {
|
||||
// Write output
|
||||
let outputDict: [String: Any] = [
|
||||
"frame_count": poseFrames.count,
|
||||
"fps": fps,
|
||||
"fps": Double(round(fps * 100)) / 100,
|
||||
"frames": poseFrames,
|
||||
]
|
||||
if let jsonData = try? JSONSerialization.data(withJSONObject: outputDict, options: [.prettyPrinted]) {
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
#!/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 psycopg2
|
||||
|
||||
@@ -28,6 +28,27 @@ Output:
|
||||
import json
|
||||
import argparse
|
||||
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 collections import defaultdict
|
||||
|
||||
@@ -544,7 +565,7 @@ def main():
|
||||
if not args.analyze_only:
|
||||
output_path = args.output or args.face_json.replace(".json", "_traced.json")
|
||||
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}")
|
||||
|
||||
|
||||
|
||||
@@ -401,6 +401,30 @@ pub struct FaceTraceProfile {
|
||||
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 {
|
||||
/// Directory: `output/{file_uuid}/{trace_id}/`
|
||||
pub fn trace_dir(output_dir: &str, file_uuid: &str, trace_id: i64) -> PathBuf {
|
||||
@@ -488,7 +512,8 @@ impl FaceTraceProfile {
|
||||
|
||||
// Write trace_profile.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);
|
||||
std::fs::write(&profile_path, json)
|
||||
.with_context(|| format!("Failed to write {}", profile_path.display()))?;
|
||||
@@ -636,6 +661,7 @@ mod tests {
|
||||
profile.face_filter = Some(FaceFilterSettings {
|
||||
min_confidence: 85.0,
|
||||
min_size: 96,
|
||||
min_capture_quality: 0.0,
|
||||
});
|
||||
let json = serde_json::to_string(&profile).unwrap();
|
||||
let restored: FileProfile = serde_json::from_str(&json).unwrap();
|
||||
|
||||
@@ -10,6 +10,7 @@ const CUT_TIMEOUT: Duration = Duration::from_secs(3600);
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct CutResult {
|
||||
pub frame_count: u64,
|
||||
#[serde(serialize_with = "round_two")]
|
||||
pub fps: f64,
|
||||
pub scenes: Vec<CutScene>,
|
||||
}
|
||||
@@ -19,10 +20,21 @@ pub struct CutScene {
|
||||
pub scene_number: u32,
|
||||
pub start_frame: u64,
|
||||
pub end_frame: u64,
|
||||
#[serde(serialize_with = "round_two")]
|
||||
pub start_time: f64,
|
||||
#[serde(serialize_with = "round_two")]
|
||||
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(
|
||||
video_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
|
||||
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_frame: u64 = 0;
|
||||
let round_time = |t: f64| (t * 1000.0).round() / 1000.0;
|
||||
|
||||
for (i, &cut_time) in scene_times.iter().enumerate() {
|
||||
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,
|
||||
start_frame: prev_frame,
|
||||
end_frame: end_frame.saturating_sub(1),
|
||||
start_time: prev_time,
|
||||
end_time: cut_time - (1.0 / fps),
|
||||
start_time: round_time(prev_time),
|
||||
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,
|
||||
start_frame: prev_frame,
|
||||
end_frame: total_frames.saturating_sub(1),
|
||||
start_time: prev_time,
|
||||
end_time: duration,
|
||||
start_time: round_time(prev_time),
|
||||
end_time: round_time(duration),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -196,7 +211,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
|
||||
start_frame: 0,
|
||||
end_frame: total_frames.saturating_sub(1),
|
||||
start_time: 0.0,
|
||||
end_time: duration,
|
||||
end_time: round_time(duration),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1564,7 +1564,11 @@ async fn build_face_track_nodes_from_qdrant(
|
||||
if kface_path.exists() {
|
||||
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);
|
||||
if tp_path.exists() {
|
||||
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
|
||||
|
||||
Reference in New Issue
Block a user