Jitender1278 commited on
Commit
48a45c6
Β·
verified Β·
1 Parent(s): 6c5ac9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -83
app.py CHANGED
@@ -381,22 +381,22 @@ class FoduucomStyleBabyCryClassifier:
381
  # Initialize classifier
382
  classifier = FoduucomStyleBabyCryClassifier()
383
 
384
- def predict_api(audio_url):
385
  """
386
- Main API function - this will be the primary API endpoint
387
  """
388
- print(f"πŸ” API Call received: {audio_url}")
389
 
390
- if not audio_url:
391
  return {"success": False, "error": "No audio URL provided"}
392
 
393
  result = classifier.predict(audio_url)
394
- print(f"βœ… API Result: {result.get('prediction', 'error')}")
395
 
396
  return result
397
 
398
  def web_interface_predict(audio_file):
399
- """Web interface function"""
400
  if audio_file is None:
401
  return "❌ No audio file provided", "{}"
402
 
@@ -441,96 +441,112 @@ def web_interface_predict(audio_file):
441
 
442
  return summary, json.dumps(result, indent=2)
443
 
444
- # Create the main Gradio Blocks interface
445
- with gr.Blocks(title="🍼 Baby Cry Classifier - HF API Ready", theme=gr.themes.Soft()) as demo:
446
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  gr.HTML("""
448
  <div style="text-align: center; margin-bottom: 20px;">
449
  <h1>🍼 Baby Cry Classifier</h1>
450
- <p><em>βœ… FIXED: Now Works with HuggingFace API!</em></p>
451
  </div>
452
  """)
453
 
454
- with gr.Tab("🌐 API Interface"):
455
- gr.Markdown("### Use this interface for API calls")
456
-
457
- with gr.Row():
458
- with gr.Column():
459
- api_url_input = gr.Textbox(
460
- label="Audio URL",
461
- placeholder="https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3",
462
- info="Enter the URL of an audio file to analyze"
463
- )
464
- api_submit_btn = gr.Button("πŸ” Analyze Audio", variant="primary")
465
-
466
- with gr.Column():
467
- api_output = gr.JSON(label="Analysis Result")
468
-
469
- # This creates the API endpoint
470
- api_submit_btn.click(
471
- fn=predict_api,
472
- inputs=[api_url_input],
473
- outputs=[api_output],
474
- api_name="predict" # This creates the /predict endpoint
475
- )
476
-
477
- gr.Examples(
478
- examples=[["https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3"]],
479
- inputs=[api_url_input]
480
- )
481
 
482
- with gr.Tab("πŸ“ File Upload"):
483
- gr.Markdown("### Upload audio files directly")
484
-
485
- with gr.Row():
486
- with gr.Column():
487
- file_input = gr.Audio(label="Upload Baby Cry Audio", type="filepath")
488
- file_submit_btn = gr.Button("πŸ” Analyze Upload", variant="primary")
489
-
490
- with gr.Column():
491
- file_summary_output = gr.Markdown(label="Analysis Summary")
492
- file_json_output = gr.Code(label="JSON Data", language="json")
493
-
494
- file_submit_btn.click(
495
- fn=web_interface_predict,
496
- inputs=[file_input],
497
- outputs=[file_summary_output, file_json_output]
498
- )
499
-
500
- with gr.Tab("πŸ“– API Documentation"):
501
  gr.Markdown("""
502
- ## πŸ”— HuggingFace API Usage
503
 
504
- **βœ… WORKING Curl Command:**
505
- ```bash
506
- curl -X POST \
507
- -H "Content-Type: application/json" \
508
- --data '{"data": ["https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3"]}' \
509
- https://jitender1278-babycry.hf.space/call/predict
510
- ```
511
 
512
- **Alternative with session_hash:**
513
- ```bash
514
- curl -X POST \
515
- -H "Content-Type: application/json" \
516
- --data '{"data": ["https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3"], "session_hash": "demo123"}' \
517
- https://jitender1278-babycry.hf.space/run/predict
518
- ```
519
 
520
- **Python Client (Recommended):**
521
  ```python
522
  from gradio_client import Client
523
 
524
- client = Client("https://jitender1278-babycry.hf.space")
 
 
 
525
  result = client.predict(
526
  "https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3",
527
  api_name="/predict"
528
  )
 
529
  print(result)
530
  ```
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  ## πŸ“ Response Format
533
- The API returns a JSON object with the following structure:
534
 
535
  ```json
536
  {
@@ -548,23 +564,35 @@ with gr.Blocks(title="🍼 Baby Cry Classifier - HF API Ready", theme=gr.themes.
548
  "immediate": "Offer feeding - check if it's been 2-3 hours since last meal",
549
  "details": "Look for additional hunger cues: rooting reflex, sucking motions, bringing hands to mouth"
550
  },
551
- "timestamp": "2025-06-12T12:00:00",
552
- "session_id": "abc123",
553
  "model_info": "foduucom-style implementation"
554
  }
555
  ```
556
 
557
- ## 🚨 Important Notes
558
- - Use `/call/predict` for the primary API endpoint
559
- - The API accepts audio file URLs (not file uploads via curl)
560
- - Supported audio formats: MP3, WAV, M4A, FLAC
 
 
 
 
561
  - Maximum file size: ~10MB
562
- - Response time: 5-15 seconds depending on audio length
 
 
 
 
 
 
563
  """)
564
 
565
  if __name__ == "__main__":
566
- print("πŸš€ Starting Baby Cry Classifier with HuggingFace API support...")
567
- demo.launch(
 
 
568
  server_name="0.0.0.0",
569
  server_port=7860,
570
  show_error=True
 
381
  # Initialize classifier
382
  classifier = FoduucomStyleBabyCryClassifier()
383
 
384
+ def predict_baby_cry(audio_url):
385
  """
386
+ Main prediction function for API and UI
387
  """
388
+ print(f"πŸ” Prediction request: {audio_url}")
389
 
390
+ if not audio_url or audio_url.strip() == "":
391
  return {"success": False, "error": "No audio URL provided"}
392
 
393
  result = classifier.predict(audio_url)
394
+ print(f"βœ… Prediction result: {result.get('prediction', 'error')}")
395
 
396
  return result
397
 
398
  def web_interface_predict(audio_file):
399
+ """Web interface function for file uploads"""
400
  if audio_file is None:
401
  return "❌ No audio file provided", "{}"
402
 
 
441
 
442
  return summary, json.dumps(result, indent=2)
443
 
444
+ # Create a simple Interface that will work with HuggingFace API
445
+ api_interface = gr.Interface(
446
+ fn=predict_baby_cry,
447
+ inputs=gr.Textbox(
448
+ label="Audio URL",
449
+ placeholder="https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3",
450
+ info="Enter the URL of an audio file to analyze"
451
+ ),
452
+ outputs=gr.JSON(label="Baby Cry Analysis"),
453
+ title="🍼 Baby Cry Classifier - API Ready",
454
+ description="Analyze baby cries to understand what your baby needs. This interface works with both UI and API calls.",
455
+ examples=[
456
+ ["https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3"]
457
+ ]
458
+ )
459
+
460
+ # Create a file upload interface
461
+ upload_interface = gr.Interface(
462
+ fn=web_interface_predict,
463
+ inputs=gr.Audio(label="Upload Baby Cry Audio", type="filepath"),
464
+ outputs=[
465
+ gr.Markdown(label="Analysis Summary"),
466
+ gr.Code(label="JSON Data", language="json")
467
+ ],
468
+ title="🍼 Baby Cry Classifier - File Upload",
469
+ description="Upload an audio file directly to analyze baby cries."
470
+ )
471
+
472
+ # Combine interfaces
473
+ demo = gr.TabbedInterface(
474
+ [api_interface, upload_interface],
475
+ ["🌐 API Interface", "πŸ“ File Upload"],
476
+ title="🍼 Baby Cry Classifier"
477
+ )
478
+
479
+ # Add documentation as a separate Blocks interface
480
+ with gr.Blocks() as full_demo:
481
  gr.HTML("""
482
  <div style="text-align: center; margin-bottom: 20px;">
483
  <h1>🍼 Baby Cry Classifier</h1>
484
+ <p><em>βœ… API Ready - Use Python Client for Best Results!</em></p>
485
  </div>
486
  """)
487
 
488
+ # Render the main demo
489
+ demo.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
 
491
+ # Add documentation
492
+ with gr.Accordion("πŸ“– API Documentation & Usage", open=True):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  gr.Markdown("""
494
+ ## 🚨 Important: HuggingFace API Limitations
495
 
496
+ **HuggingFace Spaces no longer supports direct curl commands** due to their queue system.
497
+ Here are the working alternatives:
 
 
 
 
 
498
 
499
+ ## βœ… Method 1: Python Client (RECOMMENDED)
 
 
 
 
 
 
500
 
 
501
  ```python
502
  from gradio_client import Client
503
 
504
+ # Initialize client
505
+ client = Client("https://jitender1278-babycry.hf.space/")
506
+
507
+ # Make prediction
508
  result = client.predict(
509
  "https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3",
510
  api_name="/predict"
511
  )
512
+
513
  print(result)
514
  ```
515
 
516
+ ## βœ… Method 2: JavaScript/Node.js
517
+
518
+ ```javascript
519
+ import { Client } from "@gradio/client";
520
+
521
+ const client = await Client.connect("https://jitender1278-babycry.hf.space/");
522
+ const result = await client.predict("/predict", {
523
+ audio_url: "https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3"
524
+ });
525
+
526
+ console.log(result.data);
527
+ ```
528
+
529
+ ## βœ… Method 3: Python Requests (Alternative)
530
+
531
+ ```python
532
+ import requests
533
+ import json
534
+
535
+ # This uses the gradio_client internally
536
+ from gradio_client import Client
537
+
538
+ def analyze_baby_cry(audio_url):
539
+ client = Client("https://jitender1278-babycry.hf.space/")
540
+ result = client.predict(audio_url, api_name="/predict")
541
+ return result
542
+
543
+ # Usage
544
+ audio_url = "https://raw.githubusercontent.com/jiten-kmar/python-projects/main/baby-crying-32232.mp3"
545
+ analysis = analyze_baby_cry(audio_url)
546
+ print(json.dumps(analysis, indent=2))
547
+ ```
548
+
549
  ## πŸ“ Response Format
 
550
 
551
  ```json
552
  {
 
564
  "immediate": "Offer feeding - check if it's been 2-3 hours since last meal",
565
  "details": "Look for additional hunger cues: rooting reflex, sucking motions, bringing hands to mouth"
566
  },
567
+ "timestamp": "2025-06-12T12:00:00.000000",
568
+ "session_id": "abc12345",
569
  "model_info": "foduucom-style implementation"
570
  }
571
  ```
572
 
573
+ ## πŸ”§ Installation
574
+
575
+ ```bash
576
+ pip install gradio-client
577
+ ```
578
+
579
+ ## πŸ“‹ Supported Audio Formats
580
+ - MP3, WAV, M4A, FLAC, OGG
581
  - Maximum file size: ~10MB
582
+ - Audio URLs must be publicly accessible
583
+
584
+ ## ⚠️ Why Curl Doesn't Work
585
+ HuggingFace Spaces now uses a queue system that requires WebSocket connections for real-time processing.
586
+ Direct HTTP POST requests are blocked to prevent abuse and ensure fair resource allocation.
587
+
588
+ Use the Python client above for the best API experience!
589
  """)
590
 
591
  if __name__ == "__main__":
592
+ print("πŸš€ Starting Baby Cry Classifier...")
593
+ print("πŸ“ Note: Use Python gradio_client for API access (curl not supported)")
594
+
595
+ full_demo.launch(
596
  server_name="0.0.0.0",
597
  server_port=7860,
598
  show_error=True