Spaces:
Sleeping
Sleeping
Download app.py from Cybertech007/dansyn-iso-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/Cybertech007/dansyn-iso-chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Cybertech007/dansyn-iso-chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Cybertech007/dansyn-iso-chatbot/resolve/main/app.py
12.8 kB
| import gradio as gr | |
| import torch | |
| from sentence_transformers import SentenceTransformer, util | |
| import re | |
| import json | |
| import os | |
| # Load the model | |
| print("Loading SentenceTransformer model...") | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| # Load your documents and embeddings | |
| # You'll need to replace this section with your actual data loading | |
| def load_data(): | |
| """Load documents and embeddings""" | |
| try: | |
| # If you have JSON files, uncomment these lines: | |
| # with open('docs.json', 'r') as f: | |
| # docs = json.load(f) | |
| # with open('embeddings.json', 'r') as f: | |
| # embeddings_data = json.load(f) | |
| # doc_embeddings = {k: torch.tensor(v) for k, v in embeddings_data.items()} | |
| # For now, using placeholder data - replace with your actual content | |
| docs = { | |
| "about_dansyn_iso": """Dansyn Innovation Social Organization (Dansyn ISO) is one of Dansyn's line of businesses with the objective of providing business development support to the youth who want to grow their businesses but cannot procure professional services from profit-oriented organizations. | |
| Dansyn ISO is an NPO (non-profit organization) which is aimed at supporting youth entrepreneurship and IT capabilities in the Upper East Region and beyond. The company sprang out of Dansyn Ghana Limited with the mission to support young entrepreneurs who cannot afford professional business development services. | |
| Our organization focuses on: | |
| - Supporting youth entrepreneurship | |
| - Developing IT capabilities | |
| - Providing business development support | |
| - Offering affordable professional services to young entrepreneurs | |
| - Fostering innovation in the Upper East Region""", | |
| "mission_vision": """Our Mission: To provide comprehensive business development support and IT capability building to young entrepreneurs in the Upper East Region and beyond, making professional services accessible to those who cannot afford traditional profit-oriented consulting. | |
| Our Vision: To become the leading catalyst for youth entrepreneurship and innovation in Northern Ghana, empowering the next generation of business leaders with the tools, knowledge, and support they need to succeed. | |
| Core Values: | |
| - Accessibility: Making professional services available to all youth | |
| - Innovation: Fostering creative solutions and entrepreneurial thinking | |
| - Community Impact: Creating positive change in local communities | |
| - Sustainability: Building long-term capacity and growth""", | |
| "services": """Dansyn ISO offers a comprehensive range of services designed to support young entrepreneurs: | |
| Business Development Services: | |
| - Business plan development and review | |
| - Market research and analysis | |
| - Financial planning and management training | |
| - Strategic planning and implementation | |
| - Mentorship and coaching programs | |
| IT Capabilities Development: | |
| - Digital literacy training | |
| - Website development and design | |
| - Social media marketing training | |
| - E-commerce platform setup | |
| - Basic programming and software skills | |
| Support Programs: | |
| - Startup incubation programs | |
| - Networking events and workshops | |
| - Access to funding opportunities | |
| - Legal and regulatory guidance | |
| - Ongoing business support and consultation | |
| All services are provided at affordable rates or through our non-profit initiatives to ensure accessibility for young entrepreneurs.""" | |
| } | |
| # Generate embeddings for the documents | |
| doc_embeddings = {} | |
| for key, text in docs.items(): | |
| print(f"Generating embedding for {key}...") | |
| doc_embeddings[key] = model.encode(text, convert_to_tensor=True) | |
| print("Data loading completed!") | |
| return docs, doc_embeddings | |
| except Exception as e: | |
| print(f"Error loading data: {e}") | |
| return {}, {} | |
| # Load the data | |
| docs, doc_embeddings = load_data() | |
| def chatbot_fn(message, history): | |
| """Improved chatbot function with proper greeting handling and content filtering""" | |
| # Clean and normalize the message | |
| message = message.strip() | |
| if not message: | |
| return "Please ask me something about Dansyn ISO!" | |
| # Handle greetings FIRST - before doing any embedding search | |
| greetings = [ | |
| "hello", "hi", "hey", "good morning", "good afternoon", | |
| "good evening", "greetings", "what's up", "howdy" | |
| ] | |
| # Check if message is primarily a greeting (short message with greeting words) | |
| message_lower = message.lower() | |
| if any(greeting in message_lower for greeting in greetings) and len(message.split()) <= 3: | |
| return """Hello! π I'm the Dansyn ISO assistant. | |
| I can help you with information about: | |
| β’ Our mission and vision as a non-profit organization | |
| β’ Services we offer to support youth entrepreneurship | |
| β’ IT capabilities development programs | |
| β’ Business development support | |
| β’ How we help young entrepreneurs in the Upper East Region | |
| What would you like to know about Dansyn ISO?""" | |
| # Handle thanks/goodbye | |
| thanks_phrases = ["thank you", "thanks", "bye", "goodbye", "see you"] | |
| if any(phrase in message_lower for phrase in thanks_phrases): | |
| return "You're welcome! Feel free to ask if you have any other questions about Dansyn ISO. π" | |
| # Handle "what are you" type questions | |
| identity_questions = ["what are you", "who are you", "what is this", "who is this"] | |
| if any(question in message_lower for question in identity_questions): | |
| return """I'm the Dansyn ISO assistant chatbot! π€ | |
| I'm here to help you learn about: | |
| β’ **Dansyn Innovation Social Organization (Dansyn ISO)** - A non-profit organization | |
| β’ **Our mission** - Supporting youth entrepreneurship and IT capabilities | |
| β’ **Our services** - Business development support for young entrepreneurs | |
| β’ **Our focus area** - Upper East Region and beyond | |
| Ask me anything about our programs, services, or how we can help young entrepreneurs!""" | |
| # Check if we have data loaded | |
| if not docs or not doc_embeddings: | |
| return "I'm sorry, but the knowledge base is not available right now. Please try again later." | |
| # Now do embedding search for other questions | |
| try: | |
| query_embedding = model.encode(message, convert_to_tensor=True) | |
| scores = {} | |
| # Calculate similarity scores for all documents | |
| for doc_key, doc_embedding in doc_embeddings.items(): | |
| similarity = float(util.pytorch_cos_sim(query_embedding, doc_embedding)) | |
| scores[doc_key] = similarity | |
| if not scores: | |
| return "I couldn't find relevant information. Please try asking about our services or mission." | |
| # Get best match | |
| best_doc = max(scores, key=scores.get) | |
| best_score = scores[best_doc] | |
| # Check if the match is relevant enough | |
| if best_score < 0.3: | |
| return """I couldn't find specific information about that topic in our knowledge base. | |
| Try asking about: | |
| β’ Dansyn ISO's mission and objectives | |
| β’ Youth entrepreneurship support programs | |
| β’ IT capabilities development | |
| β’ Business development services | |
| β’ How we support young entrepreneurs in the Upper East Region | |
| What specific aspect would you like to know more about?""" | |
| # Get the response text | |
| text = docs[best_doc] | |
| # Smart content extraction based on query type | |
| if any(word in message_lower for word in ['mission', 'vision', 'about', 'who', 'what', 'objective', 'purpose']): | |
| # For mission/vision questions, return full relevant content | |
| response_text = text | |
| elif any(word in message_lower for word in ['service', 'services', 'offer', 'provide', 'help', 'support']): | |
| # For services questions | |
| response_text = text | |
| else: | |
| # General questions - extract most relevant sentences | |
| sentences = [s.strip() for s in text.replace('\n', ' ').split('.') if len(s.strip()) > 30] | |
| if len(sentences) > 3: | |
| # Get most relevant sentences | |
| sentence_scores = [] | |
| for sentence in sentences: | |
| if len(sentence) > 50: | |
| try: | |
| sent_embedding = model.encode(sentence, convert_to_tensor=True) | |
| score = float(util.pytorch_cos_sim(query_embedding, sent_embedding)) | |
| sentence_scores.append((sentence, score)) | |
| except: | |
| continue | |
| if sentence_scores: | |
| sentence_scores.sort(key=lambda x: x[1], reverse=True) | |
| relevant_sentences = [s[0] for s in sentence_scores[:3]] | |
| response_text = '. '.join(relevant_sentences) + '.' | |
| else: | |
| response_text = text | |
| else: | |
| response_text = text | |
| # Limit response length | |
| if len(response_text) > 600: | |
| sentences = response_text.split('.') | |
| truncated = [] | |
| char_count = 0 | |
| for sentence in sentences: | |
| if char_count + len(sentence) > 550: | |
| break | |
| truncated.append(sentence.strip()) | |
| char_count += len(sentence) + 1 | |
| response_text = '. '.join([s for s in truncated if s]) + '.' | |
| # Format the response | |
| source_name = best_doc.replace('_', ' ').title() | |
| if best_score > 0.8: | |
| confidence_level = "High" | |
| elif best_score > 0.6: | |
| confidence_level = "Good" | |
| else: | |
| confidence_level = "Moderate" | |
| return f"""**{source_name}:** | |
| {response_text} | |
| *Confidence: {confidence_level} ({best_score:.2f})* | |
| --- | |
| *Need more specific information? Try asking a more detailed question!*""" | |
| except Exception as e: | |
| print(f"Error in chatbot_fn: {e}") | |
| return "I encountered an error processing your request. Please try rephrasing your question." | |
| # Create the Gradio interface | |
| with gr.Blocks( | |
| title="Dansyn ISO Assistant", | |
| theme=gr.themes.Soft(), | |
| css=""" | |
| .gradio-container { | |
| max-width: 800px !important; | |
| margin: auto !important; | |
| } | |
| """ | |
| ) as demo: | |
| gr.Markdown(""" | |
| # π’ Dansyn ISO Assistant | |
| Welcome! I'm here to help you learn about **Dansyn Innovation Social Organization (Dansyn ISO)**. | |
| I can answer questions about: | |
| - π― Our mission and vision | |
| - π οΈ Services and programs we offer | |
| - πΌ Business development support | |
| - π» IT capabilities development | |
| - π Youth entrepreneurship initiatives | |
| Just type your question below! | |
| """) | |
| chatbot = gr.Chatbot( | |
| height=400, | |
| placeholder="Ask me anything about Dansyn ISO...", | |
| show_label=False, | |
| type="messages" | |
| ) | |
| with gr.Row(): | |
| msg = gr.Textbox( | |
| placeholder="Type your question here...", | |
| container=False, | |
| scale=4 | |
| ) | |
| submit_btn = gr.Button("Send", scale=1, variant="primary") | |
| clear_btn = gr.Button("Clear", scale=1) | |
| # Example questions | |
| gr.Examples( | |
| examples=[ | |
| "Hello! What is Dansyn ISO?", | |
| "What is your mission?", | |
| "What services do you offer?", | |
| "How do you support young entrepreneurs?", | |
| "Tell me about your IT programs" | |
| ], | |
| inputs=msg, | |
| label="π‘ Try these example questions:" | |
| ) | |
| def user(user_message, history): | |
| if not history: | |
| history = [] | |
| return "", history + [{"role": "user", "content": user_message}] | |
| def bot(history): | |
| if history and history[-1]["role"] == "user": | |
| user_message = history[-1]["content"] | |
| bot_message = chatbot_fn(user_message, history) | |
| history.append({"role": "assistant", "content": bot_message}) | |
| return history | |
| # Event handlers | |
| msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot, chatbot, chatbot | |
| ) | |
| submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot, chatbot, chatbot | |
| ) | |
| clear_btn.click(lambda: [], None, chatbot, queue=False) | |
| # Launch the app | |
| if __name__ == "__main__": | |
| demo.launch() |