Customers commited on
Commit
4135877
·
verified ·
1 Parent(s): 1a6f5d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -90
app.py CHANGED
@@ -15,10 +15,6 @@ from google.oauth2 import service_account
15
  from googleapiclient.discovery import build
16
  from datetime import datetime
17
  from google.oauth2.service_account import Credentials
18
- from gtts import gTTS # Text-to-speech
19
- import tempfile
20
- import base64
21
- from io import BytesIO# For temporary audio file
22
 
23
 
24
 
@@ -108,7 +104,7 @@ def get_token(key):
108
  print(f"Token {key} not found in any source")
109
  return None
110
 
111
- # Now replace all your os.getenv() calls with get_token():
112
  FLW_SECRET_KEY = os.getenv("FLW_SECRET_KEY") or get_token("FLW_SECRET_KEY")
113
  FLW_ENCRYPTION_KEY = os.getenv("FLW_ENCRYPTION_KEY") or get_token("FLW_ENCRYPTION_KEY")
114
  FLW_PUBLIC_KEY = os.getenv("FLW_PUBLIC_KEY") or get_token("FLW_PUBLIC_KEY")
@@ -2872,57 +2868,38 @@ button:active {
2872
  display: none !important;
2873
  }
2874
 
2875
- /* Audio player styling */
2876
- .gradio-audio {
2877
- margin-top: 1px;
2878
- background: rgba(255, 255, 255, 0.7) !important;
2879
- border-radius: 8px !important;
2880
- padding: 1px !important;
2881
- }
2882
-
2883
  """
2884
- def text_to_speech(text):
2885
- """Convert text to speech and return audio file path"""
2886
- try:
2887
- # Create temporary file
2888
- with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as fp:
2889
- temp_path = fp.name
2890
-
2891
- # Generate speech
2892
- tts = gTTS(text=text, lang='en')
2893
- tts.save(temp_path)
2894
-
2895
- return temp_path
2896
- except Exception as e:
2897
- print(f"Error in text-to-speech: {str(e)}")
2898
- return None
2899
-
2900
  def respond(message, history, max_tokens, temperature, top_p):
2901
  email = OWNER_EMAIL
2902
 
 
2903
  save_chat_history(email, message, "")
2904
 
2905
  try:
2906
- # Save to BATTERY_SHEET_ID
2907
  sheet = get_or_create_sheet(BATTERY_SHEET_ID, "ChatHistory")
 
2908
  now_str = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
2909
  sheet.append_row([now_str, email, message, ""])
2910
 
2911
  except Exception as e:
2912
  print(f"Error saving to battery sheet: {str(e)}")
2913
 
 
2914
  temp_response = f"""<a href="https://flutterwave.com/pay/gossapp" target="_blank">
2915
  <img src='https://i.imgur.com/PznT4qo.png' width='20'>
2916
  </a>"""
2917
- yield [(message, temp_response)], None
2918
 
2919
  try:
2920
  # Build prompt
2921
- messages = []
 
2922
  for user_msg, bot_msg in history:
2923
  if user_msg:
2924
  messages.append({"role": "user", "content": user_msg})
2925
- if bot_msg and not str(bot_msg).startswith("<img"):
2926
  messages.append({"role": "assistant", "content": str(bot_msg)})
2927
  messages.append({"role": "user", "content": message})
2928
 
@@ -2930,33 +2907,21 @@ def respond(message, history, max_tokens, temperature, top_p):
2930
  inference_client = get_inference_client()
2931
 
2932
  response = ""
2933
- stream = inference_client.chat_completion(
2934
  messages,
2935
  max_tokens=max_tokens,
 
2936
  temperature=temperature,
2937
  top_p=top_p,
2938
- stream=True
2939
- )
2940
-
2941
- for chunk in stream:
2942
- # Handle both old and new API response formats
2943
- if hasattr(chunk, 'token') and chunk.token.text: # Old format
2944
- token = chunk.token.text
2945
- elif hasattr(chunk, 'choices') and chunk.choices: # New format
2946
- token = chunk.choices[0].delta.content or ""
2947
- else:
2948
- continue
2949
-
2950
  if token:
2951
  response += token
2952
  clean_response = response.split("(Note:")[0].strip()
2953
- yield [(message, clean_response)], None
2954
 
2955
  clean_response = response.split("(Note:")[0].strip()
2956
 
2957
- # Generate audio for the response
2958
- audio_file = text_to_speech(clean_response)
2959
-
2960
  # Save full bot response to chat history
2961
  save_chat_history(email, message, clean_response)
2962
 
@@ -2965,26 +2930,30 @@ def respond(message, history, max_tokens, temperature, top_p):
2965
  scope = ['https://www.googleapis.com/auth/spreadsheets',
2966
  'https://www.googleapis.com/auth/drive']
2967
  creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
2968
- gspread_client = gspread.authorize(creds)
2969
 
2970
  spreadsheet = gspread_client.open_by_key(BATTERY_SHEET_ID)
2971
 
 
2972
  for worksheet in spreadsheet.worksheets():
2973
  try:
2974
  records = worksheet.get_all_records()
2975
- for i, record in enumerate(records, start=2):
2976
  if (str(record.get('Email', '')).lower() == email.lower() and
2977
  str(record.get('User Message', '')).strip() == message.strip() and
2978
  (not record.get('Bot Message') or str(record.get('Bot Message', '')).strip() == "")):
2979
 
2980
- worksheet.update_cell(i, 4, clean_response)
 
2981
  break
2982
  except Exception as e:
2983
  print(f"Error searching sheet {worksheet.title}: {str(e)}")
 
 
2984
  except Exception as e:
2985
  print(f"Error updating battery sheet with response: {str(e)}")
2986
 
2987
- yield [(message, clean_response)], audio_file if audio_file else None
2988
 
2989
  except Exception as e:
2990
  if "402" in str(e):
@@ -2994,20 +2963,21 @@ def respond(message, history, max_tokens, temperature, top_p):
2994
  Please:<br>
2995
  1. <a href="https://flutterwave.com/pay/gossapp" target="_blank">Reload AI-time</a><br>
2996
  2. Try again later,or<br>
2997
- 3. Contact <a href="https://wa.link/x2wdpl" target="_blank">Support </a> if this persists.<br><br>
2998
- Tired of Manual Chatbot reset delays? <br> Consider a Subscription to have your chatbot last upto 20 times longer and fewer/ zero reset delays (Auto-reset)</div>
2999
  """)
3000
  else:
3001
  custom_error = gr.HTML(f"""
3002
  <div style='color: #d32f2f; background: #ffebee; padding: 10px; border-radius: 5px;'>
3003
- <strong>Error:</strong> {str(e)}<br>
3004
- Hmm...Try <strong> changing or resetting the BrainChip/LLM Blackbox below</strong>. Looks like there's no valid BrainChip, or higher BrainChip required<br>.
3005
  Contact <a href="https://wa.link/x2wdpl" target="_blank">Support </a>.
3006
  </div>
3007
  """)
3008
 
3009
  save_chat_history(email, message, f"Error occurred: {str(e)}")
3010
- yield [(message, custom_error)], None
 
3011
 
3012
 
3013
  def clear_input():
@@ -3314,14 +3284,11 @@ with gr.Blocks(
3314
  scale=6
3315
  )
3316
  submit = gr.Button("", elem_classes="send-btn")
3317
-
3318
- with gr.Row(scale=1):
3319
- audio_output = gr.Audio(
3320
- label="Voice Response",
3321
- autoplay=False,
3322
- visible=True,
3323
- elem_id="audio-player"
3324
- )
3325
 
3326
  # Add Business, Family, Friends chatbots right below the button row
3327
  business_html_display = gr.HTML(f"""
@@ -4013,7 +3980,7 @@ with gr.Blocks(
4013
  close_train = gr.Button("×", elem_classes=["close-btn"])
4014
  gr.HTML(f"""
4015
  <div style="margin: 10px 0;">
4016
- <iframe src="https://script.google.com/macros/s/AKfycbxdoewOlGNmxiJJBLy-RJSKIoEcsp6pJK2iH723zgEl8q8qYJw6nrWYTCHritVkJhkX1A/exec?email={OWNER_EMAIL}" style="width:100%; height:750px; border:none; border-radius:8px;"></iframe>
4017
  </div>
4018
  """)
4019
 
@@ -5307,18 +5274,16 @@ with gr.Blocks(
5307
  outputs=[save_status, bio_display, chatbot]
5308
  )
5309
 
5310
- # Update your submit/msg handlers
5311
  submit.click(
5312
-
5313
  respond,
5314
  inputs=[msg, chatbot, max_tokens, temperature],
5315
- outputs=[chatbot, audio_output],
5316
  ).then(clear_input, outputs=[msg])
5317
 
5318
  msg.submit(
5319
  respond,
5320
  inputs=[msg, chatbot, max_tokens, temperature],
5321
- outputs=[chatbot, audio_output],
5322
  ).then(clear_input, outputs=[msg])
5323
 
5324
  # Add these at the end of your existing event handlers
@@ -5334,24 +5299,7 @@ with gr.Blocks(
5334
  outputs=[status_display]
5335
  )
5336
 
5337
- # Add the audio player update function
5338
- def update_audio_player(audio_data):
5339
- if audio_data:
5340
- return f"""
5341
- <script>
5342
- {audio_player_js}
5343
- document.currentScript.parentNode.innerHTML = createAudioPlayer('{audio_data}');
5344
- </script>
5345
- """
5346
- return ""
5347
-
5348
- audio_output.change(
5349
- update_audio_player,
5350
- inputs=[audio_output],
5351
- outputs=[audio_output]
5352
- )
5353
-
5354
- # Certificate generation
5355
  def generate_certificate(name, email):
5356
  """Generate certificate HTML with centered name on background image"""
5357
 
 
15
  from googleapiclient.discovery import build
16
  from datetime import datetime
17
  from google.oauth2.service_account import Credentials
 
 
 
 
18
 
19
 
20
 
 
104
  print(f"Token {key} not found in any source")
105
  return None
106
 
107
+ # Now replace all your os.getenv() calls with get_tokens():
108
  FLW_SECRET_KEY = os.getenv("FLW_SECRET_KEY") or get_token("FLW_SECRET_KEY")
109
  FLW_ENCRYPTION_KEY = os.getenv("FLW_ENCRYPTION_KEY") or get_token("FLW_ENCRYPTION_KEY")
110
  FLW_PUBLIC_KEY = os.getenv("FLW_PUBLIC_KEY") or get_token("FLW_PUBLIC_KEY")
 
2868
  display: none !important;
2869
  }
2870
 
 
 
 
 
 
 
 
 
2871
  """
2872
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2873
  def respond(message, history, max_tokens, temperature, top_p):
2874
  email = OWNER_EMAIL
2875
 
2876
+ # Save to chat history
2877
  save_chat_history(email, message, "")
2878
 
2879
  try:
2880
+ # Save to BATTERY_SHEET_ID (using our multi-sheet function)
2881
  sheet = get_or_create_sheet(BATTERY_SHEET_ID, "ChatHistory")
2882
+
2883
  now_str = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
2884
  sheet.append_row([now_str, email, message, ""])
2885
 
2886
  except Exception as e:
2887
  print(f"Error saving to battery sheet: {str(e)}")
2888
 
2889
+ # Immediate feedback to user
2890
  temp_response = f"""<a href="https://flutterwave.com/pay/gossapp" target="_blank">
2891
  <img src='https://i.imgur.com/PznT4qo.png' width='20'>
2892
  </a>"""
2893
+ yield [(message, temp_response)]
2894
 
2895
  try:
2896
  # Build prompt
2897
+ current_system_msg = get_system_message()
2898
+ messages = [{"role": "system", "content": current_system_msg}]
2899
  for user_msg, bot_msg in history:
2900
  if user_msg:
2901
  messages.append({"role": "user", "content": user_msg})
2902
+ if bot_msg and not str(bot_msg).startswith("<img"): # Convert to string before checking
2903
  messages.append({"role": "assistant", "content": str(bot_msg)})
2904
  messages.append({"role": "user", "content": message})
2905
 
 
2907
  inference_client = get_inference_client()
2908
 
2909
  response = ""
2910
+ for chunk in inference_client.chat_completion(
2911
  messages,
2912
  max_tokens=max_tokens,
2913
+ stream=True,
2914
  temperature=temperature,
2915
  top_p=top_p,
2916
+ ):
2917
+ token = chunk.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
2918
  if token:
2919
  response += token
2920
  clean_response = response.split("(Note:")[0].strip()
2921
+ yield [(message, clean_response)]
2922
 
2923
  clean_response = response.split("(Note:")[0].strip()
2924
 
 
 
 
2925
  # Save full bot response to chat history
2926
  save_chat_history(email, message, clean_response)
2927
 
 
2930
  scope = ['https://www.googleapis.com/auth/spreadsheets',
2931
  'https://www.googleapis.com/auth/drive']
2932
  creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
2933
+ gspread_client = gspread.authorize(creds) # Renamed to avoid conflict
2934
 
2935
  spreadsheet = gspread_client.open_by_key(BATTERY_SHEET_ID)
2936
 
2937
+ # Search all sheets for our record to update
2938
  for worksheet in spreadsheet.worksheets():
2939
  try:
2940
  records = worksheet.get_all_records()
2941
+ for i, record in enumerate(records, start=2): # start=2 because header is row 1
2942
  if (str(record.get('Email', '')).lower() == email.lower() and
2943
  str(record.get('User Message', '')).strip() == message.strip() and
2944
  (not record.get('Bot Message') or str(record.get('Bot Message', '')).strip() == "")):
2945
 
2946
+ # Update the bot response
2947
+ worksheet.update_cell(i, 4, clean_response) # Column D is index 4
2948
  break
2949
  except Exception as e:
2950
  print(f"Error searching sheet {worksheet.title}: {str(e)}")
2951
+ continue
2952
+
2953
  except Exception as e:
2954
  print(f"Error updating battery sheet with response: {str(e)}")
2955
 
2956
+ yield [(message, clean_response)]
2957
 
2958
  except Exception as e:
2959
  if "402" in str(e):
 
2963
  Please:<br>
2964
  1. <a href="https://flutterwave.com/pay/gossapp" target="_blank">Reload AI-time</a><br>
2965
  2. Try again later,or<br>
2966
+ 3. Contact <a href="https://wa.link/x2wdpl" target="_blank">Support </a> if this persists.
2967
+ Tired of Manual Chatbot reset delays? Consider a Subscription to have your chatbot last upto 20 times longer and fewer/ zero reset delays (Auto-reset)</div>
2968
  """)
2969
  else:
2970
  custom_error = gr.HTML(f"""
2971
  <div style='color: #d32f2f; background: #ffebee; padding: 10px; border-radius: 5px;'>
2972
+ <strong>Error:</strong> {str(e)}<br>
2973
+ Hmm...Looks like there's no valid BrainChip, or higher Brainchip required<br>.
2974
  Contact <a href="https://wa.link/x2wdpl" target="_blank">Support </a>.
2975
  </div>
2976
  """)
2977
 
2978
  save_chat_history(email, message, f"Error occurred: {str(e)}")
2979
+ yield [(message, custom_error)]
2980
+
2981
 
2982
 
2983
  def clear_input():
 
3284
  scale=6
3285
  )
3286
  submit = gr.Button("", elem_classes="send-btn")
3287
+
3288
+
3289
+
3290
+ # Keep the actual clear button but hide it
3291
+ clear = gr.ClearButton([msg, chatbot], variant="secondary")
 
 
 
3292
 
3293
  # Add Business, Family, Friends chatbots right below the button row
3294
  business_html_display = gr.HTML(f"""
 
3980
  close_train = gr.Button("×", elem_classes=["close-btn"])
3981
  gr.HTML(f"""
3982
  <div style="margin: 10px 0;">
3983
+ <iframe src="https://script.google.com/macros/s/AKfycbz--PS8PC0j6Ghf96-rii6cdRsaJ2TphVA8MODnP2nysYJ4TD8JI4DWz9K5jseI1beQog/exec?email={OWNER_EMAIL}" style="width:100%; height:750px; border:none; border-radius:8px;"></iframe>
3984
  </div>
3985
  """)
3986
 
 
5274
  outputs=[save_status, bio_display, chatbot]
5275
  )
5276
 
 
5277
  submit.click(
 
5278
  respond,
5279
  inputs=[msg, chatbot, max_tokens, temperature],
5280
+ outputs=[chatbot],
5281
  ).then(clear_input, outputs=[msg])
5282
 
5283
  msg.submit(
5284
  respond,
5285
  inputs=[msg, chatbot, max_tokens, temperature],
5286
+ outputs=[chatbot],
5287
  ).then(clear_input, outputs=[msg])
5288
 
5289
  # Add these at the end of your existing event handlers
 
5299
  outputs=[status_display]
5300
  )
5301
 
5302
+ # Certificate generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5303
  def generate_certificate(name, email):
5304
  """Generate certificate HTML with centered name on background image"""
5305