-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
295 lines (254 loc) · 11.1 KB
/
app.py
File metadata and controls
295 lines (254 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import json
import re
import os
import requests
from datetime import datetime
app = Flask(__name__)
CORS(app) # Enable CORS for all routes
# Sarvam AI Configuration
SARVAM_API_KEY = os.getenv('SARVAM_API_KEY', 'your-sarvam-api-key-here')
SARVAM_BASE_URL = 'https://api.sarvam.ai/v1'
# Sample contacts database
CONTACTS = {
"sandeep": {"name": "Sandeep", "upi_id": "sandeep@paytm", "phone": "9999999999"},
"priya": {"name": "Priya", "upi_id": "priya@gpay", "phone": "8888888888"},
"rahul": {"name": "Rahul", "upi_id": "rahul@phonepe", "phone": "7777777777"}
}
# Transaction log
TRANSACTIONS = []
class VoicePaymentProcessor:
def __init__(self):
self.amount_patterns = [
r'(\d+)\s*(?:rupees?|rs\.?|₹)',
r'(?:rupees?|rs\.?|₹)\s*(\d+)',
r'(\d+)',
r'(one hundred|two hundred|three hundred|four hundred|five hundred|thousand)',
]
self.payment_patterns = [
r'(?:send|pay|transfer|give)\s+(?:rupees?\s*)?(\d+|one hundred|two hundred|three hundred|four hundred|five hundred|thousand)(?:\s*rupees?)?\s+(?:to\s+)?(\w+)(?:\s+for\s+(.*))?',
r'(?:send|pay|transfer|give)\s+(\w+)\s+(?:rupees?\s*)?(\d+|one hundred|two hundred|three hundred|four hundred|five hundred|thousand)(?:\s*rupees?)(?:\s+for\s+(.*))?',
r'pay\s+(\w+)\s+(?:rupees?\s*)?(\d+|one hundred|two hundred|three hundred|four hundred|five hundred|thousand)(?:\s*rupees?)?\s+for\s+(.*)',
r'(\d+)\s*(?:rupees?|rs\.?|₹)\s+(?:to\s+)?(\w+)(?:\s+for\s+(.*))?',
]
def enhance_with_sarvam_ai(self, text):
"""Use Sarvam AI for better text understanding"""
# Skip if no API key is configured
if SARVAM_API_KEY == 'your-sarvam-api-key-here' or not SARVAM_API_KEY:
print("Sarvam AI API key not configured, using fallback processing")
return None
try:
headers = {
'Authorization': f'Bearer {SARVAM_API_KEY}',
'Content-Type': 'application/json'
}
payload = {
'model': 'sarvam-2.0',
'messages': [
{
'role': 'system',
'content': 'You are a payment intent classifier. Extract amount, recipient name, and reason from payment commands. Respond in JSON format with fields: amount (number), recipient (string), reason (string or null).'
},
{
'role': 'user',
'content': f'Extract payment details from: "{text}"'
}
],
'max_tokens': 100,
'temperature': 0.1
}
response = requests.post(
f'{SARVAM_BASE_URL}/chat/completions',
headers=headers,
json=payload,
timeout=5
)
if response.status_code == 200:
result = response.json()
ai_response = result['choices'][0]['message']['content']
try:
return json.loads(ai_response)
except json.JSONDecodeError:
print("Failed to parse AI response as JSON")
pass
else:
print(f"Sarvam AI API error: {response.status_code}")
except requests.exceptions.Timeout:
print("Sarvam AI request timed out")
except requests.exceptions.ConnectionError:
print("Cannot connect to Sarvam AI - using fallback")
except Exception as e:
print(f"Sarvam AI error: {e}")
return None
def extract_amount(self, text):
"""Extract amount from text"""
text = text.lower()
# Word to number mapping
word_to_num = {
'one hundred': 100, 'hundred': 100,
'two hundred': 200, 'three hundred': 300,
'four hundred': 400, 'five hundred': 500,
'thousand': 1000, 'one thousand': 1000
}
for pattern in self.amount_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
amount_str = match.group(1)
if amount_str in word_to_num:
return word_to_num[amount_str]
elif amount_str.isdigit():
return int(amount_str)
return None
def extract_contact(self, text):
"""Extract contact name from text"""
text = text.lower()
for contact_key, contact_info in CONTACTS.items():
if contact_key in text or contact_info['name'].lower() in text:
return contact_info
return None
def process_voice_command(self, text):
"""Process voice command and extract payment intent"""
original_text = text
text = text.lower().strip()
# First try Sarvam AI for better understanding
ai_result = self.enhance_with_sarvam_ai(original_text)
if ai_result:
amount = ai_result.get('amount')
recipient_name = ai_result.get('recipient')
reason = ai_result.get('reason')
# Find contact by name
contact = None
if recipient_name:
for contact_key, contact_info in CONTACTS.items():
if (contact_key.lower() == recipient_name.lower() or
contact_info['name'].lower() == recipient_name.lower()):
contact = contact_info
break
if amount and contact:
return {
'success': True,
'amount': amount,
'contact': contact,
'reason': reason,
'message': f"Confirming payment of {amount} rupees to {contact['name']}" +
(f" for {reason}" if reason else "") + ". Say 'confirm' to proceed."
}
# Fallback to enhanced pattern matching
amount = None
contact = None
reason = None
# Try enhanced pattern matching
for pattern in self.payment_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
groups = match.groups()
if len(groups) >= 2:
# Check if first group is amount or contact
if groups[0].replace('hundred', '').replace('thousand', '').replace(' ', '').isdigit() or groups[0] in ['one hundred', 'two hundred', 'three hundred', 'four hundred', 'five hundred', 'thousand']:
amount_str = groups[0]
contact_name = groups[1]
reason = groups[2] if len(groups) > 2 and groups[2] else None
else:
contact_name = groups[0]
amount_str = groups[1]
reason = groups[2] if len(groups) > 2 and groups[2] else None
# Convert amount
word_to_num = {
'one hundred': 100, 'hundred': 100,
'two hundred': 200, 'three hundred': 300,
'four hundred': 400, 'five hundred': 500,
'thousand': 1000, 'one thousand': 1000
}
if amount_str in word_to_num:
amount = word_to_num[amount_str]
elif amount_str.isdigit():
amount = int(amount_str)
# Find contact
for contact_key, contact_info in CONTACTS.items():
if (contact_key.lower() == contact_name.lower() or
contact_info['name'].lower() == contact_name.lower()):
contact = contact_info
break
if amount and contact:
break
# Final fallback to original extraction methods
if not amount:
amount = self.extract_amount(text)
if not contact:
contact = self.extract_contact(text)
if not reason:
reason_match = re.search(r'for\s+(.*)', text)
reason = reason_match.group(1) if reason_match else None
if amount and contact:
return {
'success': True,
'amount': amount,
'contact': contact,
'reason': reason,
'message': f"Confirming payment of {amount} rupees to {contact['name']}" +
(f" for {reason}" if reason else "") + ". Say 'confirm' to proceed."
}
elif contact and not amount:
return {
'success': False,
'error': f"How much do you want to send to {contact['name']}?",
'contact': contact
}
elif amount and not contact:
return {
'success': False,
'error': "Who do you want to send the money to?",
'amount': amount
}
else:
return {
'success': False,
'error': "I didn't understand. Try saying 'send 100 rupees to Sandeep'"
}
processor = VoicePaymentProcessor()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process_voice', methods=['POST'])
def process_voice():
data = request.get_json()
text = data.get('text', '')
# Process confirmation
if text.lower() in ['confirm', 'yes', 'proceed', 'ok']:
# Get the last pending transaction from session (simplified)
# In real app, you'd use proper session management
return jsonify({
'success': True,
'message': 'Payment successful!',
'action': 'payment_complete'
})
# Process payment command
result = processor.process_voice_command(text)
return jsonify(result)
@app.route('/execute_payment', methods=['POST'])
def execute_payment():
data = request.get_json()
# Simulate payment processing
transaction = {
'id': len(TRANSACTIONS) + 1,
'amount': data.get('amount'),
'contact': data.get('contact'),
'reason': data.get('reason'),
'timestamp': datetime.now().isoformat(),
'status': 'success'
}
TRANSACTIONS.append(transaction)
return jsonify({
'success': True,
'message': f"Payment of {transaction['amount']} rupees to {transaction['contact']['name']} successful!",
'transaction_id': transaction['id']
})
@app.route('/contacts')
def get_contacts():
return jsonify(list(CONTACTS.values()))
@app.route('/transactions')
def get_transactions():
return jsonify(TRANSACTIONS)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)