聊天机器人代码在控制台正常,但在网站部署时不工作

-2 投票
0 回答
37 浏览
提问于 2025-04-12 02:51

我尝试用深度学习技术和NLTK工具在Python编程语言中开发一个聊天机器人。最开始,在控制台环境中测试时,聊天机器人表现得不错,没有出现错误。但是,当我试图把它放到网站上时,遇到了一些意想不到的问题。具体来说,'chat.py'文件中添加的功能没有按预期工作,这影响了聊天机器人在网页上的表现。我使用了Pytorch和Flask作为后端。

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': 'gowrisree71@gmail.com'},
        {'name': 'Hospital B', 'location': 'Location B', 'specialization': 'Dermatologist', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital C', 'location': 'Location C', 'specialization': 'Cardiologist', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital A', 'location': 'Location B', 'specialization': 'Dermotologist', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital B', 'location': 'Location C', 'specialization': 'Cardiologist', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital C', 'location': 'Location A', 'specialization': 'Physician', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital A', 'location': 'Location C', 'specialization': 'Cardiologist', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital B', 'location': 'Location A', 'specialization': 'Physician', 'email': 'gowrisree71@gmail.com'},
        {'name': 'Hospital C', 'location': 'Location B', 'specialization': 'Dermotologist', 'email': 'gowrisree71@gmail.com'},
    ]

    # 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 = 'speakheart8@gmail.com'
    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)

其他所有文件都运行得很好,包括json文件,但问题似乎出在chat.py文件上。

0 个回答

暂无回答

撰写回答