Spaces:
Sleeping
Sleeping
Update app.py
#2
by
joermd
- opened
app.py
CHANGED
@@ -1,46 +1,127 @@
|
|
1 |
-
import requests
|
2 |
import streamlit as st
|
3 |
-
import random
|
4 |
import time
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
full_response = ""
|
34 |
-
|
35 |
-
assistant_response = "I didn't understand your question. Could you please rephease?"
|
36 |
-
else:
|
37 |
-
assistant_response = random.choice(bot_reply)["text"]
|
38 |
-
# Simulate stream of response with milliseconds delay
|
39 |
-
for chunk in assistant_response.split():
|
40 |
full_response += chunk + " "
|
41 |
time.sleep(0.05)
|
42 |
-
# Add a blinking cursor to simulate typing
|
43 |
message_placeholder.markdown(full_response + "▌")
|
44 |
message_placeholder.markdown(full_response)
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
|
|
2 |
import time
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
4 |
+
import torch
|
5 |
|
6 |
+
class LLAMAChatbot:
|
7 |
+
def __init__(self):
|
8 |
+
st.title("LLAMA Chatbot")
|
9 |
+
self.initialize_model()
|
10 |
+
self.initialize_session_state()
|
11 |
+
|
12 |
+
def initialize_model(self):
|
13 |
+
"""Initialize the LLAMA model and tokenizer"""
|
14 |
+
try:
|
15 |
+
@st.cache_resource
|
16 |
+
def load_model():
|
17 |
+
tokenizer = AutoTokenizer.from_pretrained("joermd/llma-speedy")
|
18 |
+
model = AutoModelForCausalLM.from_pretrained(
|
19 |
+
"joermd/llma-speedy",
|
20 |
+
torch_dtype=torch.float16,
|
21 |
+
device_map="auto"
|
22 |
+
)
|
23 |
+
return model, tokenizer
|
24 |
+
|
25 |
+
self.model, self.tokenizer = load_model()
|
26 |
+
st.success("تم تحميل النموذج بنجاح!")
|
27 |
+
except Exception as e:
|
28 |
+
st.error(f"حدث خطأ أثناء تحميل النموذج: {str(e)}")
|
29 |
+
st.stop()
|
30 |
+
|
31 |
+
def initialize_session_state(self):
|
32 |
+
"""Initialize chat history if it doesn't exist"""
|
33 |
+
if "messages" not in st.session_state:
|
34 |
+
st.session_state.messages = []
|
35 |
+
|
36 |
+
def display_chat_history(self):
|
37 |
+
"""Display all messages from chat history"""
|
38 |
+
for message in st.session_state.messages:
|
39 |
+
with st.chat_message(message["role"]):
|
40 |
+
st.markdown(message["content"])
|
41 |
+
|
42 |
+
def add_message(self, role, content):
|
43 |
+
"""Add a message to the chat history"""
|
44 |
+
st.session_state.messages.append({
|
45 |
+
"role": role,
|
46 |
+
"content": content
|
47 |
+
})
|
48 |
+
|
49 |
+
def generate_response(self, user_input, max_length=1000):
|
50 |
+
"""Generate response using LLAMA model"""
|
51 |
+
try:
|
52 |
+
# Prepare the input context with chat history
|
53 |
+
context = ""
|
54 |
+
for message in st.session_state.messages[-4:]: # Use last 4 messages for context
|
55 |
+
if message["role"] == "user":
|
56 |
+
context += f"Human: {message['content']}\n"
|
57 |
+
else:
|
58 |
+
context += f"Assistant: {message['content']}\n"
|
59 |
+
|
60 |
+
context += f"Human: {user_input}\nAssistant:"
|
61 |
+
|
62 |
+
# Tokenize input
|
63 |
+
inputs = self.tokenizer(context, return_tensors="pt", truncation=True)
|
64 |
+
inputs = inputs.to(self.model.device)
|
65 |
+
|
66 |
+
# Generate response
|
67 |
+
with torch.no_grad():
|
68 |
+
outputs = self.model.generate(
|
69 |
+
inputs["input_ids"],
|
70 |
+
max_length=max_length,
|
71 |
+
num_return_sequences=1,
|
72 |
+
temperature=0.7,
|
73 |
+
top_p=0.9,
|
74 |
+
do_sample=True,
|
75 |
+
pad_token_id=self.tokenizer.eos_token_id
|
76 |
+
)
|
77 |
+
|
78 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
79 |
+
# Extract only the assistant's response
|
80 |
+
response = response.split("Assistant:")[-1].strip()
|
81 |
+
|
82 |
+
return response
|
83 |
+
|
84 |
+
except Exception as e:
|
85 |
+
return f"عذراً، حدث خطأ أثناء توليد الإجابة: {str(e)}"
|
86 |
+
|
87 |
+
def simulate_typing(self, message_placeholder, response):
|
88 |
+
"""Simulate typing effect for bot response"""
|
89 |
full_response = ""
|
90 |
+
for chunk in response.split():
|
|
|
|
|
|
|
|
|
|
|
91 |
full_response += chunk + " "
|
92 |
time.sleep(0.05)
|
|
|
93 |
message_placeholder.markdown(full_response + "▌")
|
94 |
message_placeholder.markdown(full_response)
|
95 |
+
return full_response
|
96 |
+
|
97 |
+
def run(self):
|
98 |
+
"""Main application loop"""
|
99 |
+
# Display existing chat history
|
100 |
+
self.display_chat_history()
|
101 |
+
|
102 |
+
# Handle user input
|
103 |
+
if user_input := st.chat_input("اكتب رسالتك هنا..."):
|
104 |
+
# Display and save user message
|
105 |
+
self.add_message("user", user_input)
|
106 |
+
with st.chat_message("user"):
|
107 |
+
st.markdown(user_input)
|
108 |
+
|
109 |
+
# Generate and display response
|
110 |
+
with st.chat_message("assistant"):
|
111 |
+
message_placeholder = st.empty()
|
112 |
+
with st.spinner("جاري التفكير..."):
|
113 |
+
assistant_response = self.generate_response(user_input)
|
114 |
+
full_response = self.simulate_typing(message_placeholder, assistant_response)
|
115 |
+
self.add_message("assistant", full_response)
|
116 |
+
|
117 |
+
if __name__ == "__main__":
|
118 |
+
# Set page config
|
119 |
+
st.set_page_config(
|
120 |
+
page_title="LLAMA Chatbot",
|
121 |
+
page_icon="🤖",
|
122 |
+
layout="wide"
|
123 |
+
)
|
124 |
+
|
125 |
+
# Initialize and run the chatbot
|
126 |
+
chatbot = LLAMAChatbot()
|
127 |
+
chatbot.run()
|