RJ40under40 commited on
Commit
18828c4
·
verified ·
1 Parent(s): 200a1a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -43
app.py CHANGED
@@ -6,7 +6,6 @@ import numpy as np
6
  import torch
7
  import librosa
8
  import uvicorn
9
-
10
  from fastapi import FastAPI, HTTPException, Security, Depends
11
  from fastapi.middleware.cors import CORSMiddleware
12
  from fastapi.security.api_key import APIKeyHeader
@@ -14,46 +13,41 @@ from pydantic import BaseModel
14
  from transformers import AutoFeatureExtractor, AutoModelForAudioClassification
15
 
16
  # ======================================================
17
- # CONFIG & SECRETS
18
  # ======================================================
 
 
19
  API_KEY_NAME = "access_token"
20
  API_KEY_VALUE = "HCL_SECURE_KEY_2026"
21
 
22
- # Get your Hugging Face token from the Space's Secret settings
23
- HF_TOKEN = os.getenv("HF_TOKEN")
24
-
25
- MODEL_ID = "melba-t/wav2vec2-fake-speech-detection"
26
  TARGET_SR = 16000
27
- LABEL_MAP = {0: "HUMAN", 1: "AI_GENERATED"}
28
 
29
- logging.basicConfig(level=logging.INFO)
30
- logger = logging.getLogger("hcl-api")
 
31
 
32
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
 
33
 
34
  # ======================================================
35
- # MODEL INITIALIZATION (WITH AUTH)
36
  # ======================================================
 
 
 
37
  try:
38
- logger.info(f"Loading private model {MODEL_ID}...")
39
- # Passing the token allows access to the private/restricted repo
40
- feature_extractor = AutoFeatureExtractor.from_pretrained(
41
- MODEL_ID,
42
- token=HF_TOKEN
43
- )
44
- model = AutoModelForAudioClassification.from_pretrained(
45
- MODEL_ID,
46
- token=HF_TOKEN
47
- ).to(DEVICE)
48
  model.eval()
49
  logger.info("Model loaded successfully.")
50
  except Exception as e:
51
- logger.error(f"Error loading model: {e}")
52
- # Fallback to prevent app crash if token is missing
53
- model = None
54
 
55
  # ======================================================
56
- # FASTAPI APP
57
  # ======================================================
58
  app = FastAPI(title="HCL AI Voice Detection API")
59
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
@@ -68,72 +62,78 @@ app.add_middleware(
68
  class AudioRequest(BaseModel):
69
  audio_base64: str
70
 
 
71
  async def verify_api_key(api_key: str = Security(api_key_header)):
72
  if api_key != API_KEY_VALUE:
73
  raise HTTPException(status_code=403, detail="Invalid API Key")
74
  return api_key
75
 
 
 
 
76
  def preprocess_audio(b64_string: str):
 
77
  try:
 
78
  if "," in b64_string:
79
  b64_string = b64_string.split(",")[1]
80
 
81
- # Standardize padding
82
  missing_padding = len(b64_string) % 4
83
  if missing_padding:
84
  b64_string += "=" * (4 - missing_padding)
85
 
86
  audio_bytes = base64.b64decode(b64_string)
87
 
88
- # Load audio using librosa (requires ffmpeg in packages.txt)
89
  with io.BytesIO(audio_bytes) as bio:
90
  audio, sr = librosa.load(bio, sr=TARGET_SR)
91
 
 
92
  if len(audio) < TARGET_SR:
93
  audio = np.pad(audio, (0, TARGET_SR - len(audio)))
94
 
95
  return audio.astype(np.float32)
96
  except Exception as e:
97
- logger.error(f"Preprocessing error: {e}")
98
- raise ValueError(f"Decoding failed: {str(e)}")
99
 
100
  @app.get("/")
101
- def home():
102
- return {"message": "HCL Voice Detection API Active. Visit /docs"}
103
 
104
  @app.post("/predict")
105
  async def predict(request: AudioRequest, _: str = Depends(verify_api_key)):
106
  if model is None:
107
- raise HTTPException(status_code=503, detail="Model not loaded. Check HF_Token.")
108
 
109
  try:
 
110
  waveform = preprocess_audio(request.audio_base64)
111
 
112
- inputs = feature_extractor(
113
- waveform,
114
- sampling_rate=TARGET_SR,
115
- return_tensors="pt"
116
- ).to(DEVICE)
117
 
118
- with torch.inference_mode():
 
119
  logits = model(**inputs).logits
120
  probs = torch.softmax(logits, dim=-1)
121
 
 
122
  confidence, pred_idx = torch.max(probs, dim=-1)
123
-
124
- # Map prediction to required hackathon labels
125
  label = LABEL_MAP.get(int(pred_idx.item()), "UNKNOWN")
126
 
127
  return {
128
  "classification": label,
129
  "confidence_score": round(float(confidence.item()), 4)
130
  }
 
131
  except ValueError as ve:
132
  raise HTTPException(status_code=400, detail=str(ve))
133
  except Exception as e:
134
- logger.error(f"Prediction error: {e}")
135
- raise HTTPException(status_code=500, detail="Inference Error")
136
 
137
  if __name__ == "__main__":
138
- # Port 7860 is required for Hugging Face Spaces
139
  uvicorn.run("app:app", host="0.0.0.0", port=7860)
 
6
  import torch
7
  import librosa
8
  import uvicorn
 
9
  from fastapi import FastAPI, HTTPException, Security, Depends
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from fastapi.security.api_key import APIKeyHeader
 
13
  from transformers import AutoFeatureExtractor, AutoModelForAudioClassification
14
 
15
  # ======================================================
16
+ # CONFIG & HACKATHON SETTINGS
17
  # ======================================================
18
+ # Use the Secret "HF_Token" if the model ever becomes restricted
19
+ HF_TOKEN = os.getenv("HF_Token")
20
  API_KEY_NAME = "access_token"
21
  API_KEY_VALUE = "HCL_SECURE_KEY_2026"
22
 
23
+ # A stable, high-accuracy public model for synthetic voice detection
24
+ MODEL_ID = "Hemgg/Deepfake-audio-detection"
 
 
25
  TARGET_SR = 16000
 
26
 
27
+ # Mapping model output indices to required Hackathon strings
28
+ # Note: Verified against Hemgg model config (0: Fake/AI, 1: Real/Human)
29
+ LABEL_MAP = {0: "AI_GENERATED", 1: "HUMAN"}
30
 
31
+ logging.basicConfig(level=logging.INFO)
32
+ logger = logging.getLogger("hcl-voice-safety")
33
 
34
  # ======================================================
35
+ # MODEL LOADING
36
  # ======================================================
37
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
38
+ logger.info(f"Loading model {MODEL_ID} to {DEVICE}...")
39
+
40
  try:
41
+ feature_extractor = AutoFeatureExtractor.from_pretrained(MODEL_ID, token=HF_TOKEN)
42
+ model = AutoModelForAudioClassification.from_pretrained(MODEL_ID, token=HF_TOKEN).to(DEVICE)
 
 
 
 
 
 
 
 
43
  model.eval()
44
  logger.info("Model loaded successfully.")
45
  except Exception as e:
46
+ logger.error(f"Critical Error: Failed to load model: {e}")
47
+ model = None
 
48
 
49
  # ======================================================
50
+ # API SETUP
51
  # ======================================================
52
  app = FastAPI(title="HCL AI Voice Detection API")
53
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
 
62
  class AudioRequest(BaseModel):
63
  audio_base64: str
64
 
65
+ # Security layer
66
  async def verify_api_key(api_key: str = Security(api_key_header)):
67
  if api_key != API_KEY_VALUE:
68
  raise HTTPException(status_code=403, detail="Invalid API Key")
69
  return api_key
70
 
71
+ # ======================================================
72
+ # CORE LOGIC
73
+ # ======================================================
74
  def preprocess_audio(b64_string: str):
75
+ """Processes base64 audio into a normalized 16kHz waveform."""
76
  try:
77
+ # Strip potential data URL prefix
78
  if "," in b64_string:
79
  b64_string = b64_string.split(",")[1]
80
 
81
+ # Ensure correct padding for base64
82
  missing_padding = len(b64_string) % 4
83
  if missing_padding:
84
  b64_string += "=" * (4 - missing_padding)
85
 
86
  audio_bytes = base64.b64decode(b64_string)
87
 
88
+ # Load audio using librosa (backed by ffmpeg for MP3 support)
89
  with io.BytesIO(audio_bytes) as bio:
90
  audio, sr = librosa.load(bio, sr=TARGET_SR)
91
 
92
+ # Padding/Stability: Ensure at least 1 second of audio
93
  if len(audio) < TARGET_SR:
94
  audio = np.pad(audio, (0, TARGET_SR - len(audio)))
95
 
96
  return audio.astype(np.float32)
97
  except Exception as e:
98
+ logger.error(f"Audio Preprocessing Failed: {e}")
99
+ raise ValueError("Decoding failed. Ensure valid Base64 MP3/WAV.")
100
 
101
  @app.get("/")
102
+ def root():
103
+ return {"status": "online", "model": MODEL_ID}
104
 
105
  @app.post("/predict")
106
  async def predict(request: AudioRequest, _: str = Depends(verify_api_key)):
107
  if model is None:
108
+ raise HTTPException(status_code=503, detail="Model unavailable.")
109
 
110
  try:
111
+ # 1. Convert B64 to raw waveform
112
  waveform = preprocess_audio(request.audio_base64)
113
 
114
+ # 2. Extract features and move to GPU/CPU
115
+ inputs = feature_extractor(waveform, sampling_rate=TARGET_SR, return_tensors="pt").to(DEVICE)
 
 
 
116
 
117
+ # 3. Model Inference (No Gradient Tracking)
118
+ with torch.no_grad():
119
  logits = model(**inputs).logits
120
  probs = torch.softmax(logits, dim=-1)
121
 
122
+ # 4. Map result to confidence and label
123
  confidence, pred_idx = torch.max(probs, dim=-1)
 
 
124
  label = LABEL_MAP.get(int(pred_idx.item()), "UNKNOWN")
125
 
126
  return {
127
  "classification": label,
128
  "confidence_score": round(float(confidence.item()), 4)
129
  }
130
+
131
  except ValueError as ve:
132
  raise HTTPException(status_code=400, detail=str(ve))
133
  except Exception as e:
134
+ logger.exception("Inference error occurred")
135
+ raise HTTPException(status_code=500, detail="Internal server error.")
136
 
137
  if __name__ == "__main__":
138
+ # Standard port for Hugging Face Spaces
139
  uvicorn.run("app:app", host="0.0.0.0", port=7860)