import streamlit as st import requests from bs4 import BeautifulSoup import csv import io import time import json import openpyxl from openpyxl import Workbook import streamlit.components.v1 as components # page config st.set_page_config(page_title="Book Scraper", layout="wide") # sidebar st.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") # ============== اعدادات الشخصية المساعدة ============== 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"}, "أزرق / Blue": {"bg": "#0d1b2a", "card": "#1b2a3b", "accent": "#00b4d8"}, "أخضر / Green": {"bg": "#0d2b1e", "card": "#1a3a2a", "accent": "#2ecc71"}, } t = themes[theme] st.markdown(f""" """, 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""" """, height=0) # title title_text = "أداة استخراج بيانات الكتب" if AR else "Book Data Scraper" st.markdown(f'
', unsafe_allow_html=True) # main inputs col1, 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 filter col3, 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} 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: if page == 1: page_url = base_url else: page_url = base_url.rstrip("/") + f"/catalogue/page-{page}.html" response = 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) break soup = 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) break for book in books: title = book.h3.a["title"] price_text = book.find("p", class_="price_color").text price_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: img_src = img_tag["src"].replace("../../", "") img_url = "https://books.toscrape.com/" + img_src data.append({ "title": title, "price": price_num, "price_text": price_text, "rating": rating_num, "rating_stars": rating_stars, "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) break progress.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 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 data def export_excel(data): wb = Workbook() ws = wb.active ws.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() while True: with placeholder.container(): data = 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'{count_msg}', 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"""