DSatishchandra commited on
Commit
837f789
·
verified ·
1 Parent(s): d2298f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -63
app.py CHANGED
@@ -1,9 +1,7 @@
1
  import torch
2
  from flask import Flask, render_template, request, jsonify
3
- from flask_session import Session
4
  import json
5
  import os
6
- import re
7
  from transformers import pipeline
8
  from gtts import gTTS
9
  from pydub import AudioSegment
@@ -13,8 +11,6 @@ import time
13
  from waitress import serve
14
  from simple_salesforce import Salesforce
15
  import requests
16
- import logging
17
-
18
 
19
  app = Flask(__name__)
20
 
@@ -47,6 +43,19 @@ def generate_audio_prompt(text, filename):
47
  for key, text in prompts.items():
48
  generate_audio_prompt(text, f"{key}.mp3")
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # Function to convert audio to WAV format
51
  def convert_to_wav(input_path, output_path):
52
  try:
@@ -62,7 +71,7 @@ def is_silent_audio(audio_path):
62
  nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
63
  return len(nonsilent_parts) == 0
64
 
65
- # Connect to Salesforce
66
  try:
67
  print("Attempting to connect to Salesforce...")
68
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
@@ -70,80 +79,82 @@ try:
70
  except Exception as e:
71
  print(f"Failed to connect to Salesforce: {str(e)}")
72
 
73
- # LOGIN ENDPOINT (Validates User)
74
- @app.route('/login', methods=['POST'])
75
- def login():
76
- data = request.json
77
- email = data.get('email').strip().lower() # Ensure no leading/trailing spaces
78
- phone_number = data.get('phone_number').strip()
 
 
79
 
80
- # Sanitize phone number by removing non-numeric characters
81
- phone_number = re.sub(r'\D', '', phone_number)
 
82
 
83
- # Check if email or phone number is missing
84
- if not email or not phone_number:
85
- return jsonify({'error': 'Missing email or phone number'}), 400
 
 
 
 
86
 
87
- try:
88
- # Log the query for debugging
89
- query = f"SELECT Id, Name FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone_number}' LIMIT 1"
90
- logging.info(f"Executing query: {query}")
91
 
92
- # Query Salesforce to check if user exists
93
- result = sf.query(query)
94
 
95
- if result['totalSize'] == 0:
96
- return jsonify({'error': 'Invalid email or phone number. User not found'}), 401
97
 
98
- user_data = result['records'][0]
99
- return jsonify({'success': True, 'message': 'Login successful', 'user_id': user_data['Id'], 'name': user_data['Name']}), 200
100
 
101
- except requests.exceptions.RequestException as req_error:
102
- logging.error(f"Salesforce connection error: {str(req_error)}")
103
- return jsonify({'error': f'Salesforce connection error: {str(req_error)}'}), 500
104
- except Exception as e:
105
- logging.error(f"Unexpected error: {str(e)}")
106
- return jsonify({'error': f'Unexpected error: {str(e)}'}), 500
 
 
 
 
 
107
 
108
- # REGISTRATION ENDPOINT (Creates New User)
109
- @app.route("/submit", methods=["POST"])
110
- def submit():
111
- data = request.json
112
- name = data.get('name')
113
- email = data.get('email').strip().lower()
114
- phone = data.get('phone').strip()
115
 
116
- if not name or not email or not phone:
117
- return jsonify({'error': 'Missing data'}), 400
 
 
118
 
 
 
119
  try:
120
- # Check if user already exists
121
- query = f"SELECT Id FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone}' LIMIT 1"
122
- existing_user = sf.query(query)
123
-
124
- if existing_user['totalSize'] > 0:
125
- return jsonify({'error': 'User already exists'}), 409 # Conflict
126
-
127
- # Create new user
128
- customer_login = sf.Customer_Login__c.create({
129
- 'Name': name,
130
- 'Email__c': email,
131
- 'Phone_Number__c': phone
132
- })
133
-
134
- if customer_login.get('id'):
135
- return jsonify({'success': True, 'user_id': customer_login['id']}), 200
136
- else:
137
- return jsonify({'error': 'Failed to create record'}), 500
138
 
139
  except Exception as e:
140
- return jsonify({'error': str(e)}), 500
 
 
141
 
142
  @app.route("/")
143
  def index():
144
  return render_template("index.html")
145
 
146
- # ✅ TRANSCRIPTION ENDPOINT (Converts Speech to Text)
147
  @app.route("/transcribe", methods=["POST"])
148
  def transcribe():
149
  if "audio" not in request.files:
@@ -173,5 +184,4 @@ def transcribe():
173
 
174
  # Start Production Server
175
  if __name__ == "__main__":
176
- serve(app, host="0.0.0.0", port=7860)
177
-
 
1
  import torch
2
  from flask import Flask, render_template, request, jsonify
 
3
  import json
4
  import os
 
5
  from transformers import pipeline
6
  from gtts import gTTS
7
  from pydub import AudioSegment
 
11
  from waitress import serve
12
  from simple_salesforce import Salesforce
13
  import requests
 
 
14
 
15
  app = Flask(__name__)
16
 
 
43
  for key, text in prompts.items():
44
  generate_audio_prompt(text, f"{key}.mp3")
45
 
46
+ # Symbol mapping for proper recognition
47
+ SYMBOL_MAPPING = {
48
+ "at the rate": "@",
49
+ "at": "@",
50
+ "dot": ".",
51
+ "underscore": "_",
52
+ "hash": "#",
53
+ "plus": "+",
54
+ "dash": "-",
55
+ "comma": ",",
56
+ "space": " "
57
+ }
58
+
59
  # Function to convert audio to WAV format
60
  def convert_to_wav(input_path, output_path):
61
  try:
 
71
  nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
72
  return len(nonsilent_parts) == 0
73
 
74
+ # Salesforce connection details
75
  try:
76
  print("Attempting to connect to Salesforce...")
77
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
 
79
  except Exception as e:
80
  print(f"Failed to connect to Salesforce: {str(e)}")
81
 
82
+ # Function to handle login & registration in Salesforce
83
+ @app.route("/validate_login", methods=["POST"])
84
+ def validate_login():
85
+ try:
86
+ # Get the email and mobile number from the request
87
+ data = request.json
88
+ email = data.get("email")
89
+ mobile = data.get("mobile")
90
 
91
+ # Salesforce query to check if the email and mobile exist
92
+ query = f"SELECT Id, Name FROM Customer_Login__c WHERE Email__c = '{email}' AND Phone_Number__c = '{mobile}'"
93
+ result = sf.query(query)
94
 
95
+ if result['totalSize'] > 0:
96
+ return jsonify({'success': True, 'message': 'User authenticated successfully.'}), 200
97
+ else:
98
+ return jsonify({'success': False, 'error': 'Invalid email or mobile number.'}), 400
99
+ except Exception as e:
100
+ logging.error(f"Error: {str(e)}")
101
+ return jsonify({'error': 'Something went wrong. Please try again later.'}), 500
102
 
103
+ if __name__ == "__main__":
104
+ app.run(host="0.0.0.0", port=7860, debug=True)
 
 
105
 
 
 
106
 
 
 
107
 
108
+ # Initialize Flask app
109
+ app = Flask(__name__)
110
 
111
+ # Set the secret key to handle sessions securely
112
+ app.secret_key = os.getenv("SECRET_KEY", "sSSjyhInIsUohKpG8sHzty2q") # Replace with a secure key
113
+
114
+ # Configure the session type
115
+ app.config["SESSION_TYPE"] = "filesystem" # Use filesystem for session storage
116
+ app.config["SESSION_COOKIE_NAME"] = "my_session" # Optional: Change session cookie name
117
+ app.config["SESSION_COOKIE_SECURE"] = True # Ensure cookies are sent over HTTPS
118
+ app.config["SESSION_COOKIE_SAMESITE"] = "None" # Allow cross-site cookies
119
+
120
+ # Initialize the session
121
+ Session(app)
122
 
123
+ # Set up logging
124
+ logging.basicConfig(level=logging.INFO)
 
 
 
 
 
125
 
126
+ @app.route("/")
127
+ def index():
128
+ # Serve the HTML page for the voice-based login
129
+ return render_template("index.html")
130
 
131
+ @app.route("/capture_email_and_mobile", methods=["POST"])
132
+ def capture_email_and_mobile():
133
  try:
134
+ # Get the voice captured email and mobile number from the request
135
+ data = request.json
136
+ email = data.get("email")
137
+ mobile = data.get("mobile")
138
+
139
+ # Validate the captured email and mobile number
140
+ if not email or not mobile:
141
+ return jsonify({"error": "Email or mobile number is missing."}), 400
142
+
143
+ # Log the captured data for now (you can replace it with actual processing logic)
144
+ logging.info(f"Captured Email: {email}, Mobile: {mobile}")
145
+
146
+ # For simplicity, we'll assume the capture was successful.
147
+ return jsonify({"success": True, "message": "Email and mobile captured successfully."}), 200
 
 
 
 
148
 
149
  except Exception as e:
150
+ logging.error(f"Error: {str(e)}")
151
+ return jsonify({"error": "Something went wrong while processing."}), 500
152
+
153
 
154
  @app.route("/")
155
  def index():
156
  return render_template("index.html")
157
 
 
158
  @app.route("/transcribe", methods=["POST"])
159
  def transcribe():
160
  if "audio" not in request.files:
 
184
 
185
  # Start Production Server
186
  if __name__ == "__main__":
187
+ serve(app, host="0.0.0.0", port=7860)