import re import nltk import gradio as gr from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity nltk.download("stopwords", quiet=True) faq_data = { "What is Artificial Intelligence?":"Artificial Intelligence (AI) is the simulation of human intelligence by machines.", "What is Machine Learning?":"Machine Learning is a subset of AI that enables computers to learn from data.", "What is Deep Learning?":"Deep Learning is a branch of Machine Learning based on neural networks.", "What is NLP?":"Natural Language Processing enables computers to understand human language.", "What is Python?":"Python is a programming language widely used for AI and web development.", "Who developed Python?":"Python was created by Guido van Rossum.", "What is Hugging Face?":"Hugging Face is a platform for machine learning models and datasets.", "What is Google Colab?":"Google Colab is a free cloud notebook for Python.", "What is Gradio?":"Gradio lets you build web interfaces for Python models.", "What is cosine similarity?":"Cosine similarity measures similarity between text vectors." } stop_words=set(stopwords.words("english")) def preprocess(text): text=text.lower() text=re.sub(r"[^a-z0-9 ]"," ",text) return " ".join([w for w in text.split() if w not in stop_words]) questions=list(faq_data.keys()) answers=list(faq_data.values()) vectorizer=TfidfVectorizer() X=vectorizer.fit_transform([preprocess(q) for q in questions]) def chatbot(msg,history): if not msg.strip(): return "",history vec=vectorizer.transform([preprocess(msg)]) sims=cosine_similarity(vec,X)[0] idx=sims.argmax() if sims[idx] < 0.25: ans="Sorry, I couldn't find a relevant answer." else: ans=answers[idx] history=history or [] history.append({"role":"user","content":msg}) history.append({"role":"assistant","content":ans}) return "",history css=""" .gradio-container{max-width:1000px!important} footer{display:none} """ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo: gr.Markdown("# 🤖 FAQ Chatbot\nAsk a question from the FAQ database.") chat=gr.Chatbot(type="messages",height=450) with gr.Row(): txt=gr.Textbox(placeholder="Ask your question...",scale=8) btn=gr.Button("Send") clr=gr.Button("Clear") gr.Examples( examples=[["What is AI?"],["What is Python?"],["What is Hugging Face?"]], inputs=txt ) btn.click(chatbot,[txt,chat],[txt,chat]) txt.submit(chatbot,[txt,chat],[txt,chat]) clr.click(lambda:("",[]),outputs=[txt,chat]) if __name__=="__main__": demo.launch()