Download app.py from SpiderGPT/zimspeak: direct link, hf CLI and curl.
- Browser
- Download file 3.85 kB
-
https://huggingface.co/spaces/SpiderGPT/zimspeak/resolve/main/app.py
- Command line
-
hf download hf://spaces/SpiderGPT/zimspeak/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SpiderGPT/zimspeak/resolve/main/app.py
3.85 kB
| import gradio as gr | |
| import tensorflow as tf | |
| import numpy as np | |
| import random | |
| import json | |
| import pickle | |
| import nltk | |
| # ============================= | |
| # 1) DOWNLOAD NLTK DATA FIX | |
| # ============================= | |
| # Avoid "punkt_tab not found" errors on Hugging Face Spaces or other hosts | |
| nltk.download("punkt_tab", quiet=True) | |
| nltk.download("punkt", quiet=True) | |
| nltk.download("wordnet", quiet=True) | |
| nltk.download("omw-1.4", quiet=True) | |
| lemmatizer = nltk.stem.WordNetLemmatizer() | |
| # ============================= | |
| # 2) LOAD YOUR MODEL & FILES | |
| # ============================= | |
| # Load your saved model (.h5) | |
| model = tf.keras.models.load_model("chatbot_model.h5") | |
| # Load words and classes from the .pkl files | |
| with open("words.pkl", "rb") as f: | |
| words = pickle.load(f) | |
| with open("classes.pkl", "rb") as f: | |
| classes = pickle.load(f) | |
| # Load intents | |
| with open("intents.json", "r") as f: | |
| intents_data = json.load(f) | |
| # For ignoring punctuation, etc. | |
| ignore_chars = ['?', '!', '.', ','] | |
| # ============================= | |
| # 3) HELPER FUNCTIONS | |
| # ============================= | |
| def clean_up_sentence(sentence): | |
| """ | |
| Tokenize & lemmatize the user input. | |
| """ | |
| sentence_words = nltk.word_tokenize(sentence) | |
| sentence_words = [ | |
| lemmatizer.lemmatize(word.lower()) | |
| for word in sentence_words | |
| if word not in ignore_chars | |
| ] | |
| return sentence_words | |
| def bag_of_words(sentence, vocabulary): | |
| """ | |
| Convert the input sentence to a bag-of-words vector | |
| matching the training vocabulary. | |
| """ | |
| sentence_words = clean_up_sentence(sentence) | |
| bag = [0] * len(vocabulary) | |
| for sw in sentence_words: | |
| for i, w in enumerate(vocabulary): | |
| if w == sw: | |
| bag[i] = 1 | |
| return np.array(bag) | |
| def predict_class(sentence): | |
| """ | |
| Predict the intent class for a given sentence. | |
| Returns a list of dicts: [{intent, probability}, ...] | |
| """ | |
| bow = bag_of_words(sentence, words) | |
| res = model.predict(np.array([bow]))[0] | |
| ERROR_THRESHOLD = 0.25 | |
| results = [] | |
| for i, prob in enumerate(res): | |
| if prob > ERROR_THRESHOLD: | |
| results.append({"intent": classes[i], "probability": float(prob)}) | |
| results.sort(key=lambda x: x["probability"], reverse=True) | |
| return results | |
| def get_response(intents_list, intents_json): | |
| """ | |
| Pick a response from the top predicted intent | |
| or return a default message if no predictions. | |
| """ | |
| if not intents_list: | |
| return "I’m not sure I understand. Could you rephrase?" | |
| top_intent = intents_list[0]["intent"] | |
| for i in intents_json["intents"]: | |
| if i["tag"] == top_intent: | |
| return random.choice(i["responses"]) | |
| return "I’m not sure I understand. Could you try again?" | |
| # ============================= | |
| # 4) GRADIO FUNCTION | |
| # ============================= | |
| def chatbot_respond(user_input, history): | |
| """ | |
| Called by Gradio for each new message. | |
| 'history' is a list of (user_msg, bot_msg) so far (not used here). | |
| """ | |
| # Predict intent | |
| intents = predict_class(user_input) | |
| # Get response from the top intent | |
| response = get_response(intents, intents_data) | |
| return response | |
| # ============================= | |
| # 5) CREATE GRADIO CHAT | |
| # ============================= | |
| demo = gr.ChatInterface( | |
| fn=chatbot_respond, | |
| title="ZimSpeak: Emotional Support Bot", | |
| description=""" | |
| **Disclaimer**: | |
| I am an **AI-based chatbot**, not a licensed mental health professional. | |
| I can offer empathy and general suggestions, **but I cannot provide professional advice**. | |
| If you are in crisis or need immediate support, please reach out to a **licensed mental health professional** or **emergency services**. | |
| """, | |
| ) | |
| # ============================= | |
| # 6) LAUNCH (LOCAL TEST) | |
| # ============================= | |
| if __name__ == "__main__": | |
| demo.launch() | |