KrizTech100 commited on
Commit
c30e743
Β·
verified Β·
1 Parent(s): f07e13c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -12
app.py CHANGED
@@ -8,6 +8,7 @@ import json
8
  import csv
9
  import os
10
  import tempfile
 
11
  from datetime import datetime
12
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
13
  import torch.nn.functional as F
@@ -23,15 +24,40 @@ load_dotenv()
23
  aai.settings.api_key = os.getenv("ASSEMBLYAI_API_KEY")
24
  hf_token = os.getenv("HF_TOKEN")
25
 
 
 
 
26
  device = "cuda" if torch.cuda.is_available() else "cpu"
27
 
28
- tokenizer = AutoTokenizer.from_pretrained(
29
- "nlptown/bert-base-multilingual-uncased-sentiment"
30
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- model = AutoModelForSequenceClassification.from_pretrained(
33
- "nlptown/bert-base-multilingual-uncased-sentiment"
34
- )
 
 
 
 
 
 
35
 
36
  model.to(device)
37
  model.eval()
@@ -73,7 +99,12 @@ def build_segments(transcript):
73
 
74
 
75
  def analyze_text(text):
76
- inputs = tokenizer(text[:512], return_tensors="pt", truncation=True).to(device)
 
 
 
 
 
77
 
78
  with torch.no_grad():
79
  logits = model(**inputs).logits
@@ -92,14 +123,13 @@ def process_audio(file, speakers=0, language="auto"):
92
  return "❌ No audio provided", "", ""
93
 
94
  path = file if isinstance(file, str) else file.name
95
-
96
  temp_path = None
97
 
98
  try:
99
  # Load audio
100
  audio, sr = librosa.load(path, sr=None, mono=True)
101
 
102
- # πŸ”₯ Create TEMP FILE (not saved permanently)
103
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
104
  sf.write(tmp.name, audio, sr)
105
  temp_path = tmp.name
@@ -116,7 +146,6 @@ def process_audio(file, speakers=0, language="auto"):
116
  return f"❌ {transcript.error}", "", ""
117
 
118
  global_segments = build_segments(transcript)
119
-
120
  speaker_count = len(set(s["speaker"] for s in global_segments))
121
 
122
  label_map = {
@@ -147,7 +176,6 @@ def process_audio(file, speakers=0, language="auto"):
147
  return f"❌ Error: {str(e)}", "", ""
148
 
149
  finally:
150
- # πŸ”₯ DELETE temp file ALWAYS
151
  if temp_path and os.path.exists(temp_path):
152
  os.remove(temp_path)
153
 
@@ -240,6 +268,5 @@ with gr.Blocks(title="AI Conversation Sentiment System") as app:
240
  outputs=[download]
241
  )
242
 
243
-
244
  if __name__ == "__main__":
245
  app.launch(theme=gr.themes.Soft())
 
8
  import csv
9
  import os
10
  import tempfile
11
+ import time
12
  from datetime import datetime
13
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
14
  import torch.nn.functional as F
 
24
  aai.settings.api_key = os.getenv("ASSEMBLYAI_API_KEY")
25
  hf_token = os.getenv("HF_TOKEN")
26
 
27
+ if not hf_token:
28
+ raise ValueError("❌ HF_TOKEN is missing. Add it to your .env")
29
+
30
  device = "cuda" if torch.cuda.is_available() else "cpu"
31
 
32
+ MODEL_NAME = "nlptown/bert-base-multilingual-uncased-sentiment"
33
+
34
+ # =========================
35
+ # LOAD MODEL (FIXED)
36
+ # =========================
37
+ def load_hf_model():
38
+ for attempt in range(3):
39
+ try:
40
+ tokenizer = AutoTokenizer.from_pretrained(
41
+ MODEL_NAME,
42
+ token=hf_token,
43
+ cache_dir="./models"
44
+ )
45
+
46
+ model = AutoModelForSequenceClassification.from_pretrained(
47
+ MODEL_NAME,
48
+ token=hf_token,
49
+ cache_dir="./models"
50
+ )
51
 
52
+ return tokenizer, model
53
+
54
+ except Exception as e:
55
+ print(f"⚠️ HF load failed (attempt {attempt+1}): {e}")
56
+ time.sleep(5)
57
+
58
+ raise RuntimeError("❌ Failed to load Hugging Face model after retries")
59
+
60
+ tokenizer, model = load_hf_model()
61
 
62
  model.to(device)
63
  model.eval()
 
99
 
100
 
101
  def analyze_text(text):
102
+ inputs = tokenizer(
103
+ text,
104
+ return_tensors="pt",
105
+ truncation=True,
106
+ max_length=512
107
+ ).to(device)
108
 
109
  with torch.no_grad():
110
  logits = model(**inputs).logits
 
123
  return "❌ No audio provided", "", ""
124
 
125
  path = file if isinstance(file, str) else file.name
 
126
  temp_path = None
127
 
128
  try:
129
  # Load audio
130
  audio, sr = librosa.load(path, sr=None, mono=True)
131
 
132
+ # Create TEMP FILE
133
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
134
  sf.write(tmp.name, audio, sr)
135
  temp_path = tmp.name
 
146
  return f"❌ {transcript.error}", "", ""
147
 
148
  global_segments = build_segments(transcript)
 
149
  speaker_count = len(set(s["speaker"] for s in global_segments))
150
 
151
  label_map = {
 
176
  return f"❌ Error: {str(e)}", "", ""
177
 
178
  finally:
 
179
  if temp_path and os.path.exists(temp_path):
180
  os.remove(temp_path)
181
 
 
268
  outputs=[download]
269
  )
270
 
 
271
  if __name__ == "__main__":
272
  app.launch(theme=gr.themes.Soft())