-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterview_processor.py
More file actions
2306 lines (1914 loc) · 93.9 KB
/
interview_processor.py
File metadata and controls
2306 lines (1914 loc) · 93.9 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###########################
# Processar arquivo único
# python interview_processor.py entrevista1.txt
#
# Processar pasta inteira
# python interview_processor.py --folder interviews/
#
# Batch com créditos mínimos de $2.00
# python interview_processor.py --folder interviews/ --min-credits 2.0
#
# Batch sem verificação de créditos
# python interview_processor.py --folder interviews/ --no-credit-check
#
# Batch com pasta de saída diferente
# python interview_processor.py --folder interviews/ --output-folder output/
###########################
import anthropic
import asyncio
from tqdm import tqdm
import argparse
import logging
import sys
from typing import List, Dict, Tuple, Optional, Any
import os
import re
from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type
import nltk
import time
import toml
from collections import deque
import hashlib
import yaml
import requests
from glob import glob
from datetime import datetime
# Load configuration from config.toml
config = toml.load("config.toml")
# Configuration constants
AI_model = config["abstract_processor"]["AI_model"]
DEFAULT_API_KEY = config["abstract_processor"]["api_key"]
DEFAULT_CONCURRENCY = int(config["abstract_processor"]["concurrent"])
DEFAULT_RETRIES = int(config["abstract_processor"]["retries"])
DEFAULT_BATCH_SIZE = int(config["abstract_processor"]["batch_size"])
DEFAULT_SCAN_MODE = config["abstract_processor"].get("scan_mode", "single")
log_file = config["abstract_processor"].get("log_file", "interview_processor.log")
# Batch processing configuration
DEFAULT_INPUT_FOLDER = config["abstract_processor"].get("input_folder", "interviews")
DEFAULT_MIN_CREDITS_USD = float(config["abstract_processor"].get("min_credits_usd", 1.00))
DEFAULT_CREDITS_CHECK_ENABLED = config["abstract_processor"].get("credits_check_enabled", True)
print("Preparing data! Please, be patient...")
# Prompt base
system_prompt = config["prompts"]["system_prompt"]
# Create log directory if it doesn't exist
log_dir = os.path.dirname(log_file)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
def _configure_utf8_streams() -> None:
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
try:
stream.reconfigure(encoding="utf-8")
except Exception:
try:
stream.reconfigure(errors="backslashreplace")
except Exception:
pass
_configure_utf8_streams()
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler(log_file, encoding="utf-8"), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
# Ensure NLTK punkt data
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
logger.info("Downloading NLTK punkt data")
nltk.download('punkt')
class InterviewProcessor:
"""Handles processing of interview transcripts with enhanced text handling and prompt caching."""
SCAN_SCOPE_EXPLORATORIOS = "fatores_exploratorios"
SCAN_SCOPE_CLASSIFICATORIOS = "fatores_classificatorios"
SCAN_SCOPES = (SCAN_SCOPE_EXPLORATORIOS, SCAN_SCOPE_CLASSIFICATORIOS)
# Claude model token limits (context window)
MODEL_TOKEN_LIMITS = {
"claude-sonnet-4-5-20250929": 200000,
"claude-opus-4-20250514": 200000,
"claude-3-5-sonnet-20241022": 200000,
"claude-3-opus-20240229": 200000,
"claude-3-sonnet-20240229": 200000,
"claude-3-haiku-20240307": 200000,
}
# Minimum tokens for prompt caching (1024 tokens minimum for cache_control)
MIN_CACHE_TOKENS = 1024
# Maximum output tokens by model
MAX_OUTPUT_TOKENS = {
"claude-sonnet-4-5-20250929": 16384,
"claude-opus-4-20250514": 16384,
"claude-3-5-sonnet-20241022": 8192,
"claude-3-opus-20240229": 4096,
"claude-3-sonnet-20240229": 4096,
"claude-3-haiku-20240307": 4096,
}
# Pricing per 1M tokens (USD) - Claude Sonnet 4.5
MODEL_PRICING = {
"claude-sonnet-4-5-20250929": {"input": 3.00, "output": 15.00},
"claude-opus-4-20250514": {"input": 15.00, "output": 75.00},
"claude-3-5-sonnet-20241022": {"input": 3.00, "output": 15.00},
"claude-3-opus-20240229": {"input": 15.00, "output": 75.00},
"claude-3-sonnet-20240229": {"input": 3.00, "output": 15.00},
"claude-3-haiku-20240307": {"input": 0.25, "output": 1.25},
}
def __init__(self, api_key: str, output_file: str, max_concurrent: int, max_retries: int,
scan_mode: str = "single", min_credits_usd: float = 1.00,
credits_check_enabled: bool = True):
self.client = anthropic.Anthropic(api_key=api_key)
self.api_key = api_key
self.output_file = output_file
self.max_concurrent = max_concurrent
self.max_retries = max_retries
self.semaphore = asyncio.Semaphore(max_concurrent)
self.scan_mode = scan_mode
self.scan_scopes = self._resolve_scan_scopes(scan_mode)
# Credit control settings
self.min_credits_usd = min_credits_usd
self.credits_check_enabled = credits_check_enabled
self.total_cost_session = 0.0
self.initial_credits = None
self.files_processed = 0
self.files_failed = 0
# Use deque for efficient rate limiting (optimized for Tier 1)
self.recent_calls = deque()
self.rate_window = 60
self.max_rpm = 50 # Tier 1 allows 50 RPM
self.input_tokens_used = deque()
self.output_tokens_used = deque()
self.max_input_tokens_per_minute = 40000 # Tier 1 allows 40k input TPM
self.max_output_tokens_per_minute = 8000 # Tier 1 allows 8k output TPM
# Cache for token estimation
self._token_cache = {}
# Create static prompt parts and cache the base prompt
self.static_prompt_parts = self._create_static_prompt_parts()
self._variable_dict_text = self.static_prompt_parts.get("variable_dictionary", "")
self._variable_dict_parse_failed = False
self._variable_dict_data = self._parse_variable_dictionary_yaml(self._variable_dict_text)
self._variable_dictionary_by_scope = {
scope: self._build_variable_dictionary_subset(scope)
for scope in self.SCAN_SCOPES
}
self._cached_base_prompt = self._build_base_prompt_template()
# Prompt caching: pre-compute static content for cache_control
self._cached_system_prompt = self._build_cached_system_prompt()
self._cached_user_prefix = self._build_cached_user_prefix()
self._cached_user_prefix_by_scope = {
scope: self._build_cached_user_prefix(scope)
for scope in self.SCAN_SCOPES
}
# Token limits for the current model
self.model_token_limit = self.MODEL_TOKEN_LIMITS.get(AI_model, 200000)
self.max_output_limit = self.MAX_OUTPUT_TOKENS.get(AI_model, 8192)
# Estimate static prompt tokens once
self._static_prompt_tokens = self.estimate_tokens(
self._cached_system_prompt + self._cached_user_prefix
)
self._static_prompt_tokens_by_scope = {
scope: self.estimate_tokens(self._cached_system_prompt + prefix)
for scope, prefix in self._cached_user_prefix_by_scope.items()
}
self._static_prompt_tokens_max = max(
[self._static_prompt_tokens] + list(self._static_prompt_tokens_by_scope.values())
)
logger.info(f"Static prompt tokens (cached): {self._static_prompt_tokens}")
for scope, tokens in self._static_prompt_tokens_by_scope.items():
logger.info(f"Static prompt tokens (cached, {scope}): {tokens}")
logger.info(f"Scan mode: {self.scan_mode}")
# Buffer for batch file writes
self.output_buffer = []
self.buffer_size = 20 # Write every 20 results
output_dir = os.path.dirname(output_file)
if output_dir:
os.makedirs(output_dir, exist_ok=True)
with open(output_file, "w", encoding="utf-8") as f:
f.write("")
def _create_static_prompt_parts(self) -> Dict[str, str]:
return {
"task": config["prompts"]["task"],
"instructions": config["prompts"]["instructions"],
"variable_dictionary": config["prompts"]["variable_dictionary"],
"output_format": config["prompts"]["output_format"]
}
def get_api_credits(self) -> Tuple[bool, Optional[float], str]:
"""
Check API credits/balance using Anthropic's billing API.
Returns:
Tuple of (success, balance_usd, message)
"""
try:
# Try to get organization billing info via Admin API
# Note: This requires admin API access which may not be available
# Fallback: Make a minimal test call to verify API access
headers = {
"x-api-key": self.api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json"
}
# Attempt to get billing information (if available)
# This endpoint may not be publicly documented
try:
response = requests.get(
"https://api.anthropic.com/v1/organizations/billing",
headers=headers,
timeout=30
)
if response.status_code == 200:
data = response.json()
balance = data.get("balance", data.get("credits", None))
if balance is not None:
return True, float(balance), f"Balance: ${balance:.2f} USD"
except Exception:
pass
# Fallback: Make a minimal API test call to verify the API key works
try:
test_response = self.client.messages.create(
model=AI_model,
max_tokens=5,
messages=[{"role": "user", "content": "Hi"}]
)
# API call succeeded - we have at least some credits
input_tokens = test_response.usage.input_tokens
output_tokens = test_response.usage.output_tokens
logger.info(f"API test call successful (used {input_tokens} input, {output_tokens} output tokens)")
return True, None, "API access verified (balance not available via API)"
except anthropic.AuthenticationError as e:
return False, 0.0, f"Authentication failed: {e}"
except anthropic.RateLimitError as e:
error_msg = str(e).lower()
if "credit" in error_msg or "balance" in error_msg or "insufficient" in error_msg:
return False, 0.0, f"Insufficient credits: {e}"
# Rate limited but API key is valid
return True, None, "API key valid (rate limited)"
except anthropic.BadRequestError as e:
error_msg = str(e).lower()
if "credit" in error_msg or "balance" in error_msg:
return False, 0.0, f"Insufficient credits: {e}"
return False, None, f"API error: {e}"
except Exception as e:
logger.error(f"Error checking API credits: {e}")
return False, None, f"Error checking credits: {e}"
def estimate_processing_cost(self, transcript: str) -> float:
"""
Estimate the cost of processing a transcript.
Args:
transcript: The transcript text
Returns:
Estimated cost in USD
"""
pricing = self.MODEL_PRICING.get(AI_model, {"input": 3.00, "output": 15.00})
# Estimate input tokens
transcript_tokens = self.estimate_tokens(transcript)
static_tokens = self._static_prompt_tokens_max
total_input_tokens = static_tokens + transcript_tokens
# Estimate output tokens (conservative: assume max output)
estimated_output_tokens = min(self.max_output_limit, transcript_tokens * 0.5)
# Calculate costs (per 1M tokens)
input_cost = (total_input_tokens / 1_000_000) * pricing["input"]
output_cost = (estimated_output_tokens / 1_000_000) * pricing["output"]
# If using dual scan mode, multiply by 2
if self.scan_mode == "dual":
input_cost *= 2
output_cost *= 2
return input_cost + output_cost
def log_credit_status(self, balance: Optional[float], message: str) -> None:
"""Log credit status with timestamp."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if balance is not None:
logger.info(f"[{timestamp}] Credit Status: ${balance:.2f} USD - {message}")
else:
logger.info(f"[{timestamp}] Credit Status: {message}")
async def check_credits_before_processing(self, filename: str, transcript: str) -> Tuple[bool, str]:
"""
Check if there are sufficient credits before processing a file.
Args:
filename: Name of the file to be processed
transcript: The transcript content
Returns:
Tuple of (can_proceed, message)
"""
if not self.credits_check_enabled:
return True, "Credit checking disabled"
estimated_cost = self.estimate_processing_cost(transcript)
logger.info(f"Estimated cost for {filename}: ${estimated_cost:.4f} USD")
success, balance, message = self.get_api_credits()
if not success:
return False, message
if balance is not None:
if balance < self.min_credits_usd:
return False, f"Insufficient credits: ${balance:.2f} USD (minimum: ${self.min_credits_usd:.2f} USD)"
if balance < estimated_cost * 2: # Warning threshold
logger.warning(f"Low credit warning: ${balance:.2f} USD remaining")
return True, message
async def prompt_user_for_credits(self) -> bool:
"""
Prompt user to confirm they have purchased more credits.
Returns:
True if user confirms continuation, False otherwise
"""
print("\n" + "=" * 60)
print("CREDITS INSUFFICIENT OR LOW")
print("=" * 60)
print(f"Minimum required: ${self.min_credits_usd:.2f} USD")
print(f"Files processed so far: {self.files_processed}")
print(f"Total cost this session: ${self.total_cost_session:.4f} USD")
print("\nPlease purchase more credits at: https://console.anthropic.com/")
print("=" * 60)
while True:
response = input("\nHave you purchased more credits? Continue processing? (yes/no): ").strip().lower()
if response in ('yes', 'y', 'sim', 's'):
logger.info("User confirmed credit purchase - continuing processing")
return True
elif response in ('no', 'n', 'nao', 'não'):
logger.info("User chose to stop processing due to credits")
return False
else:
print("Please answer 'yes' or 'no'")
def _build_cached_system_prompt(self) -> str:
"""
Build the system prompt optimized for Claude's prompt caching.
The system prompt contains all static instructions and the variable dictionary.
"""
return system_prompt
def _resolve_scan_scopes(self, scan_mode: str) -> List[Optional[str]]:
"""Resolve scan scopes based on configured scan mode."""
mode = (scan_mode or "single").lower().strip()
if mode == "dual":
return [self.SCAN_SCOPE_EXPLORATORIOS, self.SCAN_SCOPE_CLASSIFICATORIOS]
if mode in ("exploratorios", self.SCAN_SCOPE_EXPLORATORIOS):
return [self.SCAN_SCOPE_EXPLORATORIOS]
if mode in ("classificatorios", self.SCAN_SCOPE_CLASSIFICATORIOS):
return [self.SCAN_SCOPE_CLASSIFICATORIOS]
return [None]
def _normalize_yaml_content(self, yaml_content: str) -> str:
"""Normalize YAML content to improve parser compatibility."""
# Remove inline comments
yaml_content = re.sub(r'//.*$', '', yaml_content, flags=re.MULTILINE)
yaml_content = re.sub(r'#.*$', '', yaml_content, flags=re.MULTILINE)
lines = []
for line in yaml_content.split('\n'):
# Convert tabs to spaces
line = line.replace('\t', ' ')
# Fix nested quotes within YAML values
if ': "' in line and line.count('"') > 2:
if line.count(': "') == 1:
key_part, value_part = line.split(': "', 1)
if value_part.count('"') >= 2:
last_quote_idx = value_part.rfind('"')
value_before_close = value_part[:last_quote_idx]
value_close = value_part[last_quote_idx:]
value_before_close = value_before_close.replace('"', "'")
line = key_part + ': "' + value_before_close + value_close
lines.append(line)
return '\n'.join(lines)
def _extract_yaml_block_text(self, variable_dict_text: str) -> Tuple[str, str, str]:
"""Extract prefix, YAML block content, and suffix from variable_dictionary."""
yaml_matches = list(re.finditer(r'```yaml\s*(.*?)\s*```', variable_dict_text, re.DOTALL))
if not yaml_matches:
return "", "", ""
data_match = yaml_matches[1] if len(yaml_matches) > 1 else yaml_matches[0]
prefix = variable_dict_text[:data_match.start()]
yaml_content = data_match.group(1)
suffix = variable_dict_text[data_match.end():]
return prefix, yaml_content, suffix
def _parse_variable_dictionary_yaml(self, variable_dict_text: str) -> Dict[str, object]:
"""Parse the YAML dictionary block into a Python dict."""
_, yaml_content, _ = self._extract_yaml_block_text(variable_dict_text)
if not yaml_content:
if not self._variable_dict_parse_failed:
logger.warning("Could not extract YAML from variable_dictionary.")
self._variable_dict_parse_failed = True
return {}
yaml_content = self._normalize_yaml_content(yaml_content)
try:
return yaml.safe_load(yaml_content) or {}
except yaml.YAMLError as e:
if not self._variable_dict_parse_failed:
logger.warning(f"Failed to parse YAML from variable_dictionary: {e}")
self._variable_dict_parse_failed = True
return {}
def _extract_yaml_scope_block(self, yaml_content: str, scope_root: str) -> str:
"""Extract a root scope from YAML text without parsing."""
lines = yaml_content.splitlines()
start = None
end = None
for i, line in enumerate(lines):
stripped = line.strip()
if not stripped:
continue
if line.lstrip() == line and stripped.startswith(f"{scope_root}:"):
start = i
continue
if start is not None and line.lstrip() == line and stripped.endswith(":"):
end = i
break
if start is None:
return ""
if end is None:
end = len(lines)
return "\n".join(lines[start:end]).strip()
def _build_variable_dictionary_subset(self, scope_root: str) -> str:
"""Return variable_dictionary text limited to a single root scope."""
if self._variable_dict_data and scope_root in self._variable_dict_data:
prefix, _, suffix = self._extract_yaml_block_text(self._variable_dict_text)
if not prefix and not suffix:
return self._variable_dict_text
filtered = {scope_root: self._variable_dict_data.get(scope_root, {})}
filtered_yaml = yaml.safe_dump(filtered, allow_unicode=True, sort_keys=False).strip()
new_block = f"```yaml\n{filtered_yaml}\n```"
return prefix + new_block + suffix
prefix, yaml_content, suffix = self._extract_yaml_block_text(self._variable_dict_text)
if not yaml_content:
return self._variable_dict_text
scope_block = self._extract_yaml_scope_block(yaml_content, scope_root)
if not scope_block:
return self._variable_dict_text
new_block = f"```yaml\n{scope_block}\n```"
return prefix + new_block + suffix
def _build_scan_scope_note(self, scope: Optional[str]) -> str:
"""Build scope-specific guardrails to keep the model focused."""
if scope == self.SCAN_SCOPE_EXPLORATORIOS:
return (
"<scan_scope>\n"
"MODO DE VARREDURA: fatores_exploratorios\n"
"- Use SOMENTE variáveis de fatores_exploratorios\n"
"- Ignore fatores_classificatorios\n"
"</scan_scope>"
)
if scope == self.SCAN_SCOPE_CLASSIFICATORIOS:
return (
"<scan_scope>\n"
"MODO DE VARREDURA: fatores_classificatorios\n"
"- Use SOMENTE variáveis de fatores_classificatorios\n"
"- Ignore fatores_exploratorios\n"
"</scan_scope>"
)
return ""
def _extract_keyword_mappings_from_yaml(self, scope: Optional[str] = None) -> Dict[str, List[str]]:
"""
Dynamically extract keyword-to-variable mappings from the YAML variable dictionary.
This ensures the keyword index stays synchronized with the dictionary automatically.
Returns:
Dictionary mapping keywords/phrases to variable names
"""
if self._variable_dict_parse_failed:
return {}
yaml_data = self._variable_dict_data
if not yaml_data:
return {}
keyword_map = {}
def extract_keywords_from_definition(var_name: str, definition: str):
"""Extract meaningful keywords from a variable definition."""
keywords = []
# Common patterns to extract
patterns = [
r'"([^"]+)"', # Text in quotes
r'Ex[.:]\s*([^;.]+)', # Examples after "Ex:", "Ex."
r'e\.g\.\s*([^;.]+)', # Examples after "e.g."
]
for pattern in patterns:
matches = re.findall(pattern, definition, re.IGNORECASE)
for match in matches:
# Clean and split on common separators
terms = re.split(r'[,;]', match.strip())
for term in terms:
term = term.strip().lower()
if len(term) > 3 and len(term) < 50: # Reasonable keyword length
keywords.append(term)
# Also extract key terms from the main definition
# Look for significant nouns and phrases
key_terms = re.findall(r'\b([a-záàâãéèêíïóôõöúçñ]{4,}(?:\s+[a-záàâãéèêíïóôõöúçñ]{3,}){0,2})\b',
definition.lower())
# Filter common words
stop_words = {'para', 'como', 'pela', 'pelo', 'seus', 'suas', 'essa', 'esse',
'esta', 'este', 'mais', 'pode', 'forma', 'sobre', 'após', 'desde'}
for term in key_terms[:3]: # Take first 3 significant terms
if not any(stop in term for stop in stop_words):
keywords.append(term)
return keywords[:5] # Limit to 5 keywords per variable
def traverse_dict(d, path=[]):
"""Recursively traverse the YAML structure to find leaf variables."""
if isinstance(d, dict):
for key, value in d.items():
if isinstance(value, str):
# This is a leaf node (variable definition)
var_name = key
keywords = extract_keywords_from_definition(var_name, value)
for keyword in keywords:
if keyword not in keyword_map:
keyword_map[keyword] = []
if var_name not in keyword_map[keyword]:
keyword_map[keyword].append(var_name)
elif isinstance(value, dict):
traverse_dict(value, path + [key])
if scope == self.SCAN_SCOPE_EXPLORATORIOS and 'fatores_exploratorios' in yaml_data:
traverse_dict(yaml_data['fatores_exploratorios'])
elif scope == self.SCAN_SCOPE_CLASSIFICATORIOS and 'fatores_classificatorios' in yaml_data:
traverse_dict(yaml_data['fatores_classificatorios'])
else:
if 'fatores_exploratorios' in yaml_data:
traverse_dict(yaml_data['fatores_exploratorios'])
if 'fatores_classificatorios' in yaml_data:
traverse_dict(yaml_data['fatores_classificatorios'])
logger.info(f"Extracted {len(keyword_map)} keyword mappings from YAML dictionary")
return keyword_map
def _build_exhaustive_extraction_instructions(self, scope: Optional[str] = None) -> str:
"""
Build exhaustive extraction instructions that will be cached.
These instructions guide the model to extract ALL variables systematically.
Uses dynamic keyword mapping from YAML dictionary.
"""
# Get dynamic keyword mappings
keyword_map = self._extract_keyword_mappings_from_yaml(scope)
# Build keyword index section dynamically
keyword_index_lines = []
for keyword, var_names in sorted(keyword_map.items())[:50]: # Top 50 most relevant
vars_str = ", ".join(var_names[:4]) # Max 4 variables per keyword
keyword_index_lines.append(f'- "{keyword}" → {vars_str}')
keyword_index = "\n".join(keyword_index_lines)
category_lines = ""
scope_guard = ""
manual_keywords = ""
if scope == self.SCAN_SCOPE_EXPLORATORIOS:
category_lines = " - Exploratórias: drivers_religiosos, dom, etica_crista, psico_emocionais, percepcao_impacto, valores_seculares, caracteristicas_adm"
scope_guard = " - IGNORE variáveis classificatórias."
elif scope == self.SCAN_SCOPE_CLASSIFICATORIOS:
category_lines = " - Classificatórias: conversao, graca, aperfeicoamento, gratidao, modelo_gestao, sacrificio, esg/ods, rsc, esfera_soberania"
scope_guard = " - IGNORE variáveis exploratórias."
manual_keywords = """
CATEGORIAS CRÍTICAS FREQUENTEMENTE SUBDETECTADAS:
→ ODS (OBJETIVOS DE DESENVOLVIMENTO SUSTENTÁVEL) - ATENÇÃO ESPECIAL:
IMPORTANTE: ODS são frequentemente mencionados de forma INDIRETA ou com SINÔNIMOS.
Busque manifestações PRÁTICAS, não apenas jargão técnico de sustentabilidade.
ODS 1 - erradicacao_da_pobreza:
Keywords: "pobreza", "pobre", "miserável", "carente", "necessitado", "vulnerável"
ODS 2 - fome_zero_e_agricultura_sustentavel:
Keywords: "fome", "alimentação", "agricultura", "alimento", "nutrição", "comida"
ODS 3 - saude_e_bem_estar:
Keywords: "saúde", "bem-estar", "doença", "hospital", "médico", "tratamento", "cuidar"
ODS 4 - educacao_de_qualidade:
Keywords: "educação", "ensino", "escola", "aprendizado", "formação", "capacitação"
ODS 5 - igualdade_de_genero:
Keywords: "gênero", "mulher", "feminino", "igualdade", "equidade de gênero"
ODS 6 - agua_potavel_e_saneamento:
Keywords: "água", "saneamento", "higiene", "esgoto", "água potável"
ODS 7 - energia_limpa_e_acessivel:
Keywords: "energia", "renovável", "elétrica", "energia limpa", "sustentável"
ODS 8 - trabalho_decente_e_crescimento_economico:
Keywords: "trabalho decente", "emprego", "crescimento", "economia", "renda", "trabalhador"
ODS 9 - industria_inovacao_e_infraestrutura:
Keywords: "indústria", "inovação", "infraestrutura", "tecnologia", "industrial"
ODS 10 - reducao_das_desigualdades:
Keywords: "desigualdade", "inclusão", "discriminação", "equidade", "justiça social"
ODS 11 - cidades_e_comunidades_sustentaveis:
Keywords: "cidade", "comunidade", "urbano", "habitação", "moradia", "bairro"
ODS 12 - consumo_e_producao_responsaveis:
Keywords: "consumo", "produção", "resíduo", "desperdício", "sustentável", "reciclagem"
ODS 13 - acao_contra_mudanca_global_do_clima:
Keywords: "clima", "mudança climática", "aquecimento", "emissão", "carbono", "CO2"
ODS 14 - vida_na_agua:
Keywords: "oceano", "mar", "pesca", "marinho", "vida aquática", "água do mar"
ODS 15 - vida_terrestre:
Keywords: "floresta", "biodiversidade", "desmatamento", "ecossistema", "fauna", "flora"
ODS 16 - paz_justica_e_instituicoes_eficazes:
Keywords: "paz", "justiça", "instituição", "corrupção", "transparência", "governança"
ODS 17 - parcerias_e_meios_de_implementacao:
Keywords: "parceria", "cooperação", "aliança", "colaboração", "rede", "global"
→ ESFERA DE SOBERANIA (ASPECTOS DA REALIDADE):
- números, quantidades, "funcionários", "unidades" → aspecto_numerico_1
- espaço, lugar, "localização", "região" → aspecto_espacial_2
- movimento, "crescimento", "mudança ao longo do tempo" → aspecto_cinetico_3
- físico, material, "equipamento", "estrutura" → aspecto_fisico_4
- vida, saúde, "cuidar", "bem-estar físico" → aspecto_biotico_5
- sentimento, emoção, "dor", "alegria", "medo" → aspecto_sensitivo_6
- lógica, razão, "pensar", "analisar" → aspecto_analitico_7
- formar, criar, "planejar", "desenvolver" → aspecto_formativo_8
- comunicação, "falar", "conversar", "linguagem" → aspecto_linguistico_9
- relações, "equipe", "convivência", "social" → aspecto_social_10
- dinheiro, recursos, "lucro", "custo", "econômico" → aspecto_economico_11
- beleza, estética, "design" → aspecto_estetico_12
- lei, norma, "direito", "justiça legal" → aspecto_juridico_13
- amor, moral, "integridade", "ética" → aspecto_etico_14
- fé, "Deus", "oração", "transcendente" → aspecto_pistico_15
→ ESG E PERCEPÇÕES:
- "ESG", "sustentabilidade corporativa", "governança" → todas as subcategorias de esg
- "agenda", "ideologia", "progressismo" → esg_como_agenda_ideologica_e_de_poder
- "obrigação", "burocracia", "compliance" → esg_como_aparato_normativo_e_anticompetitivo
- "marketing", "greenwashing", "hipocrisia" → esg_como_capital_simbolico_e_reputacional
- "Jesus ordenou", "mandamento cristão" → obrigacoes_que_jesus_ordenou
"""
else:
category_lines = (
" - Classificatórias: conversao, graca, aperfeicoamento, gratidao, modelo_gestao, sacrificio, esg/ods, rsc, esfera_soberania\n"
" - Exploratórias: drivers_religiosos, dom, etica_crista, psico_emocionais, percepcao_impacto, valores_seculares, caracteristicas_adm"
)
return f"""
INSTRUÇÕES DE EXTRAÇÃO EXAUSTIVA:
1. SEGMENTE o transcript em unidades semânticas (1-3 frases por unidade)
2. PARA CADA UNIDADE, verifique TODAS as variáveis dentro do escopo:
{category_lines}
{scope_guard}
3. MULTI-CODIFICAÇÃO É OBRIGATÓRIA:
- Cada ITEM deve ter 3-10 variáveis (média esperada: 5+)
- Se encontrou 1 variável, busque 4+ mais no MESMO trecho
4. METAS DE COBERTURA (IMPORTANTE):
- Mínimo: 80 ITEMs por entrevista típica
- Média esperada: 100-120 ITEMs
- Variáveis totais: 200-400 por entrevista
5. VIÉS PARA INCLUSÃO: Na dúvida, SEMPRE INCLUA com justificativa.
{manual_keywords}
ÍNDICE DINÂMICO DE PALAVRAS-CHAVE → VARIÁVEIS:
(Extraído automaticamente do dicionário YAML)
{keyword_index}
ATENÇÃO ESPECIAL - BUSQUE MANIFESTAÇÕES PRÁTICAS (não jargão teológico):
- Use palavras SIMPLES do dia-a-dia do entrevistado
- Não exija terminologia técnica
- Valorize expressões coloquiais e concretas
"""
def _build_cached_user_prefix(self, scope: Optional[str] = None) -> str:
"""
Build the static user message prefix that will be cached.
This includes task, instructions, variable dictionary, output format, and exhaustive extraction instructions.
The transcript will be appended dynamically.
"""
variable_dictionary = self._variable_dictionary_by_scope.get(
scope,
self.static_prompt_parts["variable_dictionary"]
)
scope_note = self._build_scan_scope_note(scope)
parts = [
self.static_prompt_parts["task"],
self.static_prompt_parts["instructions"]
]
if scope_note:
parts.append(scope_note)
parts.extend([
variable_dictionary,
self.static_prompt_parts["output_format"],
self._build_exhaustive_extraction_instructions(scope)
])
return "\n\n".join(parts)
def _build_base_prompt_template(self) -> str:
"""Build the static parts of the prompt once to avoid repeated string concatenation."""
return "\n\n".join([
self.static_prompt_parts["task"],
"{transcript_part}", # Placeholder for dynamic content
self.static_prompt_parts["instructions"],
self.static_prompt_parts["variable_dictionary"],
self.static_prompt_parts["output_format"],
"Analyze the interview transcript and provide your analysis in the exact format specified above."
])
def _build_recall_block(self, scope: Optional[str]) -> str:
"""Build a scope-aware recall block to keep the model focused."""
if scope == self.SCAN_SCOPE_EXPLORATORIOS:
return (
"MODO DE VARREDURA (EXPLORATORIOS):\n"
"- Use SOMENTE variáveis de fatores_exploratorios\n"
"- Ignore fatores_classificatorios\n"
"- Se não houver evidência literal forte, NÃO gere ITEM\n\n"
"AGORA COMECE A EXTRAÇÃO."
)
if scope == self.SCAN_SCOPE_CLASSIFICATORIOS:
return (
"MODO DE VARREDURA (CLASSIFICATORIOS):\n"
"- Use SOMENTE variáveis de fatores_classificatorios\n"
"- Ignore fatores_exploratorios\n"
"- Se não houver evidência literal forte, NÃO gere ITEM\n\n"
"AGORA COMECE A EXTRAÇÃO."
)
return """
═══════════════════════════════════════════════════════════
ANTES DE GERAR O OUTPUT, FAÇA UM RECALL COMPLETO:
═══════════════════════════════════════════════════════════
1. RELEIA mentalmente o transcript inteiro acima
2. RECALL ESPECÍFICO POR CATEGORIA:
A) VARIÁVEIS CLASSIFICATÓRIAS:
- conversao: Busque eventos de conhecer Jesus, batismo, transformação
- graca: Busque "recebi", "Deus me deu", favor imerecido
- gratidao: Busque "agradecer", "grato", reconhecimento
- modelo_gestao: Busque menção a lucro, prejuízo, custos, resultados financeiros
- sacrificio: Busque perdas, renúncias, prejuízos por fé
- esg/ods: Busque sustentabilidade, social, ambiental, governança
- rsc: Busque responsabilidade social, práticas éticas
- esfera_soberania: Busque números, espaço, tempo, recursos, comunicação, emoções, fé
B) ODS (BUSQUE ESPECIALMENTE - ALTA PRIORIDADE):
IMPORTANTE: ODS são expressões PRÁTICAS, não jargão técnico.
Busque manifestações CONCRETAS destes temas:
→ ODS 1 (erradicacao_da_pobreza): "pobre", "pobreza", "carente", "necessitado"
→ ODS 2 (fome_zero_e_agricultura_sustentavel): "fome", "alimentação", "agricultura"
→ ODS 3 (saude_e_bem_estar): "saúde", "bem-estar", "doença", "cuidar da saúde"
→ ODS 4 (educacao_de_qualidade): "educação", "ensino", "escola", "capacitação"
→ ODS 5 (igualdade_de_genero): "mulher", "gênero", "igualdade de gênero"
→ ODS 6 (agua_potavel_e_saneamento): "água", "saneamento", "higiene"
→ ODS 7 (energia_limpa_e_acessivel): "energia", "renovável", "energia limpa"
→ ODS 8 (trabalho_decente_e_crescimento_economico): "trabalho decente", "emprego", "trabalhador"
→ ODS 9 (industria_inovacao_e_infraestrutura): "indústria", "inovação", "tecnologia"
→ ODS 10 (reducao_das_desigualdades): "desigualdade", "inclusão", "discriminação"
→ ODS 11 (cidades_e_comunidades_sustentaveis): "cidade", "comunidade", "urbano"
→ ODS 12 (consumo_e_producao_responsaveis): "consumo", "produção", "desperdício"
→ ODS 13 (acao_contra_a_mudanca_global_do_clima): "clima", "emissão", "aquecimento"
→ ODS 14 (vida_na_agua): "mar", "oceano", "pesca", "marinho", "água do mar"
→ ODS 15 (vida_terrestre): "floresta", "biodiversidade", "desmatamento"
→ ODS 16 (paz_justica_e_instituicoes_eficazes): "paz", "justiça", "corrupção"
→ ODS 17 (parcerias_e_meios_de_implementacao): "parceria", "cooperação", "aliança"
C) ESFERA DE SOBERANIA (BUSQUE ESPECIALMENTE):
- Números/quantidades → aspecto_numerico_1
- Espaço/lugar → aspecto_espacial_2
- Movimento/mudança → aspecto_cinetico_3
- Material/físico → aspecto_fisico_4
- Vida/saúde → aspecto_biotico_5
- Emoções/sentimentos → aspecto_sensitivo_6
- Lógica/razão → aspecto_analitico_7
- Planejar/formar → aspecto_formativo_8
- Comunicação/linguagem → aspecto_linguistico_9
- Relações/social → aspecto_social_10
- Dinheiro/recursos → aspecto_economico_11
- Beleza/estética → aspecto_estetico_12
- Lei/norma → aspecto_juridico_13
- Amor/moral → aspecto_etico_14
- Fé/transcendente → aspecto_pistico_15
D) DRIVERS PSICO-EMOCIONAIS:
- medo, coragem, ansiedade, frustração, calma
3. Use o ÍNDICE DE PALAVRAS-CHAVE para identificar rapidamente variáveis
4. MULTI-CODIFIQUE: se encontrou 1 variável, busque 4+ mais no MESMO trecho
METAS DE COBERTURA (CRÍTICO):
- Mínimo: 80 ITEMs por entrevista típica
- Média esperada: 100-120 ITEMs
- Variáveis totais: 200-400 por entrevista
AGORA COMECE A EXTRAÇÃO. Gere TODOS os ITEMs com evidência literal."""
def estimate_tokens(self, text: str) -> int:
"""Estimate tokens with caching to avoid repeated tokenization."""
text_hash = hash(text)
if text_hash in self._token_cache:
return self._token_cache[text_hash]
try:
# Improved estimation for Portuguese: ~1.3 tokens per word (more conservative)
# Portuguese tends to use more tokens due to accents and longer words
words = len(text.split())
tokens = int(words * 1.3)
self._token_cache[text_hash] = tokens
return tokens
except Exception as e:
logger.warning(f"Token estimation failed: {e}")
fallback = len(text) // 3 # More conservative fallback
self._token_cache[text_hash] = fallback
return fallback
def calculate_max_transcript_tokens(
self,
desired_output_tokens: int = None,
scope: Optional[str] = None,
static_tokens_override: Optional[int] = None
) -> int:
"""
Calculate maximum tokens available for transcript content.
Args:
desired_output_tokens: Desired output tokens (defaults to model max)
scope: Optional scan scope for prompt sizing
static_tokens_override: Optional override for static token count
Returns:
Maximum tokens available for transcript
"""
if desired_output_tokens is None:
desired_output_tokens = self.max_output_limit
if static_tokens_override is not None:
static_tokens = static_tokens_override
elif scope is not None:
static_tokens = self._static_prompt_tokens_by_scope.get(scope, self._static_prompt_tokens)
else:
static_tokens = self._static_prompt_tokens
# Reserve tokens: static prompt + output + safety margin (10%)
safety_margin = int(self.model_token_limit * 0.10)
available = self.model_token_limit - static_tokens - desired_output_tokens - safety_margin
logger.debug(f"Token budget: {self.model_token_limit} total, "
f"{static_tokens} static, "
f"{desired_output_tokens} output, "
f"{safety_margin} margin = {available} for transcript")
return max(available, 5000) # Minimum 5000 tokens for transcript
def create_cached_api_messages(
self,
interview_id: str,
transcript: str,
scope: Optional[str] = None
) -> Tuple[List[Dict], List[Dict]]:
"""
Create API messages with prompt caching enabled.
Returns:
Tuple of (system_messages, user_messages) formatted for Claude API with cache_control
"""
# Build dynamic transcript part with scope-aware recall prompt
recall_block = self._build_recall_block(scope)
transcript_block = f"""<interview_transcript>
interview_id: {interview_id}
{transcript}
</interview_transcript>
{recall_block}"""
# System message with cache_control on static content
system_messages = [
{
"type": "text",
"text": self._cached_system_prompt,
"cache_control": {"type": "ephemeral"}
}
]
# User message: static prefix (cached) + dynamic transcript
user_messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": self._cached_user_prefix_by_scope.get(scope, self._cached_user_prefix),
"cache_control": {"type": "ephemeral"}
},
{
"type": "text",
"text": transcript_block
}
]
}
]
return system_messages, user_messages
def validate_literal_match(self, ordem_1a: str, transcript: str, threshold: float = 0.95) -> tuple[bool, float]:
"""
Validates if ordem_1a appears literally in the transcript.
Args:
ordem_1a: The extracted text that should be literal
transcript: The original transcript to search in
threshold: Minimum similarity score to accept (0.95 = 95%)
Returns:
tuple: (is_valid, similarity_score)
"""
from difflib import SequenceMatcher
# Normalize: remove extra whitespace but preserve content
normalized_ordem = re.sub(r'\s+', ' ', ordem_1a.strip().lower())
normalized_transcript = re.sub(r'\s+', ' ', transcript.strip().lower())