Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files3 unmodified lines45678916 unmodified lines26272829303137 unmodified lines69707172737475767778798081828384852 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691704 unmodified lines175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207120 unmodified lines3283293303313323333343353363373383 unmodified linesimport csvimport ioimport timeimport openpyxlfrom openpyxl import Workbookimport streamlit.components.v1 as components16 unmodified linesfont_size = st.sidebar.slider("حجم الخط / Font Size", 12, 24, 16)text_color = st.sidebar.color_picker("لون النص / Text Color", "#ffffff")themes = {"داكن / Dark": {"bg": "#1e1e2e", "card": "#2a2a3e", "accent": "#7c6af7"},"فاتح / Light": {"bg": "#f0f2f6", "card": "#ffffff", "accent": "#4a90d9"},37 unmodified lines</style>""", unsafe_allow_html=True)# ============== الشخصية المساعدة المتحركة (تختار المستخدم شخصيته، تتحرك وتتفاعل مع كل زر) ==============components.html("""<div id="characterPicker" style="position:fixed; top:10px; left:10px; display:flex; flex-wrap:wrap; gap:8px; pointer-events:auto;"></div><script type="module">import { initAgent } from 'https://cdn.jsdelivr.net/npm/clippyjs/dist/index.mjs';import * as clippyAgents from 'https://cdn.jsdelivr.net/npm/clippyjs/dist/agents/index.mjs';// نخلي الـ iframe يغطي كامل الصفحة بدون ما يحجب أزرار Streamlitconst frame = window.frameElement;if(frame){frame.style.position = 'fixed';frame.style.top = '0';frame.style.left = '0';2 unmodified linesframe.style.zIndex = '999999';frame.style.border = 'none';frame.style.pointerEvents = 'none';}document.body.style.pointerEvents = 'none';document.getElementById('characterPicker').style.pointerEvents = 'auto';const CHARACTERS = [{ key: 'Clippy', label: 'كليبي 📎' },{ key: 'Merlin', label: 'مارلن 🧙' },{ key: 'Rover', label: 'روفر 🐶' },{ key: 'Links', label: 'لينكس 🐱' },{ key: 'Genius', label: 'الفيلسوف 🧑🔬' },{ key: 'Peedy', label: 'بيدي 🦜' },{ key: 'Bonzi', label: 'بونزي 🐵' },{ key: 'Rocky', label: 'روكي 🐧' },{ key: 'F1', label: 'روبوت 🤖' },];let currentAgent = null;let roamTimer = null;let lastReactionTime = 0;const IDLE_TIPS = ['أحتاج مساعدة؟ 😊', 'جرب تحمل الملف Excel أو CSV!', 'دور عن كتاب جديد!'];const CLICK_REACTIONS = ['أوه، شنو راح تسوي هسة؟', 'خيار زين! 👍', 'تمام، شغال؟'];function randomPoint(){return { x: 40 + Math.random() * (window.innerWidth - 150), y: 80 + Math.random() * (window.innerHeight - 200) };}function startRoaming(agent){clearInterval(roamTimer);roamTimer = setInterval(() => {if(!agent) return;const p = randomPoint();agent.moveTo(p.x, p.y);if(Math.random() < 0.35){ agent.speak(IDLE_TIPS[Math.floor(Math.random()*IDLE_TIPS.length)]); }else { agent.animate(); }}, 10000);}function reactToClick(e){if(!currentAgent) return;const now = Date.now();if(now - lastReactionTime < 1500) return;lastReactionTime = now;currentAgent.stopCurrent();currentAgent.gestureAt(e.clientX, e.clientY);currentAgent.animate();if(Math.random() < 0.5){ currentAgent.speak(CLICK_REACTIONS[Math.floor(Math.random()*CLICK_REACTIONS.length)]); }}// نستمع للضغطات على صفحة Streamlit الحقيقية (خارج الـ iframe)try{window.parent.document.addEventListener('click', (e) => {if(e.target.closest('button, a, [role="button"]')){ reactToClick(e); }});}catch(err){ console.warn('تعذر الوصول لصفحة Streamlit الأساسية', err); }async function switchTo(name){if(!clippyAgents[name]) return;clearInterval(roamTimer);if(currentAgent){ try{ currentAgent.hide(); currentAgent.dispose(); }catch(e){} currentAgent = null; }const agent = await initAgent(clippyAgents[name]);currentAgent = agent;agent.show();agent.speak('مرحباً! اخترتني، هلا 👋');startRoaming(agent);localStorage.setItem('chosenCharacter', name);}function renderPicker(){const el = document.getElementById('characterPicker');el.innerHTML = CHARACTERS.map(c => `<button data-key="${c.key}" style="padding:8px 14px; border-radius:20px; border:1px solid #ccc; background:#fff; cursor:pointer;">${c.label}</button>`).join('');el.querySelectorAll('button').forEach(btn => btn.addEventListener('click', () => switchTo(btn.dataset.key)));}renderPicker();const saved = localStorage.getItem('chosenCharacter') || 'Clippy';switchTo(saved);</script>""", height=0)4 unmodified lines# main inputscol1, col2, col3_main = st.columns([2, 1, 1])with col1:url_label = "رابط الموقع" if AR else "Website URL"url = st.text_input(url_label, "https://books.toscrape.com")with col2:refresh_label = "تحديث تلقائي (ثانية، 0=إيقاف)" if AR else "Auto Refresh (sec, 0=off)"auto_refresh = st.number_input(refresh_label, min_value=0, value=0, step=10)with col3_main:pages_label = "عدد الصفحات" if AR else "Number of Pages"max_pages = st.number_input(pages_label, min_value=1, max_value=50, value=1)# search and filtercol3, col4, col5 = st.columns(3)with col3:search_label = "بحث باسم الكتاب" if AR else "Search by Title"search_query = st.text_input(search_label)with col4:price_label = "الحد الاقصى للسعر" if AR else "Max Price"max_price = st.slider(price_label, 0, 100, 100)with col5:sort_label = "ترتيب حسب" if AR else "Sort By"if AR:sort_options = ["بدون ترتيب", "السعر تصاعدي", "السعر تنازلي", "الاسم", "التقييم"]else:sort_options = ["No Sort", "Price Low to High", "Price High to Low", "Title", "Rating"]sort_by = st.selectbox(sort_label, sort_options)btn_label = "ابدأ السحب" if AR else "Start Scraping"button = st.button(btn_label)rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}120 unmodified linescol_csv, col_excel = st.columns(2)with col_csv:csv_btn = "تنزيل CSV" if AR else "Download CSV"st.download_button(csv_btn, csv_output.getvalue(), "books.csv", "text/csv")with col_excel:excel_btn = "تنزيل Excel" if AR else "Download Excel"st.download_button(excel_btn, export_excel(filtered), "books.xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")if auto_refresh == 0:3 unmodified lines4567891016 unmodified lines27282930313233343536373839404142434445464748495051525354555637 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661672 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682694 unmodified lines274275276277278279280281282283284285286287288289290291292293294295296297298299120 unmodified lines4204214224234244254264274283 unmodified linesimport csvimport ioimport timeimport jsonimport openpyxlfrom openpyxl import Workbookimport streamlit.components.v1 as components16 unmodified linesfont_size = st.sidebar.slider("حجم الخط / Font Size", 12, 24, 16)text_color = st.sidebar.color_picker("لون النص / Text Color", "#ffffff")# ============== اعدادات الشخصية المساعدة ==============st.sidebar.markdown("---")st.sidebar.subheader("الشخصية المساعدة / Assistant Character")CHAR_OPTIONS = {'Clippy': 'كليبي 📎','Merlin': 'مارلن 🧙','Rover': 'روفر 🐶','Links': 'لينكس 🐱','Genius': 'الفيلسوف 🧑🔬','Peedy': 'بيدي 🦜','Bonzi': 'بونزي 🐵','Rocky': 'روكي 🐧','F1': 'روبوت 🤖',}char_pick_label = "اختر شكل الشخصية" if AR else "Choose Character Look"character_key = st.sidebar.selectbox(char_pick_label, list(CHAR_OPTIONS.keys()), format_func=lambda k: CHAR_OPTIONS[k])char_name_label = "شنو تريد تسميها؟" if AR else "Name the Character"character_name = st.sidebar.text_input(char_name_label, "كليبي" if AR else "Clippy")user_name_label = "شسمك؟ (راح تصيحك بيه)" if AR else "Your Name (it'll call you this)"user_name = st.sidebar.text_input(user_name_label, "صديقي" if AR else "Friend")themes = {"داكن / Dark": {"bg": "#1e1e2e", "card": "#2a2a3e", "accent": "#7c6af7"},"فاتح / Light": {"bg": "#f0f2f6", "card": "#ffffff", "accent": "#4a90d9"},37 unmodified lines</style>""", unsafe_allow_html=True)# ============== نصوص الحقول والازرار (نعرفها هنا عشان نستخدمها بالتلميحات وبالواجهة) ==============LBL_URL = "رابط الموقع" if AR else "Website URL"LBL_REFRESH = "تحديث تلقائي (ثانية، 0=إيقاف)" if AR else "Auto Refresh (sec, 0=off)"LBL_PAGES = "عدد الصفحات" if AR else "Number of Pages"LBL_SEARCH = "بحث باسم الكتاب" if AR else "Search by Title"LBL_PRICE = "الحد الاقصى للسعر" if AR else "Max Price"LBL_SORT = "ترتيب حسب" if AR else "Sort By"BTN_START = "ابدأ السحب" if AR else "Start Scraping"BTN_CSV = "تنزيل CSV" if AR else "Download CSV"BTN_EXCEL = "تنزيل Excel" if AR else "Download Excel"# ============== تلميحات الحقول ==============FIELD_HINTS = {LBL_URL: (f"اكتب رابط الموقع هنا يا {user_name} 🌐" if AR else f"Type the website URL here, {user_name} 🌐"),LBL_SEARCH: (f"دور عن اسم الكتاب اللي تريده يا {user_name} 🔍" if AR else f"Search for a book title, {user_name} 🔍"),LBL_PRICE: ("حدد اعلى سعر تقبل بيه 💰" if AR else "Set your max price 💰"),LBL_SORT: ("شلون تريد ترتب الكتب؟ 📊" if AR else "How do you want to sort? 📊"),LBL_REFRESH: ("تريد تحديث تلقائي؟ حدد الثواني ⏱️" if AR else "Want auto refresh? Set seconds ⏱️"),LBL_PAGES: ("كم صفحة تريد نسحب؟ 📄" if AR else "How many pages to scrape? 📄"),}# ============== ردود فعل الازرار ==============BUTTON_REACTIONS = {BTN_START: [f"هذا خوش رابط والله يا {user_name}، عمي محد يلحگك انت! 😂",f"خلي نشوف شنو عندهم من كتب زينة يا {user_name}...","استنى شوية، جاري السحب! 🚀",] if AR else [f"Nice link, {user_name}! Nobody can catch you 😂","Let's see what books they've got...","Hang tight, scraping now! 🚀",],BTN_CSV: [f"زين يا {user_name}، احتفظ بالملف منيح 📥","تم تجهيز ملف الـ CSV!",] if AR else [f"Nice one, {user_name}! Keep that file safe 📥","CSV is ready!",],BTN_EXCEL: [f"اكسل احلى وياك يا {user_name} 😎","تم تجهيز ملف الاكسل!",] if AR else [f"Excel looks better with you, {user_name} 😎","Excel file is ready!",],}GENERIC_REACTIONS = [f"شنو رايك بالتصميم يا {user_name}؟ 😊",f"تحتاج مساعدة ثانية يا {user_name}؟","زين، استمر! 👍",] if AR else [f"What do you think of the design, {user_name}? 😊",f"Need any more help, {user_name}?","Nice, keep going! 👍",]GREETING = (f"هلا {user_name}! انا {character_name} 👋" if AR else f"Hi {user_name}! I'm {character_name} 👋")# ============== الشخصية المساعدة المتحركة ==============components.html(f"""<script type="module">import {{ initAgent }} from 'https://cdn.jsdelivr.net/npm/clippyjs/dist/index.mjs';import * as clippyAgents from 'https://cdn.jsdelivr.net/npm/clippyjs/dist/agents/index.mjs';const frame = window.frameElement;if(frame){{frame.style.position = 'fixed';frame.style.top = '0';frame.style.left = '0';2 unmodified linesframe.style.zIndex = '999999';frame.style.border = 'none';frame.style.pointerEvents = 'none';}}document.body.style.pointerEvents = 'none';const CHARACTER_KEY = {json.dumps(character_key)};const CHARACTER_NAME = {json.dumps(character_name)};const USER_NAME = {json.dumps(user_name)};const GREETING = {json.dumps(GREETING)};const FIELD_HINTS = {json.dumps(FIELD_HINTS, ensure_ascii=False)};const BUTTON_REACTIONS= {json.dumps(BUTTON_REACTIONS, ensure_ascii=False)};const GENERIC_REACTIONS = {json.dumps(GENERIC_REACTIONS, ensure_ascii=False)};let currentAgent = null;let roamTimer = null;let lastReactionTime = 0;let lastHintTime = 0;function randomPoint(){{return {{ x: 40 + Math.random() * (window.innerWidth - 150), y: 80 + Math.random() * (window.innerHeight - 200) }};}}function startRoaming(agent){{clearInterval(roamTimer);roamTimer = setInterval(() => {{if(!agent) return;const p = randomPoint();agent.moveTo(p.x, p.y);agent.animate();}}, 12000);}}// رد فعل عند الضغط على أي زرfunction handleClick(e){{const btn = e.target.closest('button, a, [role="button"]');if(!btn || !currentAgent) return;const now = Date.now();if(now - lastReactionTime < 1200) return;lastReactionTime = now;const txt = btn.textContent.trim();const rect = btn.getBoundingClientRect();currentAgent.stopCurrent();currentAgent.gestureAt(rect.left + rect.width/2, rect.top);currentAgent.animate();const specific = BUTTON_REACTIONS[txt];const pool = specific && specific.length ? specific : GENERIC_REACTIONS;const line = pool[Math.floor(Math.random() * pool.length)];currentAgent.speak(line);}}// تلميح عند التركيز على حقل ادخالfunction handleFocus(e){{const input = e.target;if(!currentAgent) return;if(!(input.tagName === 'INPUT' || input.tagName === 'TEXTAREA' || input.getAttribute('role') === 'combobox')) return;const now = Date.now();if(now - lastHintTime < 800) return;let container = input.closest('[data-testid]') || input.parentElement?.parentElement;const label = container ? container.querySelector('label') : null;const txt = label ? label.textContent.trim() : '';if(!FIELD_HINTS[txt]) return;lastHintTime = now;const rect = input.getBoundingClientRect();currentAgent.stopCurrent();currentAgent.moveTo(Math.max(10, rect.left - 20), Math.max(10, rect.top - 90));currentAgent.gestureAt(rect.left, rect.top);currentAgent.speak(FIELD_HINTS[txt]);}}try{{window.parent.document.addEventListener('click', handleClick);window.parent.document.addEventListener('focusin', handleFocus);}}catch(err){{ console.warn('تعذر الوصول لصفحة Streamlit الأساسية', err); }}async function init(){{if(!clippyAgents[CHARACTER_KEY]) return;if(currentAgent){{ try{{ currentAgent.hide(); currentAgent.dispose(); }}catch(e){{}} currentAgent = null; }}const agent = await initAgent(clippyAgents[CHARACTER_KEY]);currentAgent = agent;agent.show();const comboKey = CHARACTER_KEY + '|' + CHARACTER_NAME + '|' + USER_NAME;const lastCombo = localStorage.getItem('assistantCombo');if(lastCombo !== comboKey){{agent.speak(GREETING);localStorage.setItem('assistantCombo', comboKey);}}startRoaming(agent);}}init();</script>""", height=0)4 unmodified lines# main inputscol1, col2, col3_main = st.columns([2, 1, 1])with col1:url = st.text_input(LBL_URL, "https://books.toscrape.com")with col2:auto_refresh = st.number_input(LBL_REFRESH, min_value=0, value=0, step=10)with col3_main:max_pages = st.number_input(LBL_PAGES, min_value=1, max_value=50, value=1)# search and filtercol3, col4, col5 = st.columns(3)with col3:search_query = st.text_input(LBL_SEARCH)with col4:max_price = st.slider(LBL_PRICE, 0, 100, 100)with col5:if AR:sort_options = ["بدون ترتيب", "السعر تصاعدي", "السعر تنازلي", "الاسم", "التقييم"]else:sort_options = ["No Sort", "Price Low to High", "Price High to Low", "Title", "Rating"]sort_by = st.selectbox(LBL_SORT, sort_options)button = st.button(BTN_START)rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}120 unmodified linescol_csv, col_excel = st.columns(2)with col_csv:st.download_button(BTN_CSV, csv_output.getvalue(), "books.csv", "text/csv")with col_excel:st.download_button(BTN_EXCEL, export_excel(filtered), "books.xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")if auto_refresh == 0:
src/streamlit_app.py+173-83