MonsterBoyTabs commited on
Commit
0bfb1ee
·
verified ·
1 Parent(s): 32bd47a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -65
app.py CHANGED
@@ -1,72 +1,61 @@
1
  import streamlit as st
2
- from transformers import DistilBertTokenizer, DistilBertForQuestionAnswering
3
- import torch
4
 
5
- # Set page configuration
6
- st.set_page_config(page_title="Urdu AI Chatbot", page_icon="🤖")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Title and description
9
- st.title("اردو AI چیٹ بوٹ")
10
- st.write("یہ ایک سادہ چیٹ بوٹ ہے جو اردو زبان میں جواب دیتا ہے۔ اپنا سوال درج کریں!")
11
-
12
- # Load a lightweight multilingual model
13
- @st.cache_resource
14
- def load_model():
15
- try:
16
- tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-multilingual-cased")
17
- model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-multilingual-cased")
18
- return model, tokenizer
19
- except Exception as e:
20
- st.error(f"ماڈل لوڈ کرنے میں خرابی: {str(e)}")
21
- return None, None
22
-
23
- model, tokenizer = load_model()
24
- if model is None or tokenizer is None:
25
- st.error("ماڈل یا ٹوکنائزر لوڈ نہیں ہوا۔ براہ کرم لاگز چیک کریں۔")
26
- st.stop()
27
 
28
- # Function to generate a simple response
29
- def generate_response(user_input):
30
- try:
31
- # Encode the input
32
- inputs = tokenizer(user_input, return_tensors="pt", truncation=True, padding=True)
33
- outputs = model(**inputs)
34
- # Since this is a QA model, we'll simulate a response
35
- start_scores = outputs.start_logits
36
- end_scores = outputs.end_logits
37
- start_idx = torch.argmax(start_scores)
38
- end_idx = torch.argmax(end_scores) + 1
39
- answer_tokens = inputs["input_ids"][0][start_idx:end_idx]
40
- response = tokenizer.decode(answer_tokens, skip_special_tokens=True)
41
 
42
- # If the response is empty or too short, provide a fallback
43
- if not response or len(response) < 3:
44
- return "میں سمجھ گیا، لیکن براہ کرم مزید وضاحت کریں۔"
45
- return response
46
- except Exception as e:
47
- return f"معذرت، کچھ غلطی ہوئی: {str(e)}"
48
-
49
- # Chat interface
50
- if "messages" not in st.session_state:
51
- st.session_state.messages = [{"role": "assistant", "content": "سلام! میں آپ کی مدد کے لیے حاضر ہوں۔"}]
 
 
 
52
 
53
  # Display chat history
54
- for message in st.session_state.messages:
55
- with st.chat_message(message["role"]):
56
- st.write(message["content"])
57
-
58
- # User input
59
- if prompt := st.chat_input("اپنا سوال یہاں لکھیں..."):
60
- st.session_state.messages.append({"role": "user", "content": prompt})
61
- with st.chat_message("user"):
62
- st.write(prompt)
63
-
64
- with st.chat_message("assistant"):
65
- with st.spinner("جواب تیار کر رہا ہوں..."):
66
- response = generate_response(prompt)
67
- st.write(response)
68
- st.session_state.messages.append({"role": "assistant", "content": response})
69
-
70
- # Sidebar
71
- st.sidebar.title("معلومات")
72
- st.sidebar.write("یہ `distilbert-base-multilingual-cased` م��ڈل استعمال کرتا ہے۔")
 
1
  import streamlit as st
 
 
2
 
3
+ # Set the title of the app
4
+ st.title("Urdu AI Chatbot 🤖")
5
+
6
+ # Define intents and responses (keyword-based)
7
+ intents = {
8
+ "greeting": {
9
+ "keywords": ["ہیلو", "سلام", "آداب", "حال", "کیسے ہو", "کیسے ہیں"],
10
+ "response": "السلام علیکم! میں ٹھیک ہوں، شکریہ۔ آپ کیسے ہیں؟"
11
+ },
12
+ "farewell": {
13
+ "keywords": ["الوداع", "خدا حافظ", "بعد میں ملتے ہیں"],
14
+ "response": "خدا حافظ! آپ کا دن اچھا گزرے۔"
15
+ },
16
+ "thanks": {
17
+ "keywords": ["شکریہ", "بہت شکریہ", "مہربانی"],
18
+ "response": "خوش آمدید! کیا میں آپ کی مزید مدد کر سکتا ہوں؟"
19
+ }
20
+ }
21
+
22
+ # Function to detect intent using keywords
23
+ def detect_intent(user_input):
24
+ user_input = user_input.lower()
25
+ for intent, data in intents.items():
26
+ for keyword in data["keywords"]:
27
+ if keyword in user_input:
28
+ return intent
29
+ return "unknown"
30
+
31
+ # Initialize chat history
32
+ if "chat_history" not in st.session_state:
33
+ st.session_state.chat_history = []
34
 
35
+ # User input
36
+ user_input = st.text_input("آپ کا پیغام یہاں لکھیں:", "ہیلو، آپ کیسے ہیں؟")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # Send button
39
+ if st.button("بھیجیں"):
40
+ if user_input:
41
+ # Add user message to chat history
42
+ st.session_state.chat_history.append(f"آپ: {user_input}")
 
 
 
 
 
 
 
 
43
 
44
+ # Detect intent using keywords (no model needed)
45
+ intent = detect_intent(user_input)
46
+
47
+ # Get response based on intent
48
+ if intent != "unknown":
49
+ response = intents[intent]["response"]
50
+ else:
51
+ response = "معذرت، میں اس سوال کا جواب نہیں دے سکتا۔ براہ کرم ایک آسان سوال پوچھیں۔"
52
+
53
+ # Add AI response to chat history
54
+ st.session_state.chat_history.append(f"AI: {response}")
55
+ else:
56
+ st.warning("براہ کرم ایک پیغام لکھیں۔")
57
 
58
  # Display chat history
59
+ st.write("چیٹ کی تاریخ:")
60
+ for message in st.session_state.chat_history:
61
+ st.write(message)