File size: 5,398 Bytes
26a814f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import json
import numpy as np 
from tensorflow import keras
from sklearn.preprocessing import LabelEncoder
import os
import random
import pickle
import time
from tensorflow import keras
import requests
import matplotlib.pyplot as plt
from tkinter import *
import requests
from flask import *
import ssl
import pyjokes
from fast_langdetect import detect, detect_multilingual
from PIL import *

# Load intents from JSON file
with open("intents.json") as file:
    data = json.load(file)
app = Flask('ai')
regs=[]
def translate_text(text, source_lang='ru', target_lang='en'):
    # функция для перевода текста с заданного языка на целевой язык
    url = "https://translate.googleapis.com/translate_a/single"
    # URL для запроса к Google Translate API
    params = {
        "client": "gtx",
        # клиент, использующий API
        "sl": source_lang,
        # исходный язык текста
        "tl": target_lang,
        # целевой язык перевода
        "dt": "t",
        # тип данных, которые запрашиваются (в данном случае текст)
        "q": text
        # текст, который необходимо перевести (убедитесь, что текст корректно закодирован в URL)
    }

    response = requests.get(url, params=params)
    # выполнение GET-запроса с указанными параметрами

    if response.status_code == 200:
        # проверка успешности запроса (код ответа 200)
        try:
            result = response.json()
            # попытка преобразовать ответ в формат JSON
            translated_text = result[0][0][0]
            # получение переведенного текста из ответа JSON

            return translated_text
            # возврат переведенного текста
        except (IndexError, ValueError, TypeError) as e:
            # обработка возможных ошибок при парсинге ответа
            print(f"Error parsing translation response: {e}")
            # вывод сообщения об ошибке
            print("Response content:", response.content)
            # вывод содержимого ответа для отладки
            return None
            # возврат None в случае ошибки
    else:
        # если запрос завершился с ошибкой (код ответа не 200)
        print(f"Error with status code: {response.status_code}")
        # вывод сообщения об ошибке с кодом ответа
        print("Response content:", response.content)
        # вывод содержимого ответа для отладки
        return None
        # возврат None в случае ошибки
model=keras.models.load_model('chat_model.keras')
def chat(text):
    
    # Load tokenizer object
    with open('tokenizer.pickle', 'rb') as handle:
        tokenizer = pickle.load(handle)
    
    # Load label encoder object
    with open('label_encoder.pickle', 'rb') as enc:
        lbl_encoder = pickle.load(enc)
    
    # Parameters
    max_len = 20
    dc='en'
    if detect(text)['lang']!='en':
        dc=detect(text)['lang']
        text=translate_text(text,dc,'en')
    print(text)
    inp = text
    # Preprocess user input
    sequence = tokenizer.texts_to_sequences([inp])
    padded_sequence = keras.preprocessing.sequence.pad_sequences(sequence, truncating='post', maxlen=max_len)
        
    # Predict intent
    result = model.predict(padded_sequence)
    tag = lbl_encoder.inverse_transform([np.argmax(result)])
    if inp.lower().find('joke')>0 or inp.lower().find('just kidding')>0 or inp.lower().find('make joke')>0:
        tag='joke'
        
    # Find corresponding intent
    for intent in data['intents']:
        if tag=='joke':
            return translater(pyjokes.get_joke(), dc)
        if intent['tag'] == tag:
            print("ChatBot: "+np.random.choice(intent['responses']))
            if dc=='en':
                return np.random.choice(intent['responses'])
            else:
                return translate_text(np.random.choice(intent['responses']),'en',dc)
                
app = Flask(__name__)
c=0
@app.route("/")
def home():
    return render_template("index.html")
    
@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return chat(userText)
@app.route("/get/api/key12004/key/1043967:lso10/<msg>",methods=['GET'])
def get_response(msg):
    return chat(msg)
@app.route("/reg/<regn>",methods=["POST"])
def reg(regn,data):
    if regn:
        if data=="appsofosaz1111":
            regs.append(data)
@app.errorhandler(404) 
  
# inbuilt function which takes error as parameter 
def not_found(e): 
  
    # defining function 
    return render_template("404.html") 
@app.route("/change/for_developers/reg/change")
def main():
    if True:
        return render_template("change.html")
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80)