lokesh341 commited on
Commit
7d5309b
·
verified ·
1 Parent(s): 784c9d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -74
app.py CHANGED
@@ -43,19 +43,6 @@ def generate_audio_prompt(text, filename):
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,7 +58,7 @@ def is_silent_audio(audio_path):
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,82 +66,71 @@ try:
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:
 
43
  for key, text in prompts.items():
44
  generate_audio_prompt(text, f"{key}.mp3")
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  # Function to convert audio to WAV format
47
  def convert_to_wav(input_path, output_path):
48
  try:
 
58
  nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
59
  return len(nonsilent_parts) == 0
60
 
61
+ # Connect to Salesforce
62
  try:
63
  print("Attempting to connect to Salesforce...")
64
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
 
66
  except Exception as e:
67
  print(f"Failed to connect to Salesforce: {str(e)}")
68
 
69
+ # LOGIN ENDPOINT (Validates User)
70
+ @app.route('/login', methods=['POST'])
71
+ def login():
72
+ data = request.json
73
+ email = data.get('email').strip().lower()
74
+ phone_number = data.get('phone_number').strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ if not email or not phone_number:
77
+ return jsonify({'error': 'Missing email or phone number'}), 400
78
 
79
+ try:
80
+ # Check if user exists in Salesforce
81
+ query = f"SELECT Id, Name FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone_number}' LIMIT 1"
82
+ result = sf.query(query)
83
 
84
+ if result['totalSize'] == 0:
85
+ return jsonify({'error': 'Invalid email or phone number. User not found'}), 401
86
 
87
+ user_data = result['records'][0]
88
+ return jsonify({'success': True, 'message': 'Login successful', 'user_id': user_data['Id'], 'name': user_data['Name']}), 200
 
 
 
89
 
90
+ except requests.exceptions.RequestException as req_error:
91
+ return jsonify({'error': f'Salesforce connection error: {str(req_error)}'}), 500
92
+ except Exception as e:
93
+ return jsonify({'error': f'Unexpected error: {str(e)}'}), 500
94
 
95
+ # REGISTRATION ENDPOINT (Creates New User)
96
+ @app.route("/submit", methods=["POST"])
97
+ def submit():
98
+ data = request.json
99
+ name = data.get('name')
100
+ email = data.get('email').strip().lower()
101
+ phone = data.get('phone').strip()
102
 
103
+ if not name or not email or not phone:
104
+ return jsonify({'error': 'Missing data'}), 400
 
 
105
 
 
 
106
  try:
107
+ # Check if user already exists
108
+ query = f"SELECT Id FROM Customer_Login__c WHERE LOWER(Email__c) = '{email}' AND Phone_Number__c = '{phone}' LIMIT 1"
109
+ existing_user = sf.query(query)
110
+
111
+ if existing_user['totalSize'] > 0:
112
+ return jsonify({'error': 'User already exists'}), 409 # Conflict
113
+
114
+ # Create new user
115
+ customer_login = sf.Customer_Login__c.create({
116
+ 'Name': name,
117
+ 'Email__c': email,
118
+ 'Phone_Number__c': phone
119
+ })
120
+
121
+ if customer_login.get('id'):
122
+ return jsonify({'success': True, 'user_id': customer_login['id']}), 200
123
+ else:
124
+ return jsonify({'error': 'Failed to create record'}), 500
125
 
126
  except Exception as e:
127
+ return jsonify({'error': str(e)}), 500
 
 
128
 
129
  @app.route("/")
130
  def index():
131
  return render_template("index.html")
132
 
133
+ # ✅ TRANSCRIPTION ENDPOINT (Converts Speech to Text)
134
  @app.route("/transcribe", methods=["POST"])
135
  def transcribe():
136
  if "audio" not in request.files: