OfficerRaccoon commited on
Commit
c2a23ac
Β·
verified Β·
1 Parent(s): 7e6138e

Update app.py

Browse files

fully modified code

Files changed (1) hide show
  1. app.py +75 -77
app.py CHANGED
@@ -250,92 +250,90 @@ def main():
250
  # Prediction button
251
  if st.button("πŸ” Identify Bird Species", type="primary", use_container_width=True):
252
  with st.spinner("πŸ”„ Processing audio and making prediction..."):
253
- # Process button
254
- # Process button
255
- if st.button("πŸ” Identify Bird Species", type="primary", use_container_width=True):
256
- with st.spinner("πŸ”„ Processing audio and making prediction..."):
257
  try:
258
- # Get the uploaded file bytes
259
- audio_bytes = uploaded_file.getvalue()
 
 
 
 
260
 
261
- # Save to a specific location
262
- temp_dir = "/tmp"
263
- temp_filename = f"uploaded_audio_{hash(audio_bytes) % 10000}.wav"
264
- temp_path = os.path.join(temp_dir, temp_filename)
265
 
266
- # Write file
267
- with open(temp_path, 'wb') as f:
268
- f.write(audio_bytes)
 
269
 
270
- # Verify file exists
271
- if os.path.exists(temp_path) and os.path.getsize(temp_path) > 0:
272
- st.write(f"βœ… Audio file saved: {os.path.getsize(temp_path)} bytes")
273
-
274
- # Process audio
275
- spectrogram = preprocess_audio(temp_path)
276
-
277
- # Rest of your processing code...
278
-
279
- else:
280
- st.error("❌ Failed to save audio file")
281
-
282
- except Exception as e:
283
- st.error(f"❌ Error: {str(e)}")
284
-
285
-
286
-
287
- # Process and predict
288
- spectrogram = preprocess_audio(tmp_file_path)
289
-
290
- if spectrogram is not None:
291
- predicted_species, confidence, top3_predictions = predict_bird_species(
292
- model, spectrogram, label_encoder, device
293
- )
294
 
295
- # Clean up
296
- os.unlink(tmp_file_path)
297
 
298
- if predicted_species is not None:
299
- # Display results
300
- st.success("πŸŽ‰ Prediction Complete!")
 
301
 
302
- # Main prediction
303
- st.subheader("πŸ† Primary Prediction")
304
- clean_species = predicted_species.replace("_sound", "").replace("_", " ")
 
 
305
 
306
- col1, col2 = st.columns([2, 1])
307
- with col1:
308
- st.metric(
309
- label="Predicted Species",
310
- value=clean_species,
311
- delta=f"{confidence:.1%} confidence"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  )
313
-
314
- with col2:
315
- if confidence > 0.8:
316
- st.success("🎯 High Confidence")
317
- elif confidence > 0.6:
318
- st.warning("⚠️ Moderate Confidence")
319
- else:
320
- st.info("πŸ’­ Low Confidence")
321
-
322
- # Top 3 predictions
323
- st.subheader("πŸ“Š Alternative Predictions")
324
- for i, (species, prob) in enumerate(top3_predictions):
325
- clean_name = species.replace("_sound", "").replace("_", " ")
326
- st.write(f"**{i+1}.** {clean_name}")
327
- st.progress(prob)
328
- st.caption(f"Confidence: {prob:.1%}")
329
-
330
- # Conservation note
331
- st.subheader("🌿 Conservation Impact")
332
- st.info(
333
- f"Identifying '{clean_species}' helps with biodiversity monitoring "
334
- "and conservation efforts in national parks and protected areas."
335
- )
336
-
337
- else:
338
- st.error("❌ Failed to process audio file.")
339
 
340
  # Footer
341
  st.markdown("---")
 
250
  # Prediction button
251
  if st.button("πŸ” Identify Bird Species", type="primary", use_container_width=True):
252
  with st.spinner("πŸ”„ Processing audio and making prediction..."):
 
 
 
 
253
  try:
254
+ # Create temporary file with proper handling
255
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
256
+ # Write the uploaded file data
257
+ tmp_file.write(uploaded_file.getvalue())
258
+ tmp_file.flush() # Ensure data is written
259
+ tmp_file_path = tmp_file.name
260
 
261
+ # Verify file was created successfully
262
+ if not os.path.exists(tmp_file_path):
263
+ st.error("❌ Failed to create temporary file")
264
+ return
265
 
266
+ file_size = os.path.getsize(tmp_file_path)
267
+ if file_size == 0:
268
+ st.error("❌ Temporary file is empty")
269
+ return
270
 
271
+ st.write(f"βœ… Temporary file created: {file_size} bytes")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
+ # Process audio
274
+ spectrogram = preprocess_audio(tmp_file_path)
275
 
276
+ if spectrogram is not None:
277
+ predicted_species, confidence, top3_predictions = predict_bird_species(
278
+ model, spectrogram, label_encoder, device
279
+ )
280
 
281
+ # Clean up temp file
282
+ try:
283
+ os.unlink(tmp_file_path)
284
+ except:
285
+ pass # Ignore cleanup errors
286
 
287
+ # Display results
288
+ if predicted_species is not None:
289
+ st.success("πŸŽ‰ Prediction Complete!")
290
+
291
+ # Main prediction
292
+ st.subheader("πŸ† Primary Prediction")
293
+ clean_species = predicted_species.replace("_sound", "").replace("_", " ")
294
+
295
+ col1, col2 = st.columns([2, 1])
296
+ with col1:
297
+ st.metric(
298
+ label="Predicted Species",
299
+ value=clean_species,
300
+ delta=f"{confidence:.1%} confidence"
301
+ )
302
+
303
+ with col2:
304
+ if confidence > 0.8:
305
+ st.success("🎯 High Confidence")
306
+ elif confidence > 0.6:
307
+ st.warning("⚠️ Moderate Confidence")
308
+ else:
309
+ st.info("πŸ’­ Low Confidence")
310
+
311
+ # Top 3 predictions
312
+ st.subheader("πŸ“Š Alternative Predictions")
313
+ for i, (species, prob) in enumerate(top3_predictions):
314
+ clean_name = species.replace("_sound", "").replace("_", " ")
315
+ st.write(f"**{i+1}.** {clean_name}")
316
+ st.progress(prob)
317
+ st.caption(f"Confidence: {prob:.1%}")
318
+
319
+ # Conservation note
320
+ st.subheader("🌿 Conservation Impact")
321
+ st.info(
322
+ f"Identifying '{clean_species}' helps with biodiversity monitoring "
323
+ "and conservation efforts in national parks and protected areas."
324
  )
325
+
326
+ else:
327
+ st.error("❌ Failed to process audio file.")
328
+
329
+ except Exception as e:
330
+ st.error(f"❌ Error processing audio: {str(e)}")
331
+ # Clean up on error
332
+ try:
333
+ if 'tmp_file_path' in locals():
334
+ os.unlink(tmp_file_path)
335
+ except:
336
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
  # Footer
339
  st.markdown("---")