Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240import osimport gradio as grimport pandas as pdimport numpy as npfrom ai_chatbot import AIChatbotfrom database_recommender import CourseRecommenderimport warningsimport logging# Suppress warningswarnings.filterwarnings('ignore')logging.getLogger('tensorflow').setLevel(logging.ERROR)# Initialize componentstry:chatbot = AIChatbot()print("✅ Chatbot initialized successfully")except Exception as e:print(f"⚠️ Warning: Could not initialize chatbot: {e}")chatbot = Nonetry:recommender = CourseRecommender()print("✅ Recommender initialized successfully")except Exception as e:print(f"⚠️ Warning: Could not initialize recommender: {e}")recommender = Nonedef chat_with_bot(message, history):"""Handle chatbot interactions"""if chatbot is None:return "Sorry, the chatbot is not available at the moment. Please try again later."if not message.strip():return "Please enter a message to start the conversation."# Get answer from chatbotanswer, confidence = chatbot.find_best_match(message)# For general conversation, just return the answer# For FAQ questions, include suggested questionsif confidence > 0.7: # High confidence FAQ matchsuggested_questions = chatbot.get_suggested_questions(message)if suggested_questions:response = f"{answer}\n\n**Related Questions:**\n"for i, q in enumerate(suggested_questions, 1):response += f"{i}. {q}\n"return response# For general conversation or low confidence, just return the answerreturn answerdef get_course_recommendations(stanine, gwa, strand, hobbies):"""Get course recommendations"""if recommender is None:return "Sorry, the recommendation system is not available at the moment. Please try again later."try:# Validate and convert inputstry:stanine = int(stanine.strip()) if stanine else 0except (ValueError, AttributeError):return "❌ Stanine score must be a valid number between 1 and 9"try:gwa = float(gwa.strip()) if gwa else 0except (ValueError, AttributeError):return "❌ GWA must be a valid number between 75 and 100"# Validate rangesif not (1 <= stanine <= 9):return "❌ Stanine score must be between 1 and 9"if not (75 <= gwa <= 100):return "❌ GWA must be between 75 and 100"if not strand:return "❌ Please select a strand"if not hobbies or not hobbies.strip():return "❌ Please enter your hobbies/interests"# Get recommendationsrecommendations = recommender.recommend_courses(stanine=stanine,gwa=gwa,strand=strand,hobbies=hobbies)if not recommendations:return "No recommendations available at the moment."# Format recommendationsresponse = f"## 🎯 Course Recommendations for You\n\n"response += f"**Profile:** Stanine {stanine}, GWA {gwa}, {strand} Strand\n"response += f"**Interests:** {hobbies}\n\n"for i, rec in enumerate(recommendations, 1):response += f"### {i}. {rec['code']} - {rec['name']}\n"response += f"**Match Score:** {rec.get('rating', rec.get('probability', 0)):.1f}%\n\n"return responseexcept Exception as e:return f"❌ Error getting recommendations: {str(e)}"def get_faqs():"""Get available FAQs"""if chatbot and chatbot.faqs:faq_text = "## 📚 Frequently Asked Questions\n\n"for i, faq in enumerate(chatbot.faqs, 1):faq_text += f"**{i}. {faq['question']}**\n"faq_text += f"{faq['answer']}\n\n"return faq_textreturn "No FAQs available at the moment."def get_available_courses():"""Get available courses"""if recommender and recommender.courses:course_text = "## 🎓 Available Courses\n\n"for code, name in recommender.courses.items():course_text += f"**{code}** - {name}\n"return course_textreturn "No courses available at the moment."# Create Gradio interfacewith gr.Blocks(title="PSAU AI Chatbot & Course Recommender", theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🤖 PSAU AI Chatbot & Course RecommenderWelcome to the Pangasinan State University AI-powered admission assistant!Get instant answers to your questions and receive personalized course recommendations.""")with gr.Tabs():# Chatbot Tabwith gr.Tab("🤖 AI Chatbot"):gr.Markdown("""**Chat with the PSAU AI Assistant!**I can help you with:• University admission questions• Course information and guidance• General conversation• Academic supportJust type your message below and I'll respond naturally!""")chatbot_interface = gr.ChatInterface(fn=chat_with_bot,title="PSAU AI Assistant",description="Chat with me about university admissions, courses, or just say hello!",examples=["Hello!","What are the admission requirements?","How are you?","What courses are available?","Tell me about PSAU","What can you help me with?","Thank you","Goodbye"],cache_examples=True)# Course Recommender Tabwith gr.Tab("🎯 Course Recommender"):gr.Markdown("""Get personalized course recommendations based on your academic profile and interests!**Input Guidelines:**- **Stanine Score**: Enter a number between 1-9 (from your entrance exam)- **GWA**: Enter your General Weighted Average (75-100)- **Strand**: Select your senior high school strand- **Hobbies**: Describe your interests and hobbies in detail""")with gr.Row():with gr.Column():stanine_input = gr.Textbox(label="Stanine Score (1-9)",placeholder="Enter your stanine score (1-9)",info="Your stanine score from entrance examination",value="7")gwa_input = gr.Textbox(label="GWA (75-100)",placeholder="Enter your GWA (75-100)",info="Your General Weighted Average",value="85.0")strand_input = gr.Dropdown(choices=["STEM", "ABM", "HUMSS"],value="STEM",label="High School Strand",info="Your senior high school strand")hobbies_input = gr.Textbox(label="Hobbies & Interests",placeholder="e.g., programming, gaming, business, teaching, healthcare...",info="Describe your interests and hobbies")recommend_btn = gr.Button("Get Recommendations", variant="primary")with gr.Column():recommendations_output = gr.Markdown()recommend_btn.click(fn=get_course_recommendations,inputs=[stanine_input, gwa_input, strand_input, hobbies_input],outputs=recommendations_output)# Information Tabwith gr.Tab("📚 Information"):with gr.Row():with gr.Column():gr.Markdown("### FAQ Section")faq_btn = gr.Button("Show FAQs")faq_output = gr.Markdown()faq_btn.click(fn=get_faqs, outputs=faq_output)with gr.Column():gr.Markdown("### Available Courses")courses_btn = gr.Button("Show Courses")courses_output = gr.Markdown()courses_btn.click(fn=get_available_courses, outputs=courses_output)if __name__ == "__main__":demo.launch(server_name="0.0.0.0",server_port=7860,share=False,show_error=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630import gradio as grimport requestsimport jsonimport refrom typing import List, Tuple, Optionalfrom difflib import SequenceMatcherimport stringclass AIChatbot:def __init__(self, database_url: str = "https://database-dhe2.onrender.com"):self.database_url = database_urlself.conversation_history = []# Simple conversation patternsself.greeting_patterns = [r'\b(hi|hello|hey|good morning|good afternoon|good evening)\b',r'\b(how are you|how\'s it going|what\'s up)\b']self.help_patterns = [r'\b(help|assist|support|guide)\b',r'\b(what can you do|what do you do|your capabilities)\b']self.thanks_patterns = [r'\b(thank you|thanks|appreciate|grateful)\b']self.goodbye_patterns = [r'\b(bye|goodbye|see you|farewell|exit|quit)\b']def is_greeting(self, message: str) -> bool:"""Check if the message is a greeting"""message_lower = message.lower()for pattern in self.greeting_patterns:if re.search(pattern, message_lower):return Truereturn Falsedef is_help_request(self, message: str) -> bool:"""Check if the message is asking for help"""message_lower = message.lower()for pattern in self.help_patterns:if re.search(pattern, message_lower):return Truereturn Falsedef is_thanks(self, message: str) -> bool:"""Check if the message is expressing thanks"""message_lower = message.lower()for pattern in self.thanks_patterns:if re.search(pattern, message_lower):return Truereturn Falsedef is_goodbye(self, message: str) -> bool:"""Check if the message is a goodbye"""message_lower = message.lower()for pattern in self.goodbye_patterns:if re.search(pattern, message_lower):return Truereturn Falsedef get_greeting_response(self) -> str:"""Generate a greeting response"""responses = ["Hello! I'm your AI assistant. How can I help you today?","Hi there! I'm here to assist you with any questions you might have.","Hello! Welcome! I can help you with general conversation or answer specific questions from our database.","Hey! Nice to meet you! What can I do for you today?"]import randomreturn random.choice(responses)def get_help_response(self) -> str:"""Generate a help response"""return """I'm an AI chatbot that can help you in two ways:1. **General Conversation**: I can chat with you about various topics, answer greetings, and have friendly conversations.2. **Specific Questions**: I can search our database for specific information and provide detailed answers to your questions.**Smart Learning**: If I can't find an answer to your question, I'll automatically save it for review so we can improve our knowledge base and provide better answers in the future.Just type your question or start a conversation, and I'll do my best to help you!"""def get_thanks_response(self) -> str:"""Generate a thanks response"""responses = ["You're welcome! I'm happy to help.","My pleasure! Feel free to ask if you need anything else.","Glad I could assist you! Is there anything else you'd like to know?","You're very welcome! I'm here whenever you need help."]import randomreturn random.choice(responses)def get_goodbye_response(self) -> str:"""Generate a goodbye response"""responses = ["Goodbye! Have a great day!","See you later! Take care!","Farewell! Feel free to come back anytime.","Bye! I enjoyed chatting with you!"]import randomreturn random.choice(responses)def save_unanswered_question(self, question: str) -> bool:"""Save unanswered question to the database"""try:# Try different possible endpoints for saving unanswered questionsendpoints = [f"{self.database_url}/unanswered_questions",f"{self.database_url}/api/unanswered_questions",f"{self.database_url}/save_question",f"{self.database_url}/api/save_question"]for endpoint in endpoints:try:# Try POST request with JSON body - matching your table structureresponse = requests.post(endpoint,json={"question": question,"created_at": self._get_timestamp()},headers={"Content-Type": "application/json"},timeout=10)if response.status_code in [200, 201]:return Trueexcept:try:# Try GET request with query parametersresponse = requests.get(endpoint,params={"question": question,"created_at": self._get_timestamp()},timeout=10)if response.status_code in [200, 201]:return Trueexcept:continuereturn Falseexcept Exception as e:print(f"Error saving unanswered question: {e}")return Falsedef _get_timestamp(self) -> str:"""Get current timestamp in ISO format"""from datetime import datetimereturn datetime.now().isoformat()def _normalize_text(self, text: str) -> str:"""Normalize text for better matching"""# Convert to lowercasetext = text.lower()# Remove punctuationtext = text.translate(str.maketrans('', '', string.punctuation))# Remove extra whitespacetext = ' '.join(text.split())return textdef _extract_keywords(self, text: str) -> List[str]:"""Extract important keywords from text with enhanced processing"""# Extended stop words to ignorestop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by','is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did','will', 'would', 'could', 'should', 'may', 'might', 'can', 'what', 'how', 'when', 'where', 'why','who', 'which', 'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they','me', 'him', 'her', 'us', 'them', 'my', 'your', 'his', 'her', 'its', 'our', 'their','there', 'here', 'some', 'any', 'all', 'each', 'every', 'much', 'many', 'more', 'most','very', 'just', 'only', 'also', 'even', 'still', 'yet', 'so', 'too', 'well', 'now', 'then'}# Normalize and split into wordswords = self._normalize_text(text).split()# Enhanced keyword extractionkeywords = []for word in words:# Filter out stop words and very short wordsif word not in stop_words and len(word) > 2:# Add the wordkeywords.append(word)# Add common variations and stemsif word.endswith('s') and len(word) > 3:keywords.append(word[:-1]) # Remove 's' for pluralsif word.endswith('ing') and len(word) > 4:keywords.append(word[:-3]) # Remove 'ing'if word.endswith('ed') and len(word) > 3:keywords.append(word[:-2]) # Remove 'ed'return list(set(keywords)) # Remove duplicatesdef _calculate_similarity(self, text1: str, text2: str) -> float:"""Calculate similarity between two texts using advanced methods"""norm1 = self._normalize_text(text1)norm2 = self._normalize_text(text2)# Method 1: Sequence matcher on normalized textsequence_similarity = SequenceMatcher(None, norm1, norm2).ratio()# Method 2: Enhanced keyword overlap with stemmingkeywords1 = set(self._extract_keywords(text1))keywords2 = set(self._extract_keywords(text2))keyword_similarity = 0.0if keywords1 and keywords2:intersection = keywords1.intersection(keywords2)union = keywords1.union(keywords2)keyword_similarity = len(intersection) / len(union) if union else 0.0# Method 3: Substring containment (both directions)contains_similarity = 0.0if norm1 in norm2:contains_similarity = max(contains_similarity, 0.9 * (len(norm1) / len(norm2)))if norm2 in norm1:contains_similarity = max(contains_similarity, 0.9 * (len(norm2) / len(norm1)))# Method 4: Word order similaritywords1 = norm1.split()words2 = norm2.split()word_order_similarity = 0.0if words1 and words2:# Check for common word sequencescommon_sequences = 0max_len = min(len(words1), len(words2))for i in range(max_len):if words1[i] == words2[i]:common_sequences += 1word_order_similarity = common_sequences / max_len if max_len > 0 else 0.0# Method 5: Semantic similarity using word relationshipssemantic_similarity = self._calculate_semantic_similarity(keywords1, keywords2)# Method 6: Length similarity (shorter queries should match longer answers)length_similarity = 0.0if len(norm1) > 0 and len(norm2) > 0:length_ratio = min(len(norm1), len(norm2)) / max(len(norm1), len(norm2))length_similarity = length_ratio * 0.3 # Lower weight for length# Method 7: Phrase matching (for common phrases)phrase_similarity = self._calculate_phrase_similarity(norm1, norm2)# Combine all methods with optimized weightsfinal_similarity = (sequence_similarity * 0.25 +keyword_similarity * 0.30 +contains_similarity * 0.20 +word_order_similarity * 0.10 +semantic_similarity * 0.10 +length_similarity * 0.03 +phrase_similarity * 0.02)return min(final_similarity, 1.0) # Cap at 1.0def _calculate_semantic_similarity(self, keywords1: set, keywords2: set) -> float:"""Calculate semantic similarity using word relationships"""if not keywords1 or not keywords2:return 0.0# Common semantic relationshipssemantic_groups = {'money': {'cost', 'price', 'tuition', 'fee', 'payment', 'money', 'financial', 'aid', 'scholarship'},'time': {'deadline', 'when', 'time', 'date', 'schedule', 'duration', 'period'},'contact': {'contact', 'phone', 'email', 'address', 'office', 'reach', 'call'},'requirements': {'requirement', 'need', 'required', 'must', 'prerequisite', 'condition'},'application': {'apply', 'application', 'submit', 'process', 'procedure'},'programs': {'program', 'course', 'major', 'degree', 'study', 'academic'},'admission': {'admission', 'admit', 'accept', 'enroll', 'entry', 'enter'}}# Check if keywords belong to the same semantic groupsemantic_score = 0.0for group, words in semantic_groups.items():group1_match = any(keyword in words for keyword in keywords1)group2_match = any(keyword in words for keyword in keywords2)if group1_match and group2_match:semantic_score += 0.3return min(semantic_score, 1.0)def _calculate_phrase_similarity(self, text1: str, text2: str) -> float:"""Calculate similarity based on common phrases"""# Common phrases that should matchcommon_phrases = [('admission requirements', 'requirements admission'),('financial aid', 'aid financial'),('tuition cost', 'cost tuition'),('application deadline', 'deadline application'),('contact admissions', 'admissions contact'),('gpa requirement', 'requirement gpa'),('academic requirements', 'requirements academic')]phrase_score = 0.0for phrase1, phrase2 in common_phrases:if (phrase1 in text1 and phrase1 in text2) or (phrase2 in text1 and phrase2 in text2):phrase_score += 0.5elif (phrase1 in text1 and phrase2 in text2) or (phrase2 in text1 and phrase1 in text2):phrase_score += 0.4return min(phrase_score, 1.0)def _find_best_match(self, user_question: str, database_questions: List[str], threshold: float = 0.25) -> Optional[str]:"""Find the best matching question from database with improved logic"""if not database_questions:return Nonebest_match = Nonebest_score = 0.0all_scores = []# Calculate similarity for all questionsfor db_question in database_questions:similarity = self._calculate_similarity(user_question, db_question)all_scores.append((db_question, similarity))if similarity > best_score:best_score = similaritybest_match = db_question# Sort by similarity scoreall_scores.sort(key=lambda x: x[1], reverse=True)# If the best score is above threshold, return itif best_score >= threshold:return best_match# If no single match is above threshold, try adaptive thresholdif all_scores:# Use the top score if it's reasonably close to thresholdtop_score = all_scores[0][1]if top_score >= threshold * 0.8: # 80% of thresholdreturn all_scores[0][0]# Last resort: if user question is very short, be more lenientif len(user_question.split()) <= 3 and all_scores:# For short queries, use a lower thresholdif all_scores[0][1] >= 0.15:return all_scores[0][0]return Nonedef fetch_from_database(self, question: str) -> str:"""Fetch answer from the database with smart matching"""try:# First, try to get all available questions for smart matchingall_questions = self._get_all_questions()# If we have all questions, try smart matching firstif all_questions:best_match = self._find_best_match(question, all_questions)if best_match:# Try to get answer for the best matching questionanswer = self._get_answer_for_question(best_match)if answer and not self._is_no_answer_response(answer):return answer# Fallback to original method if smart matching doesn't workendpoints = [f"{self.database_url}/faqs",f"{self.database_url}/search",f"{self.database_url}/query",f"{self.database_url}/api/faq"]for endpoint in endpoints:try:# Try GET request with query parameterresponse = requests.get(endpoint, params={"question": question}, timeout=10)if response.status_code == 200:data = response.json()if isinstance(data, dict):answer = data.get('answer', data.get('response', str(data)))# Check if we got a meaningful answerif answer and answer.strip() and not self._is_no_answer_response(answer):return answerelif isinstance(data, list) and len(data) > 0:answer = str(data[0])if answer and answer.strip() and not self._is_no_answer_response(answer):return answerelse:answer = str(data)if answer and answer.strip() and not self._is_no_answer_response(answer):return answerexcept:try:# Try POST request with JSON bodyresponse = requests.post(endpoint,json={"question": question},headers={"Content-Type": "application/json"},timeout=10)if response.status_code == 200:data = response.json()if isinstance(data, dict):answer = data.get('answer', data.get('response', str(data)))# Check if we got a meaningful answerif answer and answer.strip() and not self._is_no_answer_response(answer):return answerelif isinstance(data, list) and len(data) > 0:answer = str(data[0])if answer and answer.strip() and not self._is_no_answer_response(answer):return answerelse:answer = str(data)if answer and answer.strip() and not self._is_no_answer_response(answer):return answerexcept:continue# If no answer found, save the question as unansweredself.save_unanswered_question(question)return "I'm sorry, I couldn't find a specific answer to your question in our database. I've saved your question for review, and we'll work on providing a better answer in the future. Could you try rephrasing your question or ask me something else?"except requests.exceptions.Timeout:# Save the question even if there's a timeoutself.save_unanswered_question(question)return "I'm sorry, the database is taking too long to respond. I've saved your question for review. Please try again in a moment."except requests.exceptions.ConnectionError:# Save the question even if there's a connection errorself.save_unanswered_question(question)return "I'm sorry, I'm having trouble connecting to our database right now. I've saved your question for review. Please try again later."except Exception as e:# Save the question even if there's an unexpected errorself.save_unanswered_question(question)return f"I encountered an error while searching our database: {str(e)}. I've saved your question for review. Please try again."def _get_all_questions(self) -> List[str]:"""Get all available questions from the database for smart matching"""try:# Try different endpoints to get all questionsendpoints = [f"{self.database_url}/questions",f"{self.database_url}/faq/all",f"{self.database_url}/api/questions",f"{self.database_url}/all_questions"]for endpoint in endpoints:try:response = requests.get(endpoint, timeout=10)if response.status_code == 200:data = response.json()if isinstance(data, list):return [str(item) for item in data]elif isinstance(data, dict) and 'questions' in data:return [str(q) for q in data['questions']]except:continuereturn []except:return []def _get_answer_for_question(self, question: str) -> Optional[str]:"""Get answer for a specific question"""try:endpoints = [f"{self.database_url}/faqs",f"{self.database_url}/search",f"{self.database_url}/query",f"{self.database_url}/api/faq"]for endpoint in endpoints:try:response = requests.get(endpoint, params={"question": question}, timeout=10)if response.status_code == 200:data = response.json()if isinstance(data, dict):return data.get('answer', data.get('response', str(data)))elif isinstance(data, list) and len(data) > 0:return str(data[0])else:return str(data)except:try:response = requests.post(endpoint,json={"question": question},headers={"Content-Type": "application/json"},timeout=10)if response.status_code == 200:data = response.json()if isinstance(data, dict):return data.get('answer', data.get('response', str(data)))elif isinstance(data, list) and len(data) > 0:return str(data[0])else:return str(data)except:continuereturn Noneexcept:return Nonedef _is_no_answer_response(self, answer: str) -> bool:"""Check if the response indicates no answer was found"""no_answer_indicators = ["no answer","not found","no results","no data","empty","null","none","i don't know","i don't have","cannot find","unable to find"]answer_lower = answer.lower().strip()return any(indicator in answer_lower for indicator in no_answer_indicators)def chat(self, message: str, history: List[List[str]]) -> str:"""Main chat function"""if not message.strip():return "Please enter a message so I can help you!"# Store conversation historyself.conversation_history.append(("user", message))# Check for conversation patternsif self.is_greeting(message):response = self.get_greeting_response()elif self.is_help_request(message):response = self.get_help_response()elif self.is_thanks(message):response = self.get_thanks_response()elif self.is_goodbye(message):response = self.get_goodbye_response()else:# Try to fetch from databaseresponse = self.fetch_from_database(message)# Store bot responseself.conversation_history.append(("bot", response))return response# Initialize the chatbotchatbot = AIChatbot()# Create Gradio interfacedef create_interface():with gr.Blocks(title="AI Chatbot",theme=gr.themes.Soft(),css=""".gradio-container {max-width: 800px !important;margin: auto !important;}.chat-message {padding: 10px;margin: 5px 0;border-radius: 10px;}""") as interface:gr.Markdown("""# 🤖 AI Chatbot AssistantWelcome! I'm your AI assistant that can help you with:- **General conversation** and friendly chat- **Specific questions** answered from our knowledge databaseJust type your message below and I'll do my best to help you!""")# Chat interfacechatbot_interface = gr.ChatInterface(fn=chatbot.chat,title="Chat with AI Assistant",description="Ask me anything or just have a conversation!",examples=["Hello!","What can you help me with?","How do I contact support?","What are your services?","Thank you for your help!"],cache_examples=False,retry_btn="🔄 Retry",undo_btn="↩️ Undo",clear_btn="🗑️ Clear",submit_btn="Send",stop_btn="⏹️ Stop",additional_inputs=None)# Footergr.Markdown("""---**Note**: This chatbot can handle general conversation and search our database for specific information.If you don't get the answer you're looking for, try rephrasing your question!""")return interface# Launch the applicationif __name__ == "__main__":interface = create_interface()interface.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=True)
app.py+601-211