waleedmohd commited on
Commit
edd7ea8
·
verified ·
1 Parent(s): 30e88fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -129
app.py CHANGED
@@ -12,6 +12,18 @@ def simple_detect_language(text):
12
  return "ar"
13
  return "en"
14
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # Import customer service enhancements
16
  try:
17
  from customer_service_enhancements import (
@@ -200,8 +212,14 @@ def respond(message: str):
200
  "en": "Please type your question."
201
  }
202
 
203
- # Detect language using simple function
204
- language = simple_detect_language(message)
 
 
 
 
 
 
205
 
206
  # Classify the user's intent using keyword matching
207
  intent = classify_intent(message)
@@ -374,39 +392,6 @@ custom_css = """
374
  background-color: #f9f9f9;
375
  }
376
 
377
- .typing-indicator {
378
- display: inline-block;
379
- width: 50px;
380
- text-align: left;
381
- }
382
-
383
- .typing-indicator span {
384
- display: inline-block;
385
- width: 8px;
386
- height: 8px;
387
- background-color: #1a5276;
388
- border-radius: 50%;
389
- margin-right: 5px;
390
- animation: typing 1s infinite;
391
- }
392
-
393
- .typing-indicator span:nth-child(2) {
394
- animation-delay: 0.2s;
395
- }
396
-
397
- .typing-indicator span:nth-child(3) {
398
- animation-delay: 0.4s;
399
- }
400
-
401
- @keyframes typing {
402
- 0%, 100% {
403
- transform: translateY(0);
404
- }
405
- 50% {
406
- transform: translateY(-5px);
407
- }
408
- }
409
-
410
  .live-agent-button {
411
  background-color: #27ae60;
412
  color: white;
@@ -487,8 +472,6 @@ a:hover {
487
 
488
  # Chat interface with simplified UI for Hugging Face
489
  with gr.Blocks(css=custom_css) as demo:
490
- # Store conversation history
491
- state = gr.State(value=[])
492
  # Store selected language
493
  selected_lang = gr.State(value="ar")
494
  # Store user name for personalization
@@ -510,12 +493,21 @@ with gr.Blocks(css=custom_css) as demo:
510
  with gr.Row(elem_classes="chat-container"):
511
  chatbot = gr.Chatbot(height=400)
512
 
513
- # Quick action buttons (will be populated based on language)
514
  with gr.Row(elem_classes="quick-actions", visible=True) as quick_actions_container:
515
- quick_action_buttons = []
516
- for i in range(9): # Create 9 buttons (one for each intent)
517
- button = gr.Button("", visible=False, elem_classes="quick-action-button")
518
- quick_action_buttons.append(button)
 
 
 
 
 
 
 
 
 
519
 
520
  with gr.Row():
521
  with gr.Column(scale=8):
@@ -539,28 +531,42 @@ with gr.Blocks(css=custom_css) as demo:
539
  gr.Markdown("© 2025 Omdurman National Bank. All Rights Reserved. | جميع الحقوق محفوظة لبنك أم درمان الوطني ٢٠٢٥ ©")
540
 
541
  # Update language state and quick action buttons when language is changed
542
- def update_language_and_buttons(lang):
543
  language_code = "ar" if lang == "العربية" else "en"
544
 
545
  # Get the appropriate quick actions based on language
546
  quick_actions = QUICK_ACTIONS_AR if language_code == "ar" else QUICK_ACTIONS_EN
547
 
548
- # Update button visibility and text
549
- button_updates = []
550
- for i, button in enumerate(quick_action_buttons):
551
- if i < len(quick_actions):
552
- button_updates.append(gr.Button.update(visible=True, value=quick_actions[i]["text"]))
553
- else:
554
- button_updates.append(gr.Button.update(visible=False))
555
-
556
- return [language_code] + button_updates
 
 
 
 
557
 
558
  # Connect language button to update function
559
- outputs = [selected_lang] + quick_action_buttons
560
  language_btn.change(
561
- fn=update_language_and_buttons,
562
  inputs=language_btn,
563
- outputs=outputs
 
 
 
 
 
 
 
 
 
 
 
564
  )
565
 
566
  # Handle message submission
@@ -584,7 +590,7 @@ with gr.Blocks(css=custom_css) as demo:
584
  break
585
 
586
  # Add user message to chat history
587
- chat_history.append([message, None])
588
 
589
  # Get response
590
  responses = respond(message)
@@ -616,85 +622,87 @@ with gr.Blocks(css=custom_css) as demo:
616
  menu_text = menu_responses[lang]
617
 
618
  # Add system message showing the menu
619
- chat_history.append([None, menu_text.replace("\n", "<br>")])
620
 
621
  return chat_history
622
 
623
  # Handle quick action button clicks
624
- def handle_quick_action(button_index, chat_history, lang, name):
625
  # Get the appropriate quick actions based on language
626
  quick_actions = QUICK_ACTIONS_AR if lang == "ar" else QUICK_ACTIONS_EN
627
 
628
- if button_index < len(quick_actions):
629
- # Get the intent for this button
630
- intent = quick_actions[button_index]["intent"]
631
- button_text = quick_actions[button_index]["text"]
632
-
633
- # Add button text as user message
634
- chat_history.append([button_text, None])
635
-
636
- # Get the response for this intent
637
- if CUSTOMER_SERVICE_ENHANCEMENTS_AVAILABLE:
638
- # Use enhanced response if available
639
- response_ar = get_enhanced_response(intent, "ar", name)
640
- response_en = get_enhanced_response(intent, "en", name)
641
- else:
642
- # Add a greeting phrase at the beginning
643
- greeting_ar = get_random_phrase("greeting", "ar")
644
- greeting_en = get_random_phrase("greeting", "en")
645
-
646
- # Add the main response
647
- main_response_ar = ONB_GUIDELINES_AR.get(intent, "")
648
- main_response_en = ONB_GUIDELINES_EN.get(intent, "")
649
-
650
- # Add a follow-up phrase at the end
651
- follow_up_ar = get_random_phrase("follow_up", "ar")
652
- follow_up_en = get_random_phrase("follow_up", "en")
653
-
654
- # Combine all parts
655
- response_ar = f"{greeting_ar}<br><br>{main_response_ar}<br><br>{follow_up_ar}"
656
- response_en = f"{greeting_en}<br><br>{main_response_en}<br><br>{follow_up_en}"
657
-
658
- responses = {
659
- "ar": response_ar,
660
- "en": response_en
661
- }
662
-
663
- # Select response based on language
664
- response = responses[lang]
665
-
666
- # Personalize response if name is available
667
- if name:
668
- if lang == "ar":
669
- response = response.replace("مرحبًا", f"مرحبًا {name}")
670
- else:
671
- response = response.replace("Welcome", f"Welcome {name}")
672
- response = response.replace("Hello", f"Hello {name}")
673
 
674
- # Update bot response in chat history
675
- chat_history[-1][1] = response
 
676
 
677
- # Log the interaction
678
- log_interaction(button_text, response, intent, lang)
 
679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
  return chat_history
681
 
682
  # Handle live agent button click
683
  def connect_to_live_agent(chat_history, lang):
684
  message = "Connecting to a live customer service agent. Please wait a moment..." if lang == "en" else "جاري الاتصال بوكيل خدمة العملاء. يرجى الانتظار لحظة..."
685
- chat_history.append([None, message])
686
  return chat_history
687
 
688
  # Handle satisfaction survey button click
689
  def show_satisfaction_survey(chat_history, lang):
690
  if CUSTOMER_SERVICE_ENHANCEMENTS_AVAILABLE:
691
  survey_html = offer_satisfaction_survey(lang)
692
- chat_history.append([None, survey_html])
693
  else:
694
  # Simple survey message if enhancements not available
695
  title = "استطلاع رضا العملاء" if lang == "ar" else "Customer Satisfaction Survey"
696
  message = f"<div class='satisfaction-survey'><h3>{title}</h3><p>{'نشكرك على استخدام المساعد المصرفي الافتراضي!' if lang == 'ar' else 'Thank you for using our virtual banking assistant!'}</p></div>"
697
- chat_history.append([None, message])
698
 
699
  return chat_history
700
 
@@ -727,12 +735,59 @@ with gr.Blocks(css=custom_css) as demo:
727
  )
728
 
729
  # Link quick action buttons to handler function
730
- for i, button in enumerate(quick_action_buttons):
731
- button.click(
732
- fn=lambda idx=i, chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action(idx, chat, lang, name),
733
- inputs=[chatbot, selected_lang, user_name],
734
- outputs=[chatbot]
735
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
736
 
737
  # Also trigger on Enter key
738
  text_input.submit(
@@ -752,24 +807,13 @@ with gr.Blocks(css=custom_css) as demo:
752
  chat_history.append([None, welcome_ar])
753
  chat_history.append([None, welcome_en])
754
 
755
- # Get the appropriate quick actions for Arabic (default)
756
- quick_actions = QUICK_ACTIONS_AR
757
-
758
- # Update button visibility and text
759
- button_updates = []
760
- for i, button in enumerate(quick_action_buttons):
761
- if i < len(quick_actions):
762
- button_updates.append(gr.Button.update(visible=True, value=quick_actions[i]["text"]))
763
- else:
764
- button_updates.append(gr.Button.update(visible=False))
765
-
766
- return [chat_history] + button_updates
767
 
768
  # Initialize the chat when the app starts
769
  demo.load(
770
  fn=init_chat,
771
  inputs=[],
772
- outputs=[chatbot] + quick_action_buttons
773
  )
774
 
775
  if __name__ == "__main__":
 
12
  return "ar"
13
  return "en"
14
 
15
+ # Try to import transformers for Arabic NLP if available
16
+ try:
17
+ from transformers import pipeline
18
+ arabic_nlp = pipeline("text-classification", model="papluca/xlm-roberta-base-language-detection")
19
+ ARABIC_NLP_AVAILABLE = True
20
+
21
+ def detect_language_with_nlp(text):
22
+ result = arabic_nlp(text)
23
+ return result[0]['label']
24
+ except ImportError:
25
+ ARABIC_NLP_AVAILABLE = False
26
+
27
  # Import customer service enhancements
28
  try:
29
  from customer_service_enhancements import (
 
212
  "en": "Please type your question."
213
  }
214
 
215
+ # Detect language using NLP if available, otherwise use simple detection
216
+ if ARABIC_NLP_AVAILABLE:
217
+ language = detect_language_with_nlp(message)
218
+ # If the language is neither Arabic nor English, default to English
219
+ if language != "ar" and language != "en":
220
+ language = "en"
221
+ else:
222
+ language = simple_detect_language(message)
223
 
224
  # Classify the user's intent using keyword matching
225
  intent = classify_intent(message)
 
392
  background-color: #f9f9f9;
393
  }
394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  .live-agent-button {
396
  background-color: #27ae60;
397
  color: white;
 
472
 
473
  # Chat interface with simplified UI for Hugging Face
474
  with gr.Blocks(css=custom_css) as demo:
 
 
475
  # Store selected language
476
  selected_lang = gr.State(value="ar")
477
  # Store user name for personalization
 
493
  with gr.Row(elem_classes="chat-container"):
494
  chatbot = gr.Chatbot(height=400)
495
 
496
+ # Quick action buttons container
497
  with gr.Row(elem_classes="quick-actions", visible=True) as quick_actions_container:
498
+ balance_btn = gr.Button("تحقق من الرصيد", elem_classes="quick-action-button")
499
+ lost_card_btn = gr.Button("الإبلاغ عن بطاقة مفقودة", elem_classes="quick-action-button")
500
+ loan_btn = gr.Button("معلومات القرض", elem_classes="quick-action-button")
501
+
502
+ with gr.Row(elem_classes="quick-actions", visible=True):
503
+ transfer_btn = gr.Button("تحويل الأموال", elem_classes="quick-action-button")
504
+ new_account_btn = gr.Button("فتح حساب جديد", elem_classes="quick-action-button")
505
+ interest_btn = gr.Button("أسعار الفائدة", elem_classes="quick-action-button")
506
+
507
+ with gr.Row(elem_classes="quick-actions", visible=True):
508
+ branches_btn = gr.Button("مواقع الفروع", elem_classes="quick-action-button")
509
+ hours_btn = gr.Button("ساعات العمل", elem_classes="quick-action-button")
510
+ contact_btn = gr.Button("اتصل بنا", elem_classes="quick-action-button")
511
 
512
  with gr.Row():
513
  with gr.Column(scale=8):
 
531
  gr.Markdown("© 2025 Omdurman National Bank. All Rights Reserved. | جميع الحقوق محفوظة لبنك أم درمان الوطني ٢٠٢٥ ©")
532
 
533
  # Update language state and quick action buttons when language is changed
534
+ def update_language(lang):
535
  language_code = "ar" if lang == "العربية" else "en"
536
 
537
  # Get the appropriate quick actions based on language
538
  quick_actions = QUICK_ACTIONS_AR if language_code == "ar" else QUICK_ACTIONS_EN
539
 
540
+ # Update button text based on language
541
+ return [
542
+ language_code,
543
+ quick_actions[0]["text"], # balance
544
+ quick_actions[1]["text"], # lost_card
545
+ quick_actions[2]["text"], # loan
546
+ quick_actions[3]["text"], # transfer
547
+ quick_actions[4]["text"], # new_account
548
+ quick_actions[5]["text"], # interest
549
+ quick_actions[6]["text"], # branches
550
+ quick_actions[7]["text"], # working_hours
551
+ quick_actions[8]["text"] # contact
552
+ ]
553
 
554
  # Connect language button to update function
 
555
  language_btn.change(
556
+ fn=update_language,
557
  inputs=language_btn,
558
+ outputs=[
559
+ selected_lang,
560
+ balance_btn,
561
+ lost_card_btn,
562
+ loan_btn,
563
+ transfer_btn,
564
+ new_account_btn,
565
+ interest_btn,
566
+ branches_btn,
567
+ hours_btn,
568
+ contact_btn
569
+ ]
570
  )
571
 
572
  # Handle message submission
 
590
  break
591
 
592
  # Add user message to chat history
593
+ chat_history = chat_history + [[message, None]]
594
 
595
  # Get response
596
  responses = respond(message)
 
622
  menu_text = menu_responses[lang]
623
 
624
  # Add system message showing the menu
625
+ chat_history = chat_history + [[None, menu_text.replace("\n", "<br>")]]
626
 
627
  return chat_history
628
 
629
  # Handle quick action button clicks
630
+ def handle_quick_action(intent, chat_history, lang, name):
631
  # Get the appropriate quick actions based on language
632
  quick_actions = QUICK_ACTIONS_AR if lang == "ar" else QUICK_ACTIONS_EN
633
 
634
+ # Find the button text for this intent
635
+ button_text = ""
636
+ for action in quick_actions:
637
+ if action["intent"] == intent:
638
+ button_text = action["text"]
639
+ break
640
+
641
+ # Add button text as user message
642
+ chat_history = chat_history + [[button_text, None]]
643
+
644
+ # Get the response for this intent
645
+ if CUSTOMER_SERVICE_ENHANCEMENTS_AVAILABLE:
646
+ # Use enhanced response if available
647
+ response_ar = get_enhanced_response(intent, "ar", name)
648
+ response_en = get_enhanced_response(intent, "en", name)
649
+ else:
650
+ # Add a greeting phrase at the beginning
651
+ greeting_ar = get_random_phrase("greeting", "ar")
652
+ greeting_en = get_random_phrase("greeting", "en")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
 
654
+ # Add the main response
655
+ main_response_ar = ONB_GUIDELINES_AR.get(intent, "")
656
+ main_response_en = ONB_GUIDELINES_EN.get(intent, "")
657
 
658
+ # Add a follow-up phrase at the end
659
+ follow_up_ar = get_random_phrase("follow_up", "ar")
660
+ follow_up_en = get_random_phrase("follow_up", "en")
661
 
662
+ # Combine all parts
663
+ response_ar = f"{greeting_ar}<br><br>{main_response_ar}<br><br>{follow_up_ar}"
664
+ response_en = f"{greeting_en}<br><br>{main_response_en}<br><br>{follow_up_en}"
665
+
666
+ responses = {
667
+ "ar": response_ar,
668
+ "en": response_en
669
+ }
670
+
671
+ # Select response based on language
672
+ response = responses[lang]
673
+
674
+ # Personalize response if name is available
675
+ if name:
676
+ if lang == "ar":
677
+ response = response.replace("مرحبًا", f"مرحبًا {name}")
678
+ else:
679
+ response = response.replace("Welcome", f"Welcome {name}")
680
+ response = response.replace("Hello", f"Hello {name}")
681
+
682
+ # Update bot response in chat history
683
+ chat_history[-1][1] = response
684
+
685
+ # Log the interaction
686
+ log_interaction(button_text, response, intent, lang)
687
+
688
  return chat_history
689
 
690
  # Handle live agent button click
691
  def connect_to_live_agent(chat_history, lang):
692
  message = "Connecting to a live customer service agent. Please wait a moment..." if lang == "en" else "جاري الاتصال بوكيل خدمة العملاء. يرجى الانتظار لحظة..."
693
+ chat_history = chat_history + [[None, message]]
694
  return chat_history
695
 
696
  # Handle satisfaction survey button click
697
  def show_satisfaction_survey(chat_history, lang):
698
  if CUSTOMER_SERVICE_ENHANCEMENTS_AVAILABLE:
699
  survey_html = offer_satisfaction_survey(lang)
700
+ chat_history = chat_history + [[None, survey_html]]
701
  else:
702
  # Simple survey message if enhancements not available
703
  title = "استطلاع رضا العملاء" if lang == "ar" else "Customer Satisfaction Survey"
704
  message = f"<div class='satisfaction-survey'><h3>{title}</h3><p>{'نشكرك على استخدام المساعد المصرفي الافتراضي!' if lang == 'ar' else 'Thank you for using our virtual banking assistant!'}</p></div>"
705
+ chat_history = chat_history + [[None, message]]
706
 
707
  return chat_history
708
 
 
735
  )
736
 
737
  # Link quick action buttons to handler function
738
+ balance_btn.click(
739
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("balance", chat, lang, name),
740
+ inputs=[chatbot, selected_lang, user_name],
741
+ outputs=[chatbot]
742
+ )
743
+
744
+ lost_card_btn.click(
745
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("lost_card", chat, lang, name),
746
+ inputs=[chatbot, selected_lang, user_name],
747
+ outputs=[chatbot]
748
+ )
749
+
750
+ loan_btn.click(
751
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("loan", chat, lang, name),
752
+ inputs=[chatbot, selected_lang, user_name],
753
+ outputs=[chatbot]
754
+ )
755
+
756
+ transfer_btn.click(
757
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("transfer", chat, lang, name),
758
+ inputs=[chatbot, selected_lang, user_name],
759
+ outputs=[chatbot]
760
+ )
761
+
762
+ new_account_btn.click(
763
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("new_account", chat, lang, name),
764
+ inputs=[chatbot, selected_lang, user_name],
765
+ outputs=[chatbot]
766
+ )
767
+
768
+ interest_btn.click(
769
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("interest_rates", chat, lang, name),
770
+ inputs=[chatbot, selected_lang, user_name],
771
+ outputs=[chatbot]
772
+ )
773
+
774
+ branches_btn.click(
775
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("branches", chat, lang, name),
776
+ inputs=[chatbot, selected_lang, user_name],
777
+ outputs=[chatbot]
778
+ )
779
+
780
+ hours_btn.click(
781
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("working_hours", chat, lang, name),
782
+ inputs=[chatbot, selected_lang, user_name],
783
+ outputs=[chatbot]
784
+ )
785
+
786
+ contact_btn.click(
787
+ fn=lambda chat=chatbot, lang=selected_lang, name=user_name: handle_quick_action("contact", chat, lang, name),
788
+ inputs=[chatbot, selected_lang, user_name],
789
+ outputs=[chatbot]
790
+ )
791
 
792
  # Also trigger on Enter key
793
  text_input.submit(
 
807
  chat_history.append([None, welcome_ar])
808
  chat_history.append([None, welcome_en])
809
 
810
+ return chat_history
 
 
 
 
 
 
 
 
 
 
 
811
 
812
  # Initialize the chat when the app starts
813
  demo.load(
814
  fn=init_chat,
815
  inputs=[],
816
+ outputs=[chatbot]
817
  )
818
 
819
  if __name__ == "__main__":