Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445463 unmodified lines50515253545556575859606162634 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041055 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331349 unmodified lines1441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851862 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142151 unmodified line2172182192202212222232242252262272286 unmodified linesimport openpyxlfrom openpyxl import Workbook# ─── إعدادات الصفحة ───────────────────────────────────────st.set_page_config(page_title="أداة استخراج بيانات الكتب", layout="wide")# ─── الشريط الجانبي - التخصيص ──────────────────────────────st.sidebar.title("التخصيص")theme = st.sidebar.selectbox("القالب", ["داكن", "فاتح", "أزرق", "أخضر"])font = st.sidebar.selectbox("الخط", ["Cairo", "Tajawal", "Arial", "Courier New"])font_size = st.sidebar.slider("حجم الخط", 12, 24, 16)text_color = st.sidebar.color_picker("لون النص", "#ffffff")# ─── ألوان القوالب ─────────────────────────────────────────themes = {"داكن": {"bg": "#1e1e2e", "card": "#2a2a3e", "accent": "#7c6af7"},"فاتح": {"bg": "#f0f2f6", "card": "#ffffff", "accent": "#4a90d9"},"أزرق": {"bg": "#0d1b2a", "card": "#1b2a3b", "accent": "#00b4d8"},"أخضر": {"bg": "#0d2b1e", "card": "#1a3a2a", "accent": "#2ecc71"},}t = themes[theme]# ─── CSS ───────────────────────────────────────────────────st.markdown(f"""<style>@import url('https://fonts.googleapis.com/css2?family=Cairo&family=Tajawal&display=swap');html, body, [class*="css"] {{font-family: '{font}', sans-serif;font-size: {font_size}px;background-color: {t['bg']};color: {text_color};}}.main {{ background-color: {t['bg']}; }}.book-card {{background-color: {t['card']};border-left: 4px solid {t['accent']};3 unmodified linesfont-size: {font_size}px;color: {text_color};}}.title-bar {{font-size: {font_size + 6}px;font-weight: bold;color: {t['accent']};margin-bottom: 20px;}}.count-badge {{background-color: {t['accent']};color: white;4 unmodified lines</style>""", unsafe_allow_html=True)# ─── العنوان ───────────────────────────────────────────────st.markdown('<div class="title-bar">أداة استخراج بيانات الكتب</div>', unsafe_allow_html=True)# ─── الإعدادات الرئيسية ────────────────────────────────────col1, col2, col3_main = st.columns([2, 1, 1])with col1:url = st.text_input("رابط الموقع", "https://books.toscrape.com")with col2:auto_refresh = st.number_input("تحديث تلقائي (ثانية، 0=إيقاف)", min_value=0, value=0, step=10)with col3_main:max_pages = st.number_input("عدد الصفحات", min_value=1, max_value=50, value=1)# ─── البحث والفلترة ────────────────────────────────────────col3, col4, col5 = st.columns(3)with col3:search_query = st.text_input("بحث باسم الكتاب")with col4:max_price = st.slider("الحد الأقصى للسعر (£)", 0, 100, 100)with col5:sort_by = st.selectbox("ترتيب حسب", ["بدون ترتيب", "السعر تصاعدي", "السعر تنازلي", "الاسم", "التقييم"])button = st.button("ابدأ السحب")# ─── تحويل التقييم ─────────────────────────────────────────rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}# ─── دالة سحب البيانات ─────────────────────────────────────def scrape_books(base_url, max_pages):data = []progress = st.progress(0, text="جاري السحب...")for page in range(1, max_pages + 1):try:5 unmodified linesresponse = requests.get(page_url, timeout=10)if response.status_code != 200:st.warning(f"الصفحة {page} غير موجودة، تم الإيقاف.")breaksoup = BeautifulSoup(response.text, "html.parser")books = soup.find_all("article", class_="product_pod")if not books:st.warning(f"لا توجد كتب بالصفحة {page}، تم الإيقاف.")breakfor book in books:title = book.h3.a["title"]price_text = book.find("p", class_="price_color").textprice_num = float(price_text.replace("£", "").replace("Â", "").strip())rating_word = book.p["class"][1]rating_num = rating_map.get(rating_word, 0)rating_stars = "★" * rating_num + "☆" * (5 - rating_num)img_tag = book.find("img")img_url = ""if img_tag:9 unmodified lines"img_url": img_url})progress.progress(page / max_pages, text=f"صفحة {page} من {max_pages}")except Exception as e:st.error(f"خطأ بالصفحة {page}: {e}")breakprogress.empty()return data# ─── دالة فلترة وترتيب ─────────────────────────────────────def filter_sort(data, search, max_p, sort):if search:data = [b for b in data if search.lower() in b["title"].lower()]data = [b for b in data if b["price"] <= max_p]if sort == "السعر تصاعدي":data = sorted(data, key=lambda x: x["price"])elif sort == "السعر تنازلي":data = sorted(data, key=lambda x: x["price"], reverse=True)elif sort == "الاسم":data = sorted(data, key=lambda x: x["title"])elif sort == "التقييم":data = sorted(data, key=lambda x: x["rating"], reverse=True)return data# ─── تصدير Excel ───────────────────────────────────────────def export_excel(data):wb = Workbook()ws = wb.activews.title = "الكتب"ws.append(["العنوان", "السعر", "التقييم"])for b in data:ws.append([b["title"], b["price_text"], b["rating_stars"]])output = io.BytesIO()wb.save(output)return output.getvalue()# ─── التنفيذ ───────────────────────────────────────────────if button or auto_refresh > 0:placeholder = st.empty()2 unmodified linesdata = scrape_books(url, max_pages)if not data:st.error("لم يتم إيجاد بيانات. تحقق من الرابط أو بنية الموقع.")else:filtered = filter_sort(data, search_query, max_price, sort_by)st.markdown(f'<span class="count-badge">تم إيجاد {len(filtered)} كتاب</span>', unsafe_allow_html=True)st.write("")# عرض الكتب بشبكة 4 أعمدةcols = st.columns(4)for i, book in enumerate(filtered):with cols[i % 4]:if book["img_url"]:st.image(book["img_url"], use_column_width=True)st.markdown(f"""<div class="book-card"><b>{book['title']}</b><br>السعر: {book['price_text']}<br>التقييم: {book['rating_stars']}</div>""", unsafe_allow_html=True)# ─── تنزيل CSV ─────────────────────────────csv_output = io.StringIO()writer = csv.writer(csv_output)writer.writerow(["Title", "Price", "Rating"])1 unmodified linecol_csv, col_excel = st.columns(2)with col_csv:st.download_button("تنزيل CSV", csv_output.getvalue(), "books.csv", "text/csv")with col_excel:st.download_button("تنزيل Excel", export_excel(filtered), "books.xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")if auto_refresh == 0:breaktime.sleep(auto_refresh)st.rerun()6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647483 unmodified lines5253545556575859606162634 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131145 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431449 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941952 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202212222232242252261 unmodified line2282292302312322332342352362372382392402416 unmodified linesimport openpyxlfrom openpyxl import Workbook# page configst.set_page_config(page_title="Book Scraper", layout="wide")# sidebarst.sidebar.title("Settings / الاعدادات")lang = st.sidebar.selectbox("Language / اللغة", ["العربية", "English"])AR = lang == "العربية"theme = st.sidebar.selectbox("القالب / Theme",["داكن / Dark", "فاتح / Light", "أزرق / Blue", "أخضر / Green"])font = st.sidebar.selectbox("الخط / Font", ["Cairo", "Tajawal", "Arial", "Courier New"])font_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"},"أزرق / Blue": {"bg": "#0d1b2a", "card": "#1b2a3b", "accent": "#00b4d8"},"أخضر / Green": {"bg": "#0d2b1e", "card": "#1a3a2a", "accent": "#2ecc71"},}t = themes[theme]st.markdown(f"""<style>@import url('https://fonts.googleapis.com/css2?family=Cairo&family=Tajawal&display=swap');html, body, [class*="css"] {{font-family: '{font}', sans-serif;font-size: {font_size}px;background-color: {t['bg']};color: {text_color};}}.main {{ background-color: {t['bg']}; }}.book-card {{background-color: {t['card']};border-left: 4px solid {t['accent']};3 unmodified linesfont-size: {font_size}px;color: {text_color};}}.title-bar {{font-size: {font_size + 6}px;font-weight: bold;color: {t['accent']};margin-bottom: 20px;}}.count-badge {{background-color: {t['accent']};color: white;4 unmodified lines</style>""", unsafe_allow_html=True)# titletitle_text = "أداة استخراج بيانات الكتب" if AR else "Book Data Scraper"st.markdown(f'<div class="title-bar">{title_text}</div>', unsafe_allow_html=True)# 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}def scrape_books(base_url, max_pages):data = []progress_text = "جاري السحب..." if AR else "Scraping..."progress = st.progress(0, text=progress_text)for page in range(1, max_pages + 1):try:5 unmodified linesresponse = requests.get(page_url, timeout=10)if response.status_code != 200:msg = f"الصفحة {page} غير موجودة، تم الايقاف." if AR else f"Page {page} not found, stopped."st.warning(msg)breaksoup = BeautifulSoup(response.text, "html.parser")books = soup.find_all("article", class_="product_pod")if not books:msg = f"لا توجد كتب بالصفحة {page}." if AR else f"No books found on page {page}."st.warning(msg)breakfor book in books:title = book.h3.a["title"]price_text = book.find("p", class_="price_color").textprice_num = float(price_text.replace("£", "").replace("Â", "").strip())rating_word = book.p["class"][1]rating_num = rating_map.get(rating_word, 0)rating_stars = "★" * rating_num + "☆" * (5 - rating_num)img_tag = book.find("img")img_url = ""if img_tag:9 unmodified lines"img_url": img_url})prog_text = f"صفحة {page} من {max_pages}" if AR else f"Page {page} of {max_pages}"progress.progress(page / max_pages, text=prog_text)except Exception as e:msg = f"خطأ بالصفحة {page}: {e}" if AR else f"Error on page {page}: {e}"st.error(msg)breakprogress.empty()return datadef filter_sort(data, search, max_p, sort):if search:data = [b for b in data if search.lower() in b["title"].lower()]data = [b for b in data if b["price"] <= max_p]if sort in ["السعر تصاعدي", "Price Low to High"]:data = sorted(data, key=lambda x: x["price"])elif sort in ["السعر تنازلي", "Price High to Low"]:data = sorted(data, key=lambda x: x["price"], reverse=True)elif sort in ["الاسم", "Title"]:data = sorted(data, key=lambda x: x["title"])elif sort in ["التقييم", "Rating"]:data = sorted(data, key=lambda x: x["rating"], reverse=True)return datadef export_excel(data):wb = Workbook()ws = wb.activews.title = "Books"ws.append(["Title", "Price", "Rating"])for b in data:ws.append([b["title"], b["price_text"], b["rating_stars"]])output = io.BytesIO()wb.save(output)return output.getvalue()if button or auto_refresh > 0:placeholder = st.empty()2 unmodified linesdata = scrape_books(url, max_pages)if not data:msg = "لم يتم ايجاد بيانات. تحقق من الرابط." if AR else "No data found. Check the URL."st.error(msg)else:filtered = filter_sort(data, search_query, max_price, sort_by)count_msg = f"تم ايجاد {len(filtered)} كتاب" if AR else f"Found {len(filtered)} books"st.markdown(f'<span class="count-badge">{count_msg}</span>', unsafe_allow_html=True)st.write("")cols = st.columns(4)for i, book in enumerate(filtered):with cols[i % 4]:if book["img_url"]:st.image(book["img_url"], use_column_width=True)price_label = "السعر" if AR else "Price"rating_label = "التقييم" if AR else "Rating"st.markdown(f"""<div class="book-card"><b>{book['title']}</b><br>{price_label}: {book['price_text']}<br>{rating_label}: {book['rating_stars']}</div>""", unsafe_allow_html=True)csv_output = io.StringIO()writer = csv.writer(csv_output)writer.writerow(["Title", "Price", "Rating"])1 unmodified linecol_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:breaktime.sleep(auto_refresh)st.rerun()
src/streamlit_app.py+74-61