RathodHarish commited on
Commit
410fd66
·
verified ·
1 Parent(s): 96b58eb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import librosa
3
+ import numpy as np
4
+ import torch
5
+ from transformers import Wav2Vec2Processor, Wav2Vec2Model
6
+ import requests
7
+ import json
8
+ import os
9
+ from datetime import datetime
10
+
11
+ # Salesforce API credentials (store securely in environment variables)
12
+ SALESFORCE_API_URL = os.getenv("SALESFORCE_API_URL", "https://your-salesforce-instance.salesforce.com/services/data/v60.0/sobjects/HealthAssessment__c")
13
+ SALESFORCE_TOKEN = os.getenv("SALESFORCE_TOKEN", "your_salesforce_token")
14
+
15
+ # Load Wav2Vec2 model for speech feature extraction
16
+ processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
17
+ model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
18
+
19
+ def analyze_voice(audio_file):
20
+ """Analyze voice for health indicators."""
21
+ try:
22
+ # Load audio file
23
+ audio, sr = librosa.load(audio_file, sr=16000)
24
+
25
+ # Process audio for Wav2Vec2
26
+ inputs = processor(audio, sampling_rate=16000, return_tensors="pt", padding=True)
27
+ with torch.no_grad():
28
+ outputs = model(**inputs)
29
+
30
+ # Extract features (simplified for demo; real-world needs trained classifier)
31
+ features = outputs.last_hidden_state.mean(dim=1).numpy()
32
+
33
+ # Placeholder health analysis (replace with trained model)
34
+ respiratory_score = np.mean(features) # Mock score
35
+ mental_health_score = np.std(features) # Mock score
36
+ feedback = ""
37
+ if respiratory_score > 0.5:
38
+ feedback += "Possible respiratory issue detected; consult a doctor. "
39
+ if mental_health_score > 0.3:
40
+ feedback += "Possible stress indicators detected; consider professional advice. "
41
+
42
+ if not feedback:
43
+ feedback = "No significant health indicators detected."
44
+
45
+ feedback += "\n\n**Disclaimer**: This is not a diagnostic tool. Consult a healthcare provider for medical advice."
46
+
47
+ # Store in Salesforce
48
+ store_in_salesforce(audio_file, feedback, respiratory_score, mental_health_score)
49
+
50
+ return feedback
51
+ except Exception as e:
52
+ return f"Error processing audio: {str(e)}"
53
+
54
+ def store_in_salesforce(audio_file, feedback, respiratory_score, mental_health_score):
55
+ """Store analysis results in Salesforce."""
56
+ headers = {
57
+ "Authorization": f"Bearer {SALESFORCE_TOKEN}",
58
+ "Content-Type": "application/json"
59
+ }
60
+ data = {
61
+ "AssessmentDate__c": datetime.utcnow().isoformat(),
62
+ "Feedback__c": feedback,
63
+ "RespiratoryScore__c": float(respiratory_score),
64
+ "MentalHealthScore__c": float(mental_health_score),
65
+ "AudioFileName__c": os.path.basename(audio_file)
66
+ }
67
+ response = requests.post(SALESFORCE_API_URL, headers=headers, json=data)
68
+ if response.status_code != 201:
69
+ print(f"Failed to store in Salesforce: {response.text}")
70
+
71
+ # Gradio interface
72
+ iface = gr.Interface(
73
+ fn=analyze_voice,
74
+ inputs=gr.Audio(type="filepath", label="Record or Upload Voice"),
75
+ outputs=gr.Textbox(label="Health Assessment Feedback"),
76
+ title="Health Voice Analyzer",
77
+ description="Record or upload a voice sample for preliminary health assessment. Supports English, Spanish, Hindi, Mandarin."
78
+ )
79
+
80
+ if __name__ == "__main__":
81
+ iface.launch(server_name="0.0.0.0", server_port=7860)