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
Download main.py from RedCatTeam/HruwChatBotv3: direct link, hf CLI and curl.
- Browser
- Download file 5.4 kB
-
https://huggingface.co/RedCatTeam/HruwChatBotv3/resolve/main/main.py
- Command line
-
hf download hf://RedCatTeam/HruwChatBotv3/main.py
-
curl -L -o main.py https://huggingface.co/RedCatTeam/HruwChatBotv3/resolve/main/main.py
5.4 kB
| 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 | |
| def home(): | |
| return render_template("index.html") | |
| def get_bot_response(): | |
| userText = request.args.get('msg') | |
| return chat(userText) | |
| def get_response(msg): | |
| return chat(msg) | |
| def reg(regn,data): | |
| if regn: | |
| if data=="appsofosaz1111": | |
| regs.append(data) | |
| # inbuilt function which takes error as parameter | |
| def not_found(e): | |
| # defining function | |
| return render_template("404.html") | |
| def main(): | |
| if True: | |
| return render_template("change.html") | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0',port=80) | |