Spaces:
Running
Running
Download execution/inference_wav2vec.py from TEDDyx86/confereai-dev: direct link, hf CLI and curl.
- Browser
- Download file 7.48 kB
-
https://huggingface.co/spaces/TEDDyx86/confereai-dev/resolve/main/execution/inference_wav2vec.py
- Command line
-
hf download hf://spaces/TEDDyx86/confereai-dev/execution/inference_wav2vec.py
-
curl -L -o inference_wav2vec.py https://huggingface.co/spaces/TEDDyx86/confereai-dev/resolve/main/execution/inference_wav2vec.py
7.48 kB
| import sys | |
| import json | |
| import os | |
| import torch | |
| import librosa | |
| import numpy as np | |
| from transformers import AutoFeatureExtractor, AutoModelForAudioClassification | |
| # --------------------------------------------------------------------------- | |
| # Seleção de motor | |
| # --------------------------------------------------------------------------- | |
| # O modelo base anterior (HyperMoon) só publica `pytorch_model.bin`. Versões | |
| # recentes do transformers recusam carregar .bin quando o torch é anterior a | |
| # 2.6 (CVE-2025-32434), o que derrubava TODA análise com "ERROR". | |
| # Passamos a usar modelos publicados em `safetensors` (carregamento seguro e | |
| # independente da versão do torch), mantendo a possibilidade de override por | |
| # variável de ambiente. | |
| DEFAULT_MODEL = os.environ.get( | |
| "WAV2VEC_MODEL", | |
| "garystafford/wav2vec2-deepfake-voice-detector", | |
| ) | |
| # Repositório customizado (ex.: modelo fine-tuned do painel admin, publicado | |
| # manualmente no Hub). Continua sendo opt-in para não trocar o motor em uso. | |
| CUSTOM_MODEL_REPO = os.environ.get("CUSTOM_MODEL_REPO") | |
| # Cadeia de fallback: todos publicados em safetensors. | |
| FALLBACK_MODELS = [ | |
| "Gustking/wav2vec2-large-xlsr-deepfake-audio-classification", | |
| "MelodyMachine/Deepfake-audio-detection-V2", | |
| "mo-thecreator/Deepfake-audio-detection", | |
| ] | |
| # Singleton para carregar o modelo e processador apenas uma vez | |
| _feature_extractor = None | |
| _model = None | |
| _last_model_path = None | |
| def _model_candidates(extra_model=None): | |
| """Monta a lista de modelos a tentar, sem duplicatas e preservando a ordem.""" | |
| candidates = [] | |
| for path in (extra_model, CUSTOM_MODEL_REPO, DEFAULT_MODEL, *FALLBACK_MODELS): | |
| if path and path not in candidates: | |
| candidates.append(path) | |
| return candidates | |
| def _load_resources(model_path): | |
| """Carrega extrator + modelo de um caminho específico.""" | |
| print(f"Carregando motor Wav2Vec2: {model_path}...", file=sys.stderr) | |
| feature_extractor = AutoFeatureExtractor.from_pretrained(model_path) | |
| model = AutoModelForAudioClassification.from_pretrained(model_path) | |
| # --- OTIMIZAÇÃO: Quantização Dinâmica para CPU --- | |
| if not torch.cuda.is_available(): | |
| try: | |
| print("Aplicando Quantização Dinâmica (CPU Optimization)...", file=sys.stderr) | |
| model = torch.quantization.quantize_dynamic( | |
| model, {torch.nn.Linear}, dtype=torch.qint8 | |
| ) | |
| except Exception as e: | |
| # Quantização é otimização, não requisito: segue em fp32. | |
| print(f"Aviso: quantização indisponível ({e}). Usando fp32.", file=sys.stderr) | |
| model.eval() | |
| return feature_extractor, model | |
| def get_wav2vec_resources(model_path=None): | |
| """ | |
| Retorna (caminho_usado, feature_extractor, model). | |
| Tenta o caminho pedido e, se ele falhar, percorre a cadeia de fallback. | |
| O resultado fica em cache (singleton) por caminho. | |
| """ | |
| global _feature_extractor, _model, _last_model_path | |
| candidates = _model_candidates(model_path) | |
| # Reaproveita o cache se o modelo já carregado ainda é um candidato válido. | |
| if ( | |
| _feature_extractor is not None | |
| and _model is not None | |
| and _last_model_path in candidates | |
| ): | |
| return _last_model_path, _feature_extractor, _model | |
| errors = [] | |
| for path in candidates: | |
| try: | |
| feature_extractor, model = _load_resources(path) | |
| except Exception as e: | |
| errors.append(f"{path}: {e}") | |
| print(f"⚠️ Falha ao carregar '{path}': {e}", file=sys.stderr) | |
| continue | |
| _feature_extractor = feature_extractor | |
| _model = model | |
| _last_model_path = path | |
| return path, _feature_extractor, _model | |
| raise RuntimeError( | |
| "Nenhum motor Wav2Vec2 pôde ser carregado. Detalhes: " + " | ".join(errors) | |
| ) | |
| def _temporal_scores(feature_extractor, model, audio, fraud_idx): | |
| """Classifica janelas de 1s em mini-batches (explicabilidade temporal).""" | |
| print("Iniciando Análise Temporal Otimizada...", file=sys.stderr) | |
| temporal_scores = [] | |
| samples_per_segment = 16000 # 1 segundo | |
| segments = [] | |
| for i in range(0, len(audio), samples_per_segment): | |
| segment = audio[i : i + samples_per_segment] | |
| if len(segment) < samples_per_segment // 2: | |
| continue | |
| if len(segment) < samples_per_segment: | |
| segment = np.pad(segment, (0, samples_per_segment - len(segment))) | |
| segments.append(segment) | |
| BATCH_SIZE = 8 # evita OOM no Hugging Face (CPU only) | |
| for i in range(0, len(segments), BATCH_SIZE): | |
| batch_segments = segments[i : i + BATCH_SIZE] | |
| seg_inputs = feature_extractor( | |
| batch_segments, sampling_rate=16000, return_tensors="pt", padding=True | |
| ) | |
| with torch.no_grad(): | |
| seg_logits = model(**seg_inputs).logits | |
| seg_probs = torch.softmax(seg_logits, dim=-1) | |
| temporal_scores.extend( | |
| [round(p[fraud_idx].item(), 3) for p in seg_probs] | |
| ) | |
| return temporal_scores | |
| def run_inference(audio_path, fallback_model_name=None): | |
| """Executa a inferência com o motor principal e fallbacks em safetensors.""" | |
| try: | |
| model_path, feature_extractor, model = get_wav2vec_resources(fallback_model_name) | |
| model_name = f"HF Model ({model_path})" | |
| print(f"Rodando inferência REAL [{model_name}] em: {audio_path}", file=sys.stderr) | |
| # 1. Carrega e pré-processa o áudio | |
| print(f"Lendo áudio: {audio_path}", file=sys.stderr) | |
| audio, _ = librosa.load(audio_path, sr=16000) | |
| # 2. Prepara inputs para o áudio completo | |
| inputs = feature_extractor( | |
| audio, sampling_rate=16000, return_tensors="pt", padding=True | |
| ) | |
| # 3. Inferência Principal | |
| with torch.no_grad(): | |
| logits = model(**inputs).logits | |
| # 4. Processa resultados | |
| scores = torch.softmax(logits, dim=-1) | |
| id2label = model.config.id2label | |
| # Encontra o índice da classe de fraude (fake/spoof/fraud) | |
| fraud_idx = 0 | |
| for idx, lbl in id2label.items(): | |
| if any(x in str(lbl).lower() for x in ["fake", "spoof", "fraud"]): | |
| fraud_idx = int(idx) | |
| break | |
| fraud_prob = scores[0][fraud_idx].item() | |
| is_fraud = fraud_prob > 0.5 | |
| # 5. Explicabilidade temporal | |
| temporal_scores = _temporal_scores( | |
| feature_extractor, model, audio, fraud_idx | |
| ) | |
| return { | |
| "model": model_name, | |
| "prediction": str(id2label[torch.argmax(scores).item()]).upper(), | |
| "confidence": scores[0][torch.argmax(scores).item()].item(), | |
| "deepfake_probability": fraud_prob, | |
| "temporal_scores": temporal_scores, | |
| "verdict": "SPOOF" if is_fraud else "BONAFIDE", | |
| "metadata": { | |
| "id2label": id2label, | |
| "quantized": not torch.cuda.is_available(), | |
| }, | |
| } | |
| except Exception as e: | |
| print(f"Erro na inferência: {e}", file=sys.stderr) | |
| return {"error": str(e), "verdict": "ERROR"} | |
| if __name__ == "__main__": | |
| if len(sys.argv) < 2: | |
| print("Uso: python inference_wav2vec.py <audio_path>") | |
| else: | |
| # Silenciamos warnings de transformers | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| print(json.dumps(run_inference(sys.argv[1]))) | |