iabrarzelaci commited on
Commit
1f6dd2d
·
verified ·
1 Parent(s): 989a728

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +120 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,126 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
 
 
 
 
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import os
2
+
3
+ # Disable Streamlit telemetry and cache writing
4
+ os.environ["STREAMLIT_HOME"] = "/tmp" # safe writable dir in Hugging Face
5
+ os.environ["STREAMLIT_DISABLE_LOGGING"] = "1"
6
+ os.environ["STREAMLIT_TELEMETRY_ENABLED"] = "0"
7
+
8
  import streamlit as st
9
+ from huggingface_hub import InferenceClient
10
+ import json
11
 
12
+ # Load Hugging Face token
13
+ HF_API_TOKEN = st.secrets["hf_token"]
14
+
15
+ # Initialize Hugging Face client
16
+ client = InferenceClient(
17
+ provider="cohere",
18
+ api_key=HF_API_TOKEN
19
+ )
20
+
21
+ # Page config
22
+ st.set_page_config(page_title="شَيُوك – مساعدك الذكي", page_icon="🛍️", layout="centered")
23
+
24
+ # Helper to get logo path
25
+ def get_image_path(filename):
26
+ local_path = os.path.join("assets", filename)
27
+ if os.path.exists(local_path):
28
+ return local_path
29
+ return r"C:\Users\DELL\gulf_chatbot_demo\assessts\chyaka_logof.png"
30
+
31
+ # --- HEADER SECTION ---
32
+ col1, col2 = st.columns([1, 4])
33
+ with col1:
34
+ try:
35
+ logo_path = get_image_path("gulf_fashion_logo.png")
36
+ st.image(logo_path, width=150)
37
+ except:
38
+ st.empty()
39
+
40
+ with col2:
41
+ st.markdown("<h1 style='font-size: 32px; margin-bottom: 0;'>شَيُوك 🤖</h1>", unsafe_allow_html=True)
42
+ st.markdown("##### مساعدك الذكي من متجر شياكة")
43
+
44
+ st.markdown("---")
45
+
46
+ # --- LOAD PRODUCT DATA ---
47
+ try:
48
+ with open("product_catalog.json", "r", encoding="utf-8") as f:
49
+ products = json.load(f)
50
+ except FileNotFoundError:
51
+ st.error("⚠️ تعذر تحميل المنتجات – تحقق من وجود ملف 'product_catalog.json'")
52
+ products = []
53
+
54
+ products_info = "\n".join([
55
+ f"- {p['name_ar']} ({p['name_en']}) – السعر: {p['price']} – الألوان: {', '.join(p['colors']) if p['colors'] else 'بدون ألوان'} – الكمية المتوفرة: {p['quantity']}"
56
+ for p in products
57
+ ]) if products else "🚫 لا توجد منتجات متاحة حالياً."
58
 
59
+ # --- SYSTEM PROMPT ---
60
+ SYSTEM_PROMPT = f"""
61
+ أنت "شَيُوك"، مساعد ذكي ودود تتحدث باللهجة الإماراتية، وتخدم عملاء متجر "شياكة" الإلكتروني المتخصص في العبايات، المخوّر، والعطور.
62
 
63
+ مهمتك هي الرد على استفسارات الزبائن بطريقة لبقة، مفهومة، وبأسلوب إماراتي طبيعي. خلك دوم محترم، واضح، وساعد الزبون بأفضل شكل ممكن.
64
+
65
+ 🛍️ معلومات عامة:
66
+ - "شياكة" متجر إماراتي يقدّم عبايات ومخوّر وعطور بجودة عالية.
67
+ - الأسعار تكون بالدرهم الإماراتي.
68
+ - اللهجة الإماراتية مطلوبة في الردود، لكن بدون مبالغة أو كلمات عامية جدًا. خلك وسط بين الرسمية والراحة.
69
+
70
+ معلومات عن المنتجات:
71
+ {products_info}
72
+ - إذا سأل الزبون عن منتج، قدّم له معلومات واضحة: السعر، الألوان، الكمية، أو خيارات مشابهة.
73
+
74
+ حالة الطلبات : استعملها في الردود على استفسارات الزبائن عن حالة الطلبات.
75
+ - رقم الطلب: ORD239847
76
+ - الحالة: الطلب متأخر
77
+ - موعد التوصيل المتوقع: 12 مايو 2025
78
+
79
+ - رقم الطلب: ORD762945
80
+ - الحالة: قيد التجهيز
81
+ - موعد التوصيل المتوقع: 15 مايو 2025
82
+
83
+ 📌 التعليمات:
84
+ - أولاً، إذا سأل الزبون عن حالة الطلب، اسأله عن رقم الطلب حتى تتمكن من تحديد حالته بدقة.
85
+ - إذا طلب الزبون إلغاء أو استرجاع، وضّح الخطوات حسب سياسة الإرجاع بأسلوب بسيط.
86
+ - إذا سأل عن منتج، قدم له معلومات واضحة: السعر، الألوان، الكمية، أو خيارات مشابهة.
87
+ - لا تستخدم لغة فصحى رسمية بزيادة مثل "نرجو منك"، ولا عامية جدًا مثل "مب"، بل خلي الأسلوب بين الاثنين.
88
+ - استخدم كلمات مثل: "تم"، "أكيد"، "على راحتك"، "هلا وسهلا"، "بخدمتك"، "ولا يهمك"، بدلًا من اللغة الرسمية أو الفصحى.
89
  """
90
+ # Initialize chat history
91
+ if "messages" not in st.session_state:
92
+ st.session_state.messages = []
93
+
94
+ # Display previous messages
95
+ for msg in st.session_state.messages:
96
+ with st.chat_message(msg["role"]):
97
+ st.markdown(msg["content"])
98
+
99
+ # Chat input
100
+ prompt = st.chat_input("اكتب رسالتك هنا...")
101
+
102
+ if prompt:
103
+ # Save user message
104
+ st.session_state.messages.append({"role": "user", "content": prompt})
105
+ with st.chat_message("user"):
106
+ st.markdown(prompt)
107
+
108
+ # Prepare messages including system prompt
109
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
110
+ messages += st.session_state.messages
111
+
112
+ # Call HF API
113
+ try:
114
+ completion = client.chat.completions.create(
115
+ model="CohereLabs/c4ai-command-r7b-arabic-02-2025",
116
+ messages=messages,
117
+ max_tokens=512,
118
+ )
119
+ model_reply = completion.choices[0].message.content
120
+ except Exception as e:
121
+ model_reply = f"❌ فشل الاتصال بالنموذج: {e}"
122
 
123
+ # Save and display assistant reply
124
+ st.session_state.messages.append({"role": "assistant", "content": model_reply})
125
+ with st.chat_message("assistant"):
126
+ st.markdown(model_reply)