The chatbot code works well on the console but not when deployed on the website

40 views Asked by At

I tried to develop a chatbot using deep learning techniques and NLTK tools within the Python programming language. Initially, the chatbot performed satisfactorily when tested within the console environment, exhibiting no errors. However, upon attempting to deploy it onto a website, I encountered unexpected challenges. Specifically, the additional functionalities integrated into the 'chat.py' file failed to operate as intended, impeding the desired performance of the chatbot on the web platform.I have used Pytorch, and flask for the backend.

from flask import Flask, request, jsonify
import random
import json
import torch
import smtplib
import re
from datetime import datetime
from email.message import EmailMessage
from model import NeuralNet
from nltk_utils import bag_of_words, tokenize

app = Flask(__name__)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

with open('intents.json', 'r') as json_data:
    intents = json.load(json_data)

FILE = "data.pth"
data = torch.load(FILE)

input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data['all_words']
tags = data['tags']
model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
model.eval()

bot_name = "AID_ASL"

def is_valid_date(date_str):
    try:
        date_obj = datetime.strptime(date_str, '%d/%m/%Y')
        return date_obj >= datetime.now()
    except ValueError:
        return False

def is_valid_time(time_str):
    try:
        datetime.strptime(time_str, '%I:%M %p')
        return True
    except ValueError:
        return False

def is_valid_mobile_number(phone_number):
    return re.match(r'^\d{10}$', phone_number) is not None

def is_valid_email(email):
    return re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email) is not None

def find_hospitals(location, specialization):
    # Simulated hospitals data (replace this with your actual hospital data retrieval logic)
    hospitals = [
        {'name': 'Hospital A', 'location': 'Location A', 'specialization': 'Physician', 'email': '[email protected]'},
        {'name': 'Hospital B', 'location': 'Location B', 'specialization': 'Dermatologist', 'email': '[email protected]'},
        {'name': 'Hospital C', 'location': 'Location C', 'specialization': 'Cardiologist', 'email': '[email protected]'},
        {'name': 'Hospital A', 'location': 'Location B', 'specialization': 'Dermotologist', 'email': '[email protected]'},
        {'name': 'Hospital B', 'location': 'Location C', 'specialization': 'Cardiologist', 'email': '[email protected]'},
        {'name': 'Hospital C', 'location': 'Location A', 'specialization': 'Physician', 'email': '[email protected]'},
        {'name': 'Hospital A', 'location': 'Location C', 'specialization': 'Cardiologist', 'email': '[email protected]'},
        {'name': 'Hospital B', 'location': 'Location A', 'specialization': 'Physician', 'email': '[email protected]'},
        {'name': 'Hospital C', 'location': 'Location B', 'specialization': 'Dermotologist', 'email': '[email protected]'},
    ]

    # Search for hospitals based on location and specialization
    found_hospitals = [
        hospital for hospital in hospitals 
        if hospital['location'].lower() == location.lower() and hospital['specialization'].lower() == specialization.lower()
    ]
    
    return found_hospitals

def send_email(hospital_email, content):
    # SMTP configurations for Gmail
    smtp_server = 'smtp.gmail.com'
    port = 587  # Use port 465 for SSL connection
    sender_email = '[email protected]'
    password = 'srydtfufzdoxfoet'

    # Create message object
    message = EmailMessage()
    message['From'] = sender_email
    message['To'] = hospital_email
    message['Subject'] = 'Hospital Appointment Booking'
    message.set_content(content)

    try:
        # Connect to SMTP server and send email
        with smtplib.SMTP(smtp_server, port) as server:
            server.starttls()
            server.login(sender_email, password)
            server.send_message(message, from_addr=sender_email, to_addrs=[hospital_email])
            return True
    except smtplib.SMTPAuthenticationError:
        return False
    except smtplib.SMTPException:
        return False
    except Exception:
        return False

def get_chatbot_response(user_input):
    global bot_name, model, tags, intents, all_words, device

    sentence = tokenize(user_input)
    X = bag_of_words(sentence, all_words)
    X = X.reshape(1, X.shape[0])
    X = torch.from_numpy(X).to(device)

    output = model(X)
    _, predicted = torch.max(output, dim=1)

    tag = tags[predicted.item()]

    probs = torch.softmax(output, dim=1)
    prob = probs[0][predicted.item()]

    if prob.item() > 0.75:
        for intent in intents['intents']:
            if tag == intent["tag"]:
                response = random.choice(intent['responses'])

                if tag == 'hospital_appointment':
                    response += '\nCan you please provide your location?'

                    user_location = input("You: ")
                    response += f"\nYou: {user_location}"

                    response += '\nWhat specialization are you looking for? (e.g., physician, dermatologist)'
                    specialization = input("You: ")
                    response += f"\nYou: {specialization}"

                    found_hospitals = find_hospitals(user_location, specialization)
                    if found_hospitals:
                        for hospital in found_hospitals:
                            response += f"\n{bot_name}: {hospital['name']} - {hospital['specialization']} Department"
                            response += '\nWould you like to book an appointment at this hospital? (Yes/No)'

                            book_appointment = input("You: ")
                            response += f"\nYou: {book_appointment}"

                            if book_appointment.lower() == 'yes':
                                while True:
                                    response += '\nPlease provide preferred date (DD/MM/YYYY) for the appointment.'
                                    appointment_date = input("You (date): ")
                                    response += f"\nYou (date): {appointment_date}"
                                    if is_valid_date(appointment_date):
                                        break
                                    else:
                                        response += '\nInvalid date or date less than today. Please provide a valid date.'

                                while True:
                                    response += '\nPlease provide preferred time (HH:MM am/pm) for the appointment.'
                                    appointment_time = input("You (time): ")
                                    response += f"\nYou (time): {appointment_time}"
                                    if is_valid_time(appointment_time):
                                        break
                                    else:
                                        response += '\nInvalid time. Please provide a valid time.'

                                while True:
                                    response += '\nKindly provide your phone number for confirmation.'
                                    phone_number = input("You: ")
                                    response += f"\nYou: {phone_number}"
                                    if is_valid_mobile_number(phone_number):
                                        break
                                    else:
                                        response += '\nInvalid phone number. Please provide a valid 10-digit number.'

                                while True:
                                    response += '\nLastly, please share your email ID for further communication.'
                                    email_id = input("You: ")
                                    response += f"\nYou: {email_id}"
                                    if is_valid_email(email_id):
                                        break
                                    else:
                                        response += '\nInvalid email ID. Please provide a valid email address.'

                                # If all details are valid, proceed with the appointment booking
                                email_content = f"Appointment details: {appointment_date} {appointment_time}\nContact: {phone_number}, {email_id}"
                                send_email(hospital['email'], email_content)
                                response += '\nA mail has been sent to the hospital. Futher details will be shared shortly.'
                                break
                            else:
                                response += '\nOkay, let me know if you need further assistance.'
                    else:
                        response += '\nSorry, I couldn\'t find any hospitals matching your criteria.'
                return response
    else:
        return "I do not understand..."

@app.route('/chat', methods=['POST'])
def chat():
    data = request.get_json()
    user_input = data['user_input']
    response = get_chatbot_response(user_input)
    return jsonify({"response": response})

if __name__ == '__main__':
    app.run(debug=True)

All the rest of the files work well including json file but the problem seem to be with the chat.py file

0

There are 0 answers