lokesh341 commited on
Commit
c7510fe
Β·
verified Β·
1 Parent(s): a666aaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -32
app.py CHANGED
@@ -18,9 +18,6 @@ app = Flask(__name__)
18
  # Configure Flask session
19
  app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q")
20
  app.config["SESSION_TYPE"] = "filesystem"
21
- app.config["SESSION_COOKIE_NAME"] = "my_session"
22
- app.config["SESSION_COOKIE_SECURE"] = True
23
- app.config["SESSION_COOKIE_SAMESITE"] = "None"
24
  Session(app)
25
 
26
  # Set up logging
@@ -28,18 +25,17 @@ logging.basicConfig(level=logging.INFO)
28
 
29
  # Connect to Salesforce
30
  try:
31
- print("Attempting to connect to Salesforce...")
32
  sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
33
- print("Connected to Salesforce successfully!")
34
  except Exception as e:
35
- print(f"Failed to connect to Salesforce: {str(e)}")
36
 
37
  # Whisper ASR Configuration
38
  device = "cuda" if torch.cuda.is_available() else "cpu"
39
  config = AutoConfig.from_pretrained("openai/whisper-small")
40
  config.update({"timeout": 60})
41
 
42
- # Voice prompts for registration
43
  prompts = {
44
  "welcome": "Welcome to Biryani Hub.",
45
  "ask_name": "Tell me your name.",
@@ -47,13 +43,12 @@ prompts = {
47
  "thank_you": "Thank you for registration."
48
  }
49
 
 
50
  def generate_audio_prompt(text, filename):
51
  try:
52
  tts = gTTS(text)
53
  tts.save(os.path.join("static", filename))
54
  except gtts.tts.gTTSError as e:
55
- print(f"Error: {e}")
56
- print("Retrying after 5 seconds...")
57
  time.sleep(5)
58
  generate_audio_prompt(text, filename)
59
 
@@ -62,12 +57,9 @@ for key, text in prompts.items():
62
 
63
  # Function to convert audio to WAV format
64
  def convert_to_wav(input_path, output_path):
65
- try:
66
- audio = AudioSegment.from_file(input_path)
67
- audio = audio.set_frame_rate(16000).set_channels(1)
68
- audio.export(output_path, format="wav")
69
- except Exception as e:
70
- raise Exception(f"Audio conversion failed: {str(e)}")
71
 
72
  # Function to check if audio contains actual speech
73
  def is_silent_audio(audio_path):
@@ -79,47 +71,39 @@ def is_silent_audio(audio_path):
79
  def index():
80
  return render_template("index.html")
81
 
82
- # βœ… LOGIN ENDPOINT (Validates Existing Users)
83
  @app.route('/login', methods=['POST'])
84
  def login():
85
  data = request.json
86
- email = data.get('email').strip().lower()
87
- phone_number = data.get('phone_number').strip()
88
 
89
  if not email or not phone_number:
90
  return jsonify({'error': 'Missing email or phone number'}), 400
91
 
92
  try:
93
- print(f"πŸ” Checking login for Email: {email}, Phone: {phone_number}")
94
-
95
  query = f"SELECT Id, Name FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone_number}' LIMIT 1"
96
  result = sf.query(query)
97
 
98
  if result['totalSize'] == 0:
99
- print("❌ No matching records found!")
100
  return jsonify({'error': 'Invalid email or phone number. User not found'}), 401
101
 
102
  user_data = result['records'][0]
103
  session['user_id'] = user_data['Id']
104
  session['name'] = user_data['Name']
105
- print("βœ… User found:", user_data)
106
 
107
  return jsonify({'success': True, 'message': 'Login successful', 'user_id': user_data['Id'], 'name': user_data['Name']}), 200
108
 
109
- except requests.exceptions.RequestException as req_error:
110
- print("πŸ”΄ Salesforce Connection Error:", req_error)
111
- return jsonify({'error': f'Salesforce connection error: {str(req_error)}'}), 500
112
  except Exception as e:
113
- print("🚨 Unexpected Error:", e)
114
  return jsonify({'error': f'Unexpected error: {str(e)}'}), 500
115
 
116
- # βœ… REGISTRATION ENDPOINT (Creates New User)
117
  @app.route("/register", methods=["POST"])
118
  def register():
119
  data = request.json
120
- name = data.get('name')
121
- email = data.get('email').strip().lower()
122
- phone = data.get('phone').strip()
123
 
124
  if not name or not email or not phone:
125
  return jsonify({'error': 'Missing data'}), 400
@@ -145,7 +129,7 @@ def register():
145
  except Exception as e:
146
  return jsonify({'error': str(e)}), 500
147
 
148
- # βœ… TRANSCRIPTION ENDPOINT (Converts Speech to Text)
149
  @app.route("/transcribe", methods=["POST"])
150
  def transcribe():
151
  if "audio" not in request.files:
@@ -173,4 +157,3 @@ def transcribe():
173
  # Start Production Server
174
  if __name__ == "__main__":
175
  serve(app, host="0.0.0.0", port=7860)
176
-
 
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
 
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.",
 
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
 
 
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):
 
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
 
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:
 
157
  # Start Production Server
158
  if __name__ == "__main__":
159
  serve(app, host="0.0.0.0", port=7860)