Files
momentry_core/v1.1/scripts/refine_search_v1.11.py
Accusys 2cfcfdd1af feat: Phase 2.6 edges migration to Qdrant (TKG-only architecture)
Phase 2.6.1: co_occurrence_edges migration
- build_co_occurrence_edges_from_qdrant()
- Qdrant embeddings → frame grouping → YOLO objects
- Result: 6679 edges (vs 6701 PostgreSQL)

Phase 2.6.2: face_face_edges migration
- build_face_face_edges_from_qdrant()
- Qdrant embeddings → frame grouping → face pairs
- mutual_gaze detection preserved
- Result: 6 edges (exact match)

Phase 2.6.3: speaker_face_edges migration
- build_speaker_face_edges_from_qdrant()
- Qdrant embeddings → trace_id frame ranges
- SPEAKS_AS edge creation

Architecture:
- All edges use Qdrant payload (no face_detections queries)
- PostgreSQL fallback for empty Qdrant
- Estimated 3.6x performance improvement

Testing:
- Playground (3003): ✓ All Phase 2.6 logs verified
- Edge counts: ✓ Close match with PostgreSQL
- Fallback: ✓ Working

Docs:
- docs_v1.0/DESIGN/TKG_PHASE2_6_EDGES_MIGRATION.md
- docs_v1.0/M4_workspace/2026-06-21_phase2_6_test.md
2026-06-21 04:47:49 +08:00

137 lines
4.3 KiB
Python

#!/opt/homebrew/bin/python3.11
"""
Refined Search for "Postage Stamp" in the Image
"""
import os
import cv2
import types
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM
UUID = "384b0ff44aaaa1f1"
OUTPUT_DIR = f"output/{UUID}/florence2_results"
INPUT_IMG = os.path.join(OUTPUT_DIR, "raw_6846.jpg")
# Patch for compatibility (Required for this environment)
def patch_model(model):
inner_model = model.language_model
original_prepare = inner_model.prepare_inputs_for_generation
def patched_prepare(
self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
**kwargs,
):
is_valid_cache = False
if past_key_values is not None:
if isinstance(past_key_values, (list, tuple)) and len(past_key_values) > 0:
first_layer = past_key_values[0]
if first_layer is not None and (
not isinstance(first_layer, (list, tuple)) or len(first_layer) > 0
):
is_valid_cache = True
if not is_valid_cache:
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"past_key_values": None,
"use_cache": True,
}
else:
return original_prepare(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
**kwargs,
)
inner_model.prepare_inputs_for_generation = types.MethodType(
patched_prepare, inner_model
)
print(f"📷 Loading image from {INPUT_IMG}...")
if not os.path.exists(INPUT_IMG):
print("❌ Image not found.")
exit()
image = Image.open(INPUT_IMG).convert("RGB")
print(f"📐 Image Size: {image.width}x{image.height}")
print("🧠 Loading Florence-2 model...")
try:
processor = AutoProcessor.from_pretrained(
"microsoft/Florence-2-base", trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
"microsoft/Florence-2-base", trust_remote_code=True, attn_implementation="eager"
)
patch_model(model)
prompt = "<OPEN_VOCABULARY_DETECTION>"
# Try more specific terms
search_terms = ["postage stamp", "envelope", "letter"]
img_cv = cv2.imread(INPUT_IMG)
all_found = []
for term in search_terms:
print(f"🔍 Scanning for '{term}'...")
inputs = processor(text=prompt, images=image, return_tensors="pt")
generated_ids = model.generate(
input_ids=inputs["input_ids"],
pixel_values=inputs["pixel_values"],
max_new_tokens=1024,
num_beams=3,
)
generated_text = processor.batch_decode(
generated_ids, skip_special_tokens=False
)[0]
try:
parsed_answer = processor.post_process_generation(
generated_text, task=prompt, image_size=(image.width, image.height)
)
results = parsed_answer.get("<OPEN_VOCABULARY_DETECTION>", {})
bboxes = results.get("bboxes", [])
labels = results.get("bboxes_labels", [])
if bboxes:
print(f"✅ Found {len(bboxes)} '{term}'! Labels: {labels}")
for i, (box, label) in enumerate(zip(bboxes, labels)):
x1, y1, x2, y2 = map(int, box)
# Crop and save
crop = img_cv[y1:y2, x1:x2]
crop_path = os.path.join(
OUTPUT_DIR, f"crop_{term.replace(' ', '_')}_{i}.jpg"
)
cv2.imwrite(crop_path, crop)
print(f" 💾 Saved crop to {crop_path}")
# Also draw on main image
cv2.rectangle(img_cv, (x1, y1), (x2, y2), (0, 255, 0), 2)
all_found.append((box, label))
else:
print(f" ❌ No '{term}' found.")
except Exception as e:
print(f" ⚠️ Error processing '{term}': {e}")
final_out = os.path.join(OUTPUT_DIR, "refined_detection.jpg")
cv2.imwrite(final_out, img_cv)
print(f"\n🎨 Main image with detections saved to: {final_out}")
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()