Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import streamlit.components.v1 as components
|
3 |
+
from transformers import pipeline
|
4 |
+
import os
|
5 |
+
|
6 |
+
def main():
|
7 |
+
# تكوين الصفحة
|
8 |
+
st.set_page_config(
|
9 |
+
page_title="سبيدي",
|
10 |
+
page_icon="💬",
|
11 |
+
layout="wide"
|
12 |
+
)
|
13 |
+
|
14 |
+
# إخفاء عناصر Streamlit الافتراضية
|
15 |
+
hide_streamlit_style = """
|
16 |
+
<style>
|
17 |
+
#MainMenu {visibility: hidden;}
|
18 |
+
footer {visibility: hidden;}
|
19 |
+
header {visibility: hidden;}
|
20 |
+
</style>
|
21 |
+
"""
|
22 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
23 |
+
|
24 |
+
# قراءة ملف HTML
|
25 |
+
def read_html():
|
26 |
+
with open('index.html', 'r', encoding='utf-8') as file:
|
27 |
+
return file.read()
|
28 |
+
|
29 |
+
# تهيئة نموذج Hugging Face
|
30 |
+
@st.cache_resource
|
31 |
+
def load_model():
|
32 |
+
# يمكنك تغيير اسم النموذج حسب احتياجك
|
33 |
+
return pipeline("text-generation", model="facebook/opt-350m", device=-1)
|
34 |
+
|
35 |
+
# معالجة الرسائل
|
36 |
+
def process_message(message):
|
37 |
+
model = load_model()
|
38 |
+
response = model(message, max_length=100, num_return_sequences=1)
|
39 |
+
return response[0]['generated_text']
|
40 |
+
|
41 |
+
# إعداد API للتواصل بين JavaScript و Python
|
42 |
+
if 'messages' not in st.session_state:
|
43 |
+
st.session_state.messages = []
|
44 |
+
|
45 |
+
# استقبال الرسائل من JavaScript
|
46 |
+
result = components.html(
|
47 |
+
read_html() + """
|
48 |
+
<script>
|
49 |
+
// تعديل دالة sendMessage لتتواصل مع Python
|
50 |
+
async function sendMessage() {
|
51 |
+
var input = document.getElementById('message-input');
|
52 |
+
var message = input.value.trim();
|
53 |
+
if (message !== '') {
|
54 |
+
appendMessage('user-message', message);
|
55 |
+
input.value = '';
|
56 |
+
|
57 |
+
// إرسال الرسالة إلى Python
|
58 |
+
const response = await fetch('/_stcore/message', {
|
59 |
+
method: 'POST',
|
60 |
+
headers: {'Content-Type': 'application/json'},
|
61 |
+
body: JSON.stringify({message: message})
|
62 |
+
});
|
63 |
+
|
64 |
+
const data = await response.json();
|
65 |
+
appendMessage('bot-message', data.response);
|
66 |
+
}
|
67 |
+
}
|
68 |
+
</script>
|
69 |
+
""",
|
70 |
+
height=800
|
71 |
+
)
|
72 |
+
|
73 |
+
# معالجة الرسائل المستلمة من JavaScript
|
74 |
+
if st.session_state.messages:
|
75 |
+
last_message = st.session_state.messages[-1]
|
76 |
+
response = process_message(last_message)
|
77 |
+
st.session_state.messages.append(response)
|
78 |
+
|
79 |
+
if __name__ == "__main__":
|
80 |
+
main()
|