geethareddy commited on
Commit
b52c1f7
·
verified ·
1 Parent(s): 1e778ba

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import logging
4
+ import json
5
+ import requests
6
+ import torch
7
+ from flask import Flask, render_template, request, jsonify, session
8
+ from flask_session import Session
9
+ from simple_salesforce import Salesforce
10
+ from transformers import pipeline, AutoConfig
11
+ from gtts import gTTS
12
+ from pydub import AudioSegment
13
+ from pydub.silence import detect_nonsilent
14
+ from waitress import serve
15
+
16
+ app = Flask(__name__)
17
+
18
+ # Configure Flask session
19
+ app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q")
20
+ app.config["SESSION_TYPE"] = "filesystem"
21
+ Session(app)
22
+
23
+ # Set up logging
24
+ logging.basicConfig(level=logging.INFO)
25
+
26
+ # Connect to Salesforce
27
+ try:
28
+ sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
29
+ print("✅ Connected to Salesforce successfully!")
30
+ except Exception as e:
31
+ print(f"❌ Failed to connect to Salesforce: {str(e)}")
32
+
33
+ # Whisper ASR Configuration
34
+ device = "cuda" if torch.cuda.is_available() else "cpu"
35
+ config = AutoConfig.from_pretrained("openai/whisper-small")
36
+ config.update({"timeout": 60})
37
+
38
+ # Voice prompts
39
+ prompts = {
40
+ "welcome": "Welcome to Biryani Hub.",
41
+ "ask_name": "Tell me your name.",
42
+ "ask_email": "Please provide your email address.",
43
+ "thank_you": "Thank you for registration."
44
+ }
45
+
46
+ # Function to generate voice prompts
47
+ def generate_audio_prompt(text, filename):
48
+ try:
49
+ tts = gTTS(text)
50
+ tts.save(os.path.join("static", filename))
51
+ except gtts.tts.gTTSError as e:
52
+ time.sleep(5)
53
+ generate_audio_prompt(text, filename)
54
+
55
+ for key, text in prompts.items():
56
+ generate_audio_prompt(text, f"{key}.mp3")
57
+
58
+ # Function to convert audio to WAV format
59
+ def convert_to_wav(input_path, output_path):
60
+ audio = AudioSegment.from_file(input_path)
61
+ audio = audio.set_frame_rate(16000).set_channels(1)
62
+ audio.export(output_path, format="wav")
63
+
64
+ # Function to check if audio contains actual speech
65
+ def is_silent_audio(audio_path):
66
+ audio = AudioSegment.from_wav(audio_path)
67
+ nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
68
+ return len(nonsilent_parts) == 0
69
+
70
+ @app.route("/")
71
+ def index():
72
+ return render_template("index.html")
73
+
74
+ # ✅ LOGIN ENDPOINT
75
+ @app.route('/login', methods=['POST'])
76
+ def login():
77
+ data = request.json
78
+ email = data.get('email', '').strip().lower()
79
+ phone_number = data.get('phone_number', '').strip()
80
+
81
+ if not email or not phone_number:
82
+ return jsonify({'error': 'Missing email or phone number'}), 400
83
+
84
+ try:
85
+ query = f"SELECT Id, Name FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone_number}' LIMIT 1"
86
+ result = sf.query(query)
87
+
88
+ if result['totalSize'] == 0:
89
+ return jsonify({'error': 'Invalid email or phone number. User not found'}), 401
90
+
91
+ user_data = result['records'][0]
92
+ session['user_id'] = user_data['Id']
93
+ session['name'] = user_data['Name']
94
+
95
+ return jsonify({'success': True, 'message': 'Login successful', 'user_id': user_data['Id'], 'name': user_data['Name']}), 200
96
+
97
+ except Exception as e:
98
+ return jsonify({'error': f'Unexpected error: {str(e)}'}), 500
99
+
100
+ # ✅ REGISTRATION ENDPOINT
101
+ @app.route("/register", methods=["POST"])
102
+ def register():
103
+ data = request.json
104
+ name = data.get('name', '').strip()
105
+ email = data.get('email', '').strip().lower()
106
+ phone = data.get('phone', '').strip()
107
+
108
+ if not name or not email or not phone:
109
+ return jsonify({'error': 'Missing data'}), 400
110
+
111
+ try:
112
+ query = f"SELECT Id FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone}' LIMIT 1"
113
+ existing_user = sf.query(query)
114
+
115
+ if existing_user['totalSize'] > 0:
116
+ return jsonify({'error': 'User already exists'}), 409
117
+
118
+ customer_login = sf.Customer_Login__c.create({
119
+ 'Name': name,
120
+ 'Email__c': email,
121
+ 'Phone_Number__c': phone
122
+ })
123
+
124
+ if customer_login.get('id'):
125
+ return jsonify({'success': True, 'user_id': customer_login['id']}), 200
126
+ else:
127
+ return jsonify({'error': 'Failed to create record'}), 500
128
+
129
+ except Exception as e:
130
+ return jsonify({'error': str(e)}), 500
131
+
132
+ # ✅ TRANSCRIPTION ENDPOINT
133
+ @app.route("/transcribe", methods=["POST"])
134
+ def transcribe():
135
+ if "audio" not in request.files:
136
+ return jsonify({"error": "No audio file provided"}), 400
137
+
138
+ audio_file = request.files["audio"]
139
+ input_audio_path = os.path.join("static", "temp_input.wav")
140
+ output_audio_path = os.path.join("static", "temp.wav")
141
+ audio_file.save(input_audio_path)
142
+
143
+ try:
144
+ convert_to_wav(input_audio_path, output_audio_path)
145
+
146
+ if is_silent_audio(output_audio_path):
147
+ return jsonify({"error": "No speech detected. Please try again."}), 400
148
+
149
+ result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
150
+ transcribed_text = result(output_audio_path)["text"].strip().capitalize()
151
+
152
+ return jsonify({"text": transcribed_text})
153
+
154
+ except Exception as e:
155
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
156
+
157
+ # Start Production Server
158
+ if __name__ == "__main__":
159
+ serve(app, host="0.0.0.0", port=7860)