Skip to content

About

Bilingual cafe assistant chatbot built with NLP techniques, handling customer queries in English and Urdu. Focused on practical AI application and conversational flow design.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

Repository files navigation

Floro Café Chatbot

Overview

Floro is a bilingual (English/Urdu) conversational chatbot designed to automate café order processing, with a primary focus on robust backend logic. Built with Python, PyTorch, and NLTK, it enables users to place orders for tea and coffee, specify delivery locations (Islamabad, Lahore, Karachi), choose payment methods (cash on delivery or online with Visa/Mastercard/Paypak), and query delivery times (20–40 minutes). A functional Tkinter GUI provides a user-friendly interface backed by a neural network for natural language understanding (NLU).

Chatbot Interface 1

Chatbot Screenshot 1

Chatbot Interface 2

Chatbot Screenshot 2


Key Features

  • Bilingual Support: Processes English and Urdu inputs (e.g., "I want tea" or "mujhe chai chahiye").
  • Order Management: Handles orders with quantities (e.g., "2 chai") and provides order summaries.
  • Delivery Flow: Validates locations and supports cash or online payments with card type selection.
  • NLU: Employs a PyTorch feedforward neural network to classify intents (e.g., ordering, delivery queries).
  • GUI: Tkinter interface with a Mocha brown theme, scrolled chat area, and input field.
  • Error Handling: Robust against invalid inputs and GUI errors (e.g., _tkinter.TclError).

Project Structure

nlp_project/
│
├── app.py            # Main Tkinter GUI and chatbot logic
├── chat.py           # Console-based chatbot (predecessor to app.py)
├── train.py          # Script to train the PyTorch NLU model
├── model.py          # Neural network model definition
├── nltk_utils.py     # NLTK utilities for tokenization and bag-of-words
├── intents.json      # Intent patterns and responses for NLU
├── data.pth          # Trained model weights
└── README.md         # Project documentation

File Descriptions

  • app.py: The main application, integrating the Tkinter GUI and chatbot backend. Handles user interactions, processes inputs via NLU, manages order and delivery states, and renders responses in a scrolled chat area. Key components include get_floro_response for backend logic and build_gui for frontend rendering.
  • chat.py: A console-based version of the chatbot, serving as the predecessor to app.py. Contains the same backend logic but uses terminal input/output for testing and development.
  • train.py: Trains the PyTorch NLU model. Processes intents.json to create a dataset, trains a neural network (model.py), and saves weights to data.pth.
  • model.py: Defines the NeuralNet class — a three-layer PyTorch feedforward network for intent classification.
  • nltk_utils.py: Provides NLP utilities: tokenize (splits text into tokens) and bag_of_words (converts tokens to numerical feature vectors for NLU).
  • intents.json: Contains intent patterns (e.g., "mujhe chai chahiye") and responses (e.g., "Zabardast!") for both English and Urdu. Used by train.py and app.py.
  • data.pth: Stores trained model weights generated by train.py and loaded by app.py for inference.

Setup Instructions

Prerequisites

  • Python 3.13
  • Libraries: torch, nltk, tkinter (bundled with Python)
  • NLTK data: punkt tokenizer

Installation

  1. Clone the repository or copy all files into a local directory (e.g., C:\Users\Hp\Documents\nlp_project).

  2. Install dependencies:

    pip install torch nltk

    For CPU-only PyTorch:

    pip3 install torch torchvision torchaudio
  3. Download NLTK data:

    import nltk
    nltk.download('punkt')

    Note (Windows): If you encounter an error, also run nltk.download('punkt_tab') in train.py.

  4. Ensure intents.json and data.pth are present in the project directory.

  5. (Optional) If data.pth is missing, retrain the model:

    python train.py

Running the Application

Navigate to the project directory:

cd C:\Users\Hp\Documents\nlp_project

Launch the GUI:

python app.py

Select a language (English or Urdu) and interact with the chatbot.


Architecture

Backend

FloroChatbot Logic (app.py): The core focus of the project. Manages conversational state via two dictionaries:

  • order_flow: tracks items ordered and running total.
  • delivery_flow: tracks delivery location, payment method, and card type.

Processes inputs using a combination of rule-based regex logic and NLU for bilingual functionality (e.g., "2 chai" → Tea x2, Rs. 220).

NLU:

  • PyTorch neural network (model.py) trained on intents.json.
  • Classifies intents (e.g., order_start, delivery_time) using a bag-of-words representation (nltk_utils.py).
  • Trained weights stored in data.pth. The model reaches near-zero training loss on the custom-built intent dataset.

Intents (intents.json): Defines patterns and responses for all supported intents in both English and Urdu.

Frontend

Tkinter GUI (app.py): A functional interface with a scrolled chat area, input field, and Send button.

  • Uses a Mocha brown theme (#4E342E) with Comic Sans MS font.
  • Prevents race conditions with an is_processing flag.
  • Handles _tkinter.TclError with a delayed root.destroy() on exit.

Integration

  • Communication: send_message (frontend) calls get_floro_response (backend) for each user input.
  • State Management: Backend maintains order_flow and delivery_flow, surfaced to the user via show_order_summary.

Core Code Snippets

1. GUI Setup (app.py)

Sets up the Tkinter interface with a chat area and input field.

def build_gui(self):
    header = tk.Label(self.root, text="Floro ☕ - Your Café Assistant",
                     font=("Arial", 16, "bold"), bg=BG_COLOR, fg=CHAT_BG)
    header.pack(pady=10)
    self.chat_area = scrolledtext.ScrolledText(self.root, wrap=tk.WORD, width=50, height=15,
                                              font=FONT, bg=CHAT_BG, fg=TEXT_COLOR, bd=0, relief="flat")
    self.chat_area.pack(padx=10, pady=5)
    self.chat_area.config(state=tk.DISABLED)
    self.entry_frame = tk.Frame(self.root, bg=BG_COLOR)
    self.entry_frame.pack(pady=10)
    self.user_input = tk.Entry(self.entry_frame, width=40, font=FONT, bg=CHAT_BG, fg=TEXT_COLOR)
    self.user_input.grid(row=0, column=0, padx=10)
    self.user_input.bind("<Return>", self.send_message)
    send_btn = tk.Button(self.entry_frame, text="Send", bg=BUTTON_COLOR, fg="white",
                        font=("Comic Sans MS", 12, "bold"), bd=0, padx=10, pady=5,
                        command=self.send_message)
    send_btn.grid(row=0, column=1)

Creates a Tkinter window with a header, scrolled chat area (ScrolledText), input field (Entry), and Send button. The <Return> binding and is_processing flag prevent race conditions on rapid input.


2. NLU Processing (app.py)

Classifies user intents using the trained PyTorch model.

tokens = tokenize(sentence)
X = bag_of_words(tokens, self.all_words)
X = X.reshape(1, X.shape[0])
X = torch.from_numpy(X).to(self.device)
output = self.model(X)
_, predicted = torch.max(output, dim=1)
tag = self.tags[predicted.item()]
probs = torch.softmax(output, dim=1)
prob = probs[0][predicted.item()]
if prob.item() > 0.5:
    self.last_tag = tag
    for intent in self.intents["intents"]:
        if tag == intent["tag"]:
            response_obj = random.choice(intent["responses"])
            if isinstance(response_obj, dict):
                response = response_obj.get(self.language, "Sorry, I don't have a response.")
            else:
                response = response_obj

Tokenizes input, converts to a bag-of-words vector, and runs inference. Predicts an intent with a confidence threshold of prob > 0.5 and selects a bilingual response from intents.json.


3. Order Processing (app.py)

Handles order inputs with quantities using regex extraction.

matches = re.findall(r'(\d+)?\s*(cups? of)?\s*(tea|coffee|chai)', sentence.lower())
if not matches:
    matches = [(None, None, word) for word in ["tea", "coffee", "chai"] if word in sentence.lower()]
for quantity, _, item in matches:
    item = "tea" if item == "chai" else item.lower()
    quantity = int(quantity) if quantity else 1
    if item in self.item_prices:
        self.order_flow["items"][item] = self.order_flow["items"].get(item, 0) + quantity
        self.order_flow["total"] += self.item_prices[item] * quantity
if self.order_flow["items"]:
    items_summary = ", ".join([f"{itm.capitalize()} x{q}" for itm, q in self.order_flow["items"].items()])
    response = f"{'Added to your order: ' if self.language == 'english' else 'Apkay order mein shamil: '}{items_summary}. {'Would you like to confirm this order? (yes/no)' if self.language == 'english' else 'Kya aap yeh order confirm karna chahte hain? (yes/no)'}"

Extracts quantities and items via regex (e.g., "2 chai" → Tea x2). Updates order_flow with item counts and total cost (Tea: Rs. 110, Coffee: Rs. 180), then generates a bilingual confirmation prompt.


4. Neural Network Definition (model.py)

import torch.nn as nn

class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.l1 = nn.Linear(input_size, hidden_size)
        self.l2 = nn.Linear(hidden_size, hidden_size)
        self.l3 = nn.Linear(hidden_size, num_classes)
        self.relu = nn.ReLU()
    
    def forward(self, x):
        out = self.l1(x)
        out = self.relu(out)
        out = self.l2(out)
        out = self.relu(out)
        out = self.l3(out)
        return out

A three-layer feedforward network with ReLU activations. input_size is the bag-of-words vocabulary length, hidden_size is configurable (default: 8), and num_classes is the number of intent categories. Used by both train.py and app.py.


5. Intent Sample (intents.json)

{
  "intents": [
    {
      "tag": "delivery_time",
      "patterns": [
        "How long does delivery take?",
        "How long will it take?",
        "kitni dair lagy gi?",
        "itni dair?"
      ],
      "responses": [
        {
          "english": "Delivery takes 20 - 40 minutes.",
          "urdu": "Delivery mein 20 - 40 minutes lagtay hain."
        }
      ]
    }
  ]
}

Each intent specifies patterns (training examples) and bilingual responses. Loaded by train.py to build the dataset and by app.py at runtime for response generation.


Usage Guide

Start the Application

python app.py

Select a language by typing English or Urdu.

Example Session (Urdu)

You:   Urdu
Floro: Urdu zuban chuni gayi hai.

You:   mujhe 2 chai chahiye
Floro: Apkay order mein shamil: Tea x2. Kya aap yeh order confirm karna chahte hain? (yes/no)

You:   yes
Floro: Zabardast! Apna address batayein.

You:   Islamabad
Floro: Jee haan, hum Islamabad mein deliver karte hain! Online payment ya cash on delivery?

You:   online payment
Floro: Kya aap Visa, Mastercard, ya Paypak se karenge?

You:   Visa
Floro: Order confirm hua: Tea x2.
       Kul: Rs. 220 ke zariye online payment Visa.
       Apka order Islamabad ko deliver hoga! Shukriya!

You:   kitni dair lagy gi?
Floro: Delivery mein 20 - 40 minutes lagtay hain.

You:   close
Floro: Khuda hafiz!

Order Summary

Type summary (English) or kitna order kiya (Urdu) at any point to view current order details.

Invalid Location Handling

You:   faisalabad deliver karte ho?
Floro: Maaf kijiye, hum sirf Islamabad, Lahore, aur Karachi mein deliver karte hain.

You:   faisalabad nahi hai?
Floro: Maaf kijiye, hum ab bhi sirf Islamabad, Lahore aur Karachi mein deliver karte hain.
       Inme se kisi ke liye order karna chahte hain?

Future Improvements

  • Web Frontend: Replace Tkinter with a Flask-based web interface for broader accessibility.
  • REST API: Expose FloroChatbot as a backend API for integration with other clients.
  • Enhanced Urdu NLU: Improve Urdu tokenization using indic-nlp-library.
  • GUI Enhancements: Add Clear and Reset buttons.
  • Persistent Storage: Store order history in SQLite.

Contributing

Fork the repository and submit pull requests. For issues or suggestions, contact the developer directly.


Acknowledgments

Built with Python, PyTorch, NLTK, and Tkinter.
Inspired by bilingual customer service needs in Pakistan.

About

Bilingual cafe assistant chatbot built with NLP techniques, handling customer queries in English and Urdu. Focused on practical AI application and conversational flow design.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages