pgdev0410 commited on
Commit
d57f5f4
·
verified ·
1 Parent(s): dea4d13

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +217 -0
  2. config.py +39 -0
  3. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
+ import torch
4
+ import requests
5
+ import os
6
+
7
+ # ============================================
8
+ # MODEL SETUP - BharatGen Param-1 Instruct
9
+ # ============================================
10
+
11
+ print("Loading BharatGen Param-1...")
12
+
13
+ # Use Instruct version for better responses
14
+ PARAM1_MODEL = "bharatgenai/Param-1-2.9B-Instruct"
15
+ HF_TOKEN = os.getenv("HF_TOKEN")
16
+
17
+ # Load tokenizer and model
18
+ tokenizer = AutoTokenizer.from_pretrained(PARAM1_MODEL, trust_remote_code=True)
19
+ model = AutoModelForCausalLM.from_pretrained(
20
+ PARAM1_MODEL,
21
+ trust_remote_code=True,
22
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
23
+ device_map="auto",
24
+ low_cpu_mem_usage=True
25
+ )
26
+
27
+ # STT Model - AI4Bharat IndicConformer
28
+ STT_API = "https://api-inference.huggingface.co/models/ai4bharat/conformer_multilingual"
29
+
30
+ # ============================================
31
+ # SYSTEM PROMPT FOR WOMEN EMPOWERMENT
32
+ # ============================================
33
+
34
+ SYSTEM_PROMPT = """आप एक सहायक AI हैं जो भारतीय महिलाओं की सुरक्षा और सशक्तिकरण के लिए बनाई गई है।
35
+
36
+ निम्नलिखित विश्लेषण प्रदान करें:
37
+ 1. भावना श्रेणी (Emergency/Distress/Help Needed/Support/Positive)
38
+ 2. सहानुभूतिपूर्ण प्रतिक्रिया (1-2 वाक्य)
39
+ 3. 2-3 ठोस कार्रवाई
40
+ 4. प्रासंगिक हेल्पलाइन (यदि आवश्यक हो)
41
+
42
+ महत्वपूर्ण हेल्पलाइन:
43
+ - महिला हेल्पलाइन: 181
44
+ - पुलिस आपातकाल: 100, 112
45
+ - मानसिक स्वास्थ्य: NIMHANS 080-46110007
46
+
47
+ उत्तर संक्षिप्त, व्यावहारिक और सहायक हो।"""
48
+
49
+ # ============================================
50
+ # CORE FUNCTIONS
51
+ # ============================================
52
+
53
+ def transcribe_audio(audio_path):
54
+ """Convert speech to text using IndicConformer"""
55
+ try:
56
+ with open(audio_path, "rb") as f:
57
+ data = f.read()
58
+
59
+ response = requests.post(
60
+ STT_API,
61
+ headers={"Authorization": f"Bearer {HF_TOKEN}"},
62
+ data=data,
63
+ timeout=30
64
+ )
65
+
66
+ result = response.json()
67
+
68
+ # Handle different response formats
69
+ if isinstance(result, dict) and "text" in result:
70
+ return result["text"]
71
+ elif isinstance(result, list) and len(result) > 0:
72
+ return result[0].get("text", "")
73
+ else:
74
+ return ""
75
+
76
+ except Exception as e:
77
+ print(f"STT Error: {e}")
78
+ return ""
79
+
80
+ def analyze_sentiment_and_suggest(text):
81
+ """Use BharatGen Param-1 for sentiment analysis and suggestions"""
82
+ try:
83
+ # Create prompt for BharatGen
84
+ prompt = f"""{SYSTEM_PROMPT}
85
+
86
+ महिला का कथन: {text}
87
+
88
+ विश्लेषण और सुझाव:"""
89
+
90
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
91
+
92
+ with torch.no_grad():
93
+ outputs = model.generate(
94
+ **inputs,
95
+ max_new_tokens=250,
96
+ do_sample=True,
97
+ top_k=50,
98
+ top_p=0.95,
99
+ temperature=0.7,
100
+ eos_token_id=tokenizer.eos_token_id,
101
+ pad_token_id=tokenizer.pad_token_id
102
+ )
103
+
104
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
105
+
106
+ # Extract only the response after the prompt
107
+ response = generated_text.split("विश्लेषण और सुझाव:")[-1].strip()
108
+
109
+ return response
110
+
111
+ except Exception as e:
112
+ print(f"Analysis Error: {e}")
113
+ return f"⚠️ विश्लेषण में त्रुटि। कृपया पुनः प्रयास करें।\nError: {str(e)}"
114
+
115
+ def process_voice_input(audio):
116
+ """Main pipeline: Voice → Text → Analysis → Suggestions"""
117
+
118
+ if audio is None:
119
+ return "⚠️ कृपया अपनी आवाज़ रिकॉर्ड करें।\n⚠️ Please record your voice."
120
+
121
+ try:
122
+ # Step 1: Speech to Text
123
+ print("Converting speech to text...")
124
+ transcribed_text = transcribe_audio(audio)
125
+
126
+ if not transcribed_text or len(transcribed_text.strip()) < 3:
127
+ return """⚠️ आपकी आवाज़ स्पष्ट नहीं सुनाई दी। कृपया फिर से बोलें।
128
+ ⚠️ Could not understand your voice clearly. Please speak again."""
129
+
130
+ # Step 2: Sentiment Analysis and Suggestions
131
+ print(f"Analyzing: {transcribed_text}")
132
+ suggestions = analyze_sentiment_and_suggest(transcribed_text)
133
+
134
+ # Format output
135
+ output = f"""📝 **आपने कहा / What you said:**
136
+ {transcribed_text}
137
+
138
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
139
+
140
+ 🤖 **विश्लेषण और सुझाव / Analysis & Suggestions:**
141
+ {suggestions}
142
+
143
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
144
+
145
+ 📞 **आपातकालीन संपर्क / Emergency Contacts:**
146
+ • महिला हेल्पलाइन: 181
147
+ • पुलिस आपातकाल: 100, 112
148
+ • मानसिक स्वास्थ्य: 080-46110007
149
+ """
150
+
151
+ return output
152
+
153
+ except Exception as e:
154
+ return f"""❌ त्रुटि / Error: {str(e)}
155
+
156
+ कृपया पुनः प्रयास करें या सीधे 181 पर कॉल करें।
157
+ Please try again or call 181 directly for immediate help."""
158
+
159
+ # ============================================
160
+ # GRADIO INTERFACE
161
+ # ============================================
162
+
163
+ # Custom CSS for better UI
164
+ custom_css = """
165
+ .gradio-container {
166
+ font-family: 'Inter', sans-serif;
167
+ }
168
+ .output-box {
169
+ font-size: 16px;
170
+ line-height: 1.6;
171
+ }
172
+ """
173
+
174
+ # Create interface
175
+ demo = gr.Interface(
176
+ fn=process_voice_input,
177
+ inputs=gr.Audio(
178
+ sources=["microphone"],
179
+ type="filepath",
180
+ label="🎤 अपनी आवाज़ रिकॉर्ड करें / Record Your Voice",
181
+ show_label=True
182
+ ),
183
+ outputs=gr.Textbox(
184
+ label="📋 विश्लेषण और सुझाव / Analysis & Suggestions",
185
+ lines=20,
186
+ show_label=True,
187
+ elem_classes="output-box"
188
+ ),
189
+ title="🌸 महिला सशक्तिकरण सहायक / Women Empowerment Assistant",
190
+ description="""
191
+ **हिंदी और अंग्रेजी में बोलें | Speak in Hindi or English**
192
+
193
+ यह एक AI-आधारित सहायक है जो महिलाओं की चिंताओं को सुनता है और व्यावहारिक सुझाव देता है।
194
+
195
+ *This AI assistant listens to women's concerns and provides actionable suggestions.*
196
+
197
+ 🔒 **गोपनीयता:** आपकी आवाज़ सुरक्षित है। | Your voice is secure.
198
+ """,
199
+ theme=gr.themes.Soft(
200
+ primary_hue="pink",
201
+ secondary_hue="purple"
202
+ ),
203
+ examples=[],
204
+ css=custom_css,
205
+ allow_flagging="never"
206
+ )
207
+
208
+ # ============================================
209
+ # LAUNCH
210
+ # ============================================
211
+
212
+ if __name__ == "__main__":
213
+ demo.launch(
214
+ share=False,
215
+ server_name="0.0.0.0",
216
+ server_port=7860
217
+ )
config.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration file for Women Empowerment Voice Assistant
3
+ """
4
+
5
+ # Model Configuration
6
+ BHARATGEN_MODEL = "bharatgenai/Param-1-2.9B-Instruct"
7
+ STT_MODEL = "ai4bharat/conformer_multilingual"
8
+
9
+ # Supported Languages (current)
10
+ SUPPORTED_LANGUAGES = [
11
+ "Hindi (हिंदी)",
12
+ "English (अंग्रेजी)",
13
+ "Marathi (मराठी)",
14
+ "Tamil (தமிழ்)",
15
+ "Malayalam (മലയാളം)",
16
+ "Bengali (বাংলা)",
17
+ "Punjabi (ਪੰਜਾਬੀ)",
18
+ "Gujarati (ગુજરાતી)",
19
+ "Telugu (తెలుగు)",
20
+ "Kannada (ಕನ್ನಡ)"
21
+ ]
22
+
23
+ # Emergency Contacts
24
+ HELPLINES = {
25
+ "women_helpline": "181",
26
+ "police_emergency": "100, 112",
27
+ "child_helpline": "1098",
28
+ "mental_health": "080-46110007",
29
+ "domestic_violence": "181"
30
+ }
31
+
32
+ # Generation Parameters
33
+ GEN_CONFIG = {
34
+ "max_new_tokens": 250,
35
+ "temperature": 0.7,
36
+ "top_k": 50,
37
+ "top_p": 0.95,
38
+ "do_sample": True
39
+ }
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio==4.44.0
2
+ transformers==4.45.0
3
+ torch==2.4.0
4
+ accelerate==0.34.0
5
+ requests==2.32.0
6
+ soundfile==0.12.1
7
+ librosa==0.10.1
8
+ sentencepiece==0.2.0