Trynitzan commited on
Commit
51ac236
·
verified ·
1 Parent(s): 21a2142

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -15
app.py CHANGED
@@ -24,7 +24,7 @@ try:
24
  "ivrit-ai/pyannote-speaker-diarization-3.1",
25
  use_auth_token=HF_TOKEN,
26
  )
27
- pipeline.to(device)
28
  print("✅ Model loaded successfully!")
29
  except Exception as e:
30
  print(f"❌ Failed to load model: {e}")
@@ -65,7 +65,6 @@ def estimate_duration(file_path: str) -> float:
65
  """אומדן אורך קובץ בדקות"""
66
  try:
67
  file_size_mb = os.path.getsize(file_path) / (1024 * 1024)
68
- # אומדן: ~2MB לדקה (ממוצע)
69
  return file_size_mb / 2.0
70
  except Exception:
71
  return 0
@@ -128,39 +127,32 @@ async def diarize(file: UploadFile = File(...)):
128
  wav_path = None
129
 
130
  try:
131
- # קריאת הקובץ
132
  content = await file.read()
133
  file_size_mb = len(content) / (1024 * 1024)
134
 
135
- # בדיקת גודל
136
  if file_size_mb > MAX_FILE_SIZE_MB:
137
  raise HTTPException(
138
  status_code=400,
139
  detail=f"File too large: {file_size_mb:.1f}MB (max: {MAX_FILE_SIZE_MB}MB)"
140
  )
141
 
142
- # בדיקת תור
143
  if active_requests >= MAX_CONCURRENT_REQUESTS:
144
  raise HTTPException(
145
  status_code=503,
146
  detail=f"Server busy ({active_requests}/{MAX_CONCURRENT_REQUESTS} active). Try again later."
147
  )
148
 
149
- # עיבוד
150
  async with processing_semaphore:
151
  active_requests += 1
152
 
153
  try:
154
- # שמירה זמנית
155
  suffix = Path(file.filename).suffix or ".tmp"
156
  with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
157
  tmp.write(content)
158
  tmp_path = tmp.name
159
 
160
- # המרה ל-WAV
161
  wav_path = ensure_wav_16k_mono(tmp_path)
162
 
163
- # אומדן אורך
164
  duration = estimate_duration(wav_path)
165
  if duration > MAX_DURATION_MINUTES:
166
  raise HTTPException(
@@ -168,7 +160,6 @@ async def diarize(file: UploadFile = File(...)):
168
  detail=f"File too long: ~{duration:.1f} min (max: {MAX_DURATION_MINUTES} min)"
169
  )
170
 
171
- # זיהוי דוברים
172
  print(f"🎤 Processing: {file.filename} ({file_size_mb:.1f}MB)")
173
  start_time = datetime.now()
174
 
@@ -177,7 +168,6 @@ async def diarize(file: UploadFile = File(...)):
177
  processing_time = (datetime.now() - start_time).total_seconds()
178
  print(f"✅ Done in {processing_time:.1f}s")
179
 
180
- # בניית תוצאות
181
  segments = []
182
  last_segment = None
183
 
@@ -186,7 +176,6 @@ async def diarize(file: UploadFile = File(...)):
186
  end = round(float(segment.end), 3)
187
  speaker_id = str(speaker)
188
 
189
- # איחוד מקטעים צמודים של אותו דובר
190
  if (last_segment and
191
  last_segment["speaker"] == speaker_id and
192
  abs(start - last_segment["end"]) < 0.1):
@@ -203,7 +192,6 @@ async def diarize(file: UploadFile = File(...)):
203
  if last_segment:
204
  segments.append(last_segment)
205
 
206
- # סינון מקטעים קצרים
207
  segments = [s for s in segments if s["end"] - s["start"] >= 0.2]
208
 
209
  return JSONResponse({
@@ -224,7 +212,6 @@ async def diarize(file: UploadFile = File(...)):
224
  print(f"❌ Error: {str(e)}")
225
  raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}")
226
  finally:
227
- # ניקוי
228
  for path in [tmp_path, wav_path]:
229
  if path and os.path.exists(path):
230
  try:
@@ -235,4 +222,21 @@ async def diarize(file: UploadFile = File(...)):
235
 
236
  if __name__ == "__main__":
237
  import uvicorn
238
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  "ivrit-ai/pyannote-speaker-diarization-3.1",
25
  use_auth_token=HF_TOKEN,
26
  )
27
+ pipeline.to(torch.device(device)) # ✅ תיקון כאן!
28
  print("✅ Model loaded successfully!")
29
  except Exception as e:
30
  print(f"❌ Failed to load model: {e}")
 
65
  """אומדן אורך קובץ בדקות"""
66
  try:
67
  file_size_mb = os.path.getsize(file_path) / (1024 * 1024)
 
68
  return file_size_mb / 2.0
69
  except Exception:
70
  return 0
 
127
  wav_path = None
128
 
129
  try:
 
130
  content = await file.read()
131
  file_size_mb = len(content) / (1024 * 1024)
132
 
 
133
  if file_size_mb > MAX_FILE_SIZE_MB:
134
  raise HTTPException(
135
  status_code=400,
136
  detail=f"File too large: {file_size_mb:.1f}MB (max: {MAX_FILE_SIZE_MB}MB)"
137
  )
138
 
 
139
  if active_requests >= MAX_CONCURRENT_REQUESTS:
140
  raise HTTPException(
141
  status_code=503,
142
  detail=f"Server busy ({active_requests}/{MAX_CONCURRENT_REQUESTS} active). Try again later."
143
  )
144
 
 
145
  async with processing_semaphore:
146
  active_requests += 1
147
 
148
  try:
 
149
  suffix = Path(file.filename).suffix or ".tmp"
150
  with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
151
  tmp.write(content)
152
  tmp_path = tmp.name
153
 
 
154
  wav_path = ensure_wav_16k_mono(tmp_path)
155
 
 
156
  duration = estimate_duration(wav_path)
157
  if duration > MAX_DURATION_MINUTES:
158
  raise HTTPException(
 
160
  detail=f"File too long: ~{duration:.1f} min (max: {MAX_DURATION_MINUTES} min)"
161
  )
162
 
 
163
  print(f"🎤 Processing: {file.filename} ({file_size_mb:.1f}MB)")
164
  start_time = datetime.now()
165
 
 
168
  processing_time = (datetime.now() - start_time).total_seconds()
169
  print(f"✅ Done in {processing_time:.1f}s")
170
 
 
171
  segments = []
172
  last_segment = None
173
 
 
176
  end = round(float(segment.end), 3)
177
  speaker_id = str(speaker)
178
 
 
179
  if (last_segment and
180
  last_segment["speaker"] == speaker_id and
181
  abs(start - last_segment["end"]) < 0.1):
 
192
  if last_segment:
193
  segments.append(last_segment)
194
 
 
195
  segments = [s for s in segments if s["end"] - s["start"] >= 0.2]
196
 
197
  return JSONResponse({
 
212
  print(f"❌ Error: {str(e)}")
213
  raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}")
214
  finally:
 
215
  for path in [tmp_path, wav_path]:
216
  if path and os.path.exists(path):
217
  try:
 
222
 
223
  if __name__ == "__main__":
224
  import uvicorn
225
+ uvicorn.run(app, host="0.0.0.0", port=7860)
226
+ ```
227
+
228
+ ---
229
+
230
+ ## 🚀 עכשיו זה אמור לעבוד!
231
+
232
+ 1. **עדכן את `app.py`** ב-Space
233
+ 2. שמור
234
+ 3. המתן לבנייה (~1-2 דקות - כי יש cache)
235
+ 4. בדוק `/health`
236
+
237
+ אחרי התיקון הזה, אמור לראות בלוגים:
238
+ ```
239
+ 🚀 Loading model on cpu...
240
+ ✅ Model loaded successfully!
241
+ INFO: Started server process
242
+ INFO: Uvicorn running on http://0.0.0.0:7860