File size: 5,793 Bytes
a9de05b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | #!/usr/bin/env python3
"""
measure_efficiency.py — Profile the heuristic section detection
===============================================================
Measures:
- Execution time (wall-clock time)
- Memory usage
- Section count and distribution
- Quality metrics (section balance, boundary placement)
"""
import json
import os
import sys
import time
from pathlib import Path
# Try to import psutil; fallback to basic memory tracking
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
# Add script directory to path
sys.path.insert(0, str(Path(__file__).parent))
from agent0_sectioner import run_sectioning
from transcript_parser import parse_transcript
def get_memory_usage() -> dict:
"""Get current memory usage in MB."""
if HAS_PSUTIL:
process = psutil.Process(os.getpid())
mem_info = process.memory_info()
return {
"rss_mb": mem_info.rss / 1024 / 1024, # Resident set size
"vms_mb": mem_info.vms / 1024 / 1024, # Virtual memory size
}
else:
return {"rss_mb": 0, "vms_mb": 0} # Not available without psutil
def profile_sectioning(turns: list[dict], session_id: str) -> dict:
"""Profile run_sectioning() with timing and memory metrics."""
print(f"\n{'='*60}")
print(f"Profiling heuristic section detection")
print(f"{'='*60}")
print(f"Input: {len(turns)} turns")
# Baseline memory
mem_before = get_memory_usage()
print(f"Memory before: {mem_before['rss_mb']:.1f} MB")
# Time the sectioning
start_time = time.time()
try:
result = run_sectioning(turns, session_id)
elapsed = time.time() - start_time
success = True
except Exception as e:
elapsed = time.time() - start_time
success = False
result = {"error": str(e)}
# Memory after
mem_after = get_memory_usage()
mem_delta = mem_after['rss_mb'] - mem_before['rss_mb']
# Statistics
sections = result.get("sections", [])
turn_counts = [s["end_turn_id"] - s["start_turn_id"] + 1 for s in sections]
stats = {
"success": success,
"elapsed_seconds": round(elapsed, 3),
"memory_before_mb": round(mem_before['rss_mb'], 1),
"memory_after_mb": round(mem_after['rss_mb'], 1),
"memory_delta_mb": round(mem_delta, 1),
"input_turns": len(turns),
"output_sections": len(sections),
"turns_per_section": {
"mean": round(sum(turn_counts) / len(turn_counts), 1) if turn_counts else 0,
"min": min(turn_counts) if turn_counts else 0,
"max": max(turn_counts) if turn_counts else 0,
"stddev": round(
(sum((x - (sum(turn_counts) / len(turn_counts)))**2 for x in turn_counts) / len(turn_counts))**0.5,
1
) if turn_counts else 0,
},
"section_labels": [s["label"] for s in sections],
"warnings": result.get("warnings", []),
}
# Print report
print(f"\nResults:")
print(f" ✓ Execution time: {stats['elapsed_seconds']} seconds")
print(f" ✓ Memory used: {stats['memory_delta_mb']:+.1f} MB")
print(f" ✓ Sections detected: {stats['output_sections']}")
if turn_counts:
print(f"\nSection distribution:")
print(f" - Turns per section: {stats['turns_per_section']['mean']} ± {stats['turns_per_section']['stddev']}")
print(f" - Range: {stats['turns_per_section']['min']}–{stats['turns_per_section']['max']}")
if stats['warnings']:
print(f"\n⚠ Warnings: {stats['warnings']}")
print(f"\nSection labels detected:")
for i, label in enumerate(stats['section_labels'], 1):
print(f" s{i:02d}: {label}")
return stats
def main():
"""Load sample transcript and profile sectioning."""
# Find sample transcripts
script_dir = Path(__file__).parent
sample_files = [
script_dir / "meeting_saved_closed_caption.txt",
script_dir / "meeting_saved_closed_caption-groupchat1647.txt",
]
sample_file = None
for f in sample_files:
if f.exists():
sample_file = f
break
if not sample_file:
print(f"ERROR: No sample transcript found in {script_dir}")
print(f"Expected one of:")
for f in sample_files:
print(f" - {f.name}")
sys.exit(1)
print(f"Loading transcript: {sample_file.name}")
# Parse transcript
text = sample_file.read_text(encoding='utf-8')
turns = parse_transcript(text)
print(f"Parsed {len(turns)} turns")
if not turns:
print("ERROR: No turns parsed from transcript")
sys.exit(1)
# Enable local sectioning
os.environ["LOCAL_SECTIONING"] = "1"
# Run profile
stats = profile_sectioning(turns, "local_test_001")
# Save results
results_file = script_dir / "profile_results.json"
results_file.write_text(json.dumps(stats, indent=2), encoding='utf-8')
print(f"\n✓ Results saved to {results_file.name}")
# Success/failure
if stats['success']:
print(f"\n{'='*60}")
print(f"✓ Heuristic sectioning PASSED")
print(f" Processed {stats['input_turns']} turns into {stats['output_sections']} sections")
print(f" in {stats['elapsed_seconds']}s ({stats['input_turns']/stats['elapsed_seconds']:.0f} turns/sec)")
print(f"{'='*60}\n")
return 0
else:
print(f"\n{'='*60}")
print(f"✗ Heuristic sectioning FAILED")
print(f" Error: {stats.get('error')}")
print(f"{'='*60}\n")
return 1
if __name__ == "__main__":
sys.exit(main())
|