Instructions to use RedCatTeam/HruwChatBotv3 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use RedCatTeam/HruwChatBotv3 with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://RedCatTeam/HruwChatBotv3") - Notebooks
- Google Colab
- Kaggle
Upload main.py
Browse filesGUI on Flask for this AI
main.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tensorflow import keras
|
| 4 |
+
from sklearn.preprocessing import LabelEncoder
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import pickle
|
| 8 |
+
import time
|
| 9 |
+
from tensorflow import keras
|
| 10 |
+
import requests
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
from tkinter import *
|
| 13 |
+
import requests
|
| 14 |
+
from flask import *
|
| 15 |
+
import ssl
|
| 16 |
+
import pyjokes
|
| 17 |
+
from fast_langdetect import detect, detect_multilingual
|
| 18 |
+
from PIL import *
|
| 19 |
+
|
| 20 |
+
# Load intents from JSON file
|
| 21 |
+
with open("intents.json") as file:
|
| 22 |
+
data = json.load(file)
|
| 23 |
+
app = Flask('ai')
|
| 24 |
+
regs=[]
|
| 25 |
+
def translate_text(text, source_lang='ru', target_lang='en'):
|
| 26 |
+
# функция для перевода текста с заданного языка на целевой язык
|
| 27 |
+
url = "https://translate.googleapis.com/translate_a/single"
|
| 28 |
+
# URL для запроса к Google Translate API
|
| 29 |
+
params = {
|
| 30 |
+
"client": "gtx",
|
| 31 |
+
# клиент, использующий API
|
| 32 |
+
"sl": source_lang,
|
| 33 |
+
# исходный язык текста
|
| 34 |
+
"tl": target_lang,
|
| 35 |
+
# целевой язык перевода
|
| 36 |
+
"dt": "t",
|
| 37 |
+
# тип данных, которые запрашиваются (в данном случае текст)
|
| 38 |
+
"q": text
|
| 39 |
+
# текст, который необходимо перевести (убедитесь, что текст корректно закодирован в URL)
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
response = requests.get(url, params=params)
|
| 43 |
+
# выполнение GET-запроса с указанными параметрами
|
| 44 |
+
|
| 45 |
+
if response.status_code == 200:
|
| 46 |
+
# проверка успешности запроса (код ответа 200)
|
| 47 |
+
try:
|
| 48 |
+
result = response.json()
|
| 49 |
+
# попытка преобразовать ответ в формат JSON
|
| 50 |
+
translated_text = result[0][0][0]
|
| 51 |
+
# получение переведенного текста из ответа JSON
|
| 52 |
+
|
| 53 |
+
return translated_text
|
| 54 |
+
# возврат переведенного текста
|
| 55 |
+
except (IndexError, ValueError, TypeError) as e:
|
| 56 |
+
# обработка возможных ошибок при парсинге ответа
|
| 57 |
+
print(f"Error parsing translation response: {e}")
|
| 58 |
+
# вывод сообщения об ошибке
|
| 59 |
+
print("Response content:", response.content)
|
| 60 |
+
# вывод содержимого ответа для отладки
|
| 61 |
+
return None
|
| 62 |
+
# возврат None в случае ошибки
|
| 63 |
+
else:
|
| 64 |
+
# если запрос завершился с ошибкой (код ответа не 200)
|
| 65 |
+
print(f"Error with status code: {response.status_code}")
|
| 66 |
+
# вывод сообщения об ошибке с кодом ответа
|
| 67 |
+
print("Response content:", response.content)
|
| 68 |
+
# вывод содержимого ответа для отладки
|
| 69 |
+
return None
|
| 70 |
+
# возврат None в случае ошибки
|
| 71 |
+
model=keras.models.load_model('chat_model.keras')
|
| 72 |
+
def chat(text):
|
| 73 |
+
|
| 74 |
+
# Load tokenizer object
|
| 75 |
+
with open('tokenizer.pickle', 'rb') as handle:
|
| 76 |
+
tokenizer = pickle.load(handle)
|
| 77 |
+
|
| 78 |
+
# Load label encoder object
|
| 79 |
+
with open('label_encoder.pickle', 'rb') as enc:
|
| 80 |
+
lbl_encoder = pickle.load(enc)
|
| 81 |
+
|
| 82 |
+
# Parameters
|
| 83 |
+
max_len = 20
|
| 84 |
+
dc='en'
|
| 85 |
+
if detect(text)['lang']!='en':
|
| 86 |
+
dc=detect(text)['lang']
|
| 87 |
+
text=translate_text(text,dc,'en')
|
| 88 |
+
print(text)
|
| 89 |
+
inp = text
|
| 90 |
+
# Preprocess user input
|
| 91 |
+
sequence = tokenizer.texts_to_sequences([inp])
|
| 92 |
+
padded_sequence = keras.preprocessing.sequence.pad_sequences(sequence, truncating='post', maxlen=max_len)
|
| 93 |
+
|
| 94 |
+
# Predict intent
|
| 95 |
+
result = model.predict(padded_sequence)
|
| 96 |
+
tag = lbl_encoder.inverse_transform([np.argmax(result)])
|
| 97 |
+
if inp.lower().find('joke')>0 or inp.lower().find('just kidding')>0 or inp.lower().find('make joke')>0:
|
| 98 |
+
tag='joke'
|
| 99 |
+
|
| 100 |
+
# Find corresponding intent
|
| 101 |
+
for intent in data['intents']:
|
| 102 |
+
if tag=='joke':
|
| 103 |
+
return translater(pyjokes.get_joke(), dc)
|
| 104 |
+
if intent['tag'] == tag:
|
| 105 |
+
print("ChatBot: "+np.random.choice(intent['responses']))
|
| 106 |
+
if dc=='en':
|
| 107 |
+
return np.random.choice(intent['responses'])
|
| 108 |
+
else:
|
| 109 |
+
return translate_text(np.random.choice(intent['responses']),'en',dc)
|
| 110 |
+
|
| 111 |
+
app = Flask(__name__)
|
| 112 |
+
c=0
|
| 113 |
+
@app.route("/")
|
| 114 |
+
def home():
|
| 115 |
+
return render_template("index.html")
|
| 116 |
+
|
| 117 |
+
@app.route("/get")
|
| 118 |
+
def get_bot_response():
|
| 119 |
+
userText = request.args.get('msg')
|
| 120 |
+
return chat(userText)
|
| 121 |
+
@app.route("/get/api/key12004/key/1043967:lso10/<msg>",methods=['GET'])
|
| 122 |
+
def get_response(msg):
|
| 123 |
+
return chat(msg)
|
| 124 |
+
@app.route("/reg/<regn>",methods=["POST"])
|
| 125 |
+
def reg(regn,data):
|
| 126 |
+
if regn:
|
| 127 |
+
if data=="appsofosaz1111":
|
| 128 |
+
regs.append(data)
|
| 129 |
+
@app.errorhandler(404)
|
| 130 |
+
|
| 131 |
+
# inbuilt function which takes error as parameter
|
| 132 |
+
def not_found(e):
|
| 133 |
+
|
| 134 |
+
# defining function
|
| 135 |
+
return render_template("404.html")
|
| 136 |
+
@app.route("/change/for_developers/reg/change")
|
| 137 |
+
def main():
|
| 138 |
+
if True:
|
| 139 |
+
return render_template("change.html")
|
| 140 |
+
if __name__ == '__main__':
|
| 141 |
+
app.run(host='0.0.0.0',port=80)
|
| 142 |
+
|