import gradio as gr import requests from datetime import datetime, timedelta import pandas as pd import tempfile import re # ============================================ # WB API URL # ============================================ BASE_URL = "https://common-api.wildberries.ru/api/communications/v2/news" # ============================================ # PREMIUM CSS # ============================================ custom_css = """ body { background: linear-gradient(135deg, #0f172a, #111827); } .gradio-container { max-width: 1400px !important; margin: auto; } .main-title { text-align: center; font-size: 42px; font-weight: bold; color: white; margin-bottom: 10px; } .sub-title { text-align: center; font-size: 18px; color: #cbd5e1; margin-bottom: 30px; } .notification-box { border-radius: 22px !important; border: 2px solid #ef4444 !important; box-shadow: 0 0 30px rgba(239,68,68,0.35); } .news-box { border-radius: 22px !important; border: 2px solid #3b82f6 !important; box-shadow: 0 0 30px rgba(59,130,246,0.25); } button { border-radius: 18px !important; font-size: 18px !important; font-weight: bold !important; padding: 14px !important; } textarea { font-size: 16px !important; } footer { display: none !important; } """ # ============================================ # ПОИСК ДАТ # ============================================ def extract_action_dates(text): months = { "января": "01", "февраля": "02", "марта": "03", "апреля": "04", "мая": "05", "июня": "06", "июля": "07", "августа": "08", "сентября": "09", "октября": "10", "ноября": "11", "декабря": "12" } pattern = r"(с|до)\s+(\d{1,2})\s+(января|февраля|марта|апреля|мая|июня|июля|августа|сентября|октября|ноября|декабря)\s+(\d{4})" matches = re.findall( pattern, text.lower() ) result_dates = [] for match in matches: action_type = match[0] day = match[1] month_name = match[2] year = match[3] month = months.get(month_name) result_dates.append({ "type": action_type, "raw": f"{day} {month_name} {year}" }) return result_dates # ============================================ # ПОЛУЧЕНИЕ НОВОСТЕЙ # ============================================ def get_wb_news(api_key): if not api_key.strip(): return "⛔ API ключ не введён", "", None try: token = api_key.strip() from_date = ( datetime.now() - timedelta(days=30) ).strftime('%Y-%m-%d') headers = { "Authorization": token } # ============================================ # ПОЛУЧАЕМ ДО 50 НОВОСТЕЙ # ============================================ news_list = [] response = requests.get( BASE_URL, headers=headers, params={ "from": from_date }, timeout=30 ) if response.status_code != 200: return ( f"❌ Ошибка {response.status_code}\n{response.text}", "", None ) data = response.json() news_list = data.get("data", []) # максимум 50 news_list = news_list[:50] if not news_list: return "✅ Новости не найдены", "", None rows = [] notifications_text = "" # ============================================ # ОБРАБОТКА НОВОСТЕЙ # ============================================ for news in news_list: news_id = news.get("id", "N/A") date = ( news.get("createdAt") or news.get("publishedAt") or news.get("date") or "" ) text = ( news.get("text") or news.get("content") or news.get("body") or news.get("description") or "Текст отсутствует" ) title = ( news.get("title") or news.get("header") or news.get("name") or "" ) if not title: title = text[:100] + "..." read_status = ( "Прочитано" if news.get("readStatus", False) else "Не прочитано" ) # ============================================ # ПОИСК ВАЖНЫХ ДАТ # ============================================ found_dates = extract_action_dates(text) important_dates = "" if found_dates: important_dates += ( "\n🚨 НАЧАЛО ДЕЙСТВИЯ:\n" ) for item in found_dates: if item["type"] == "с": important_dates += ( f"\n✅ С {item['raw']}" ) elif item["type"] == "до": important_dates += ( f"\n⛔ ДО {item['raw']}" ) notifications_text += f""" 📌 ЗАГОЛОВОК: {title} {important_dates} ================================================== """ rows.append({ "ID": news_id, "Дата": date, "Статус": read_status, "Заголовок": title, "Текст": text, "Уведомления": important_dates }) # ============================================ # DATAFRAME # ============================================ df = pd.DataFrame(rows) df["Дата"] = pd.to_datetime( df["Дата"], errors="coerce", utc=True ) df = df.dropna(subset=["Дата"]) df["Дата"] = ( df["Дата"] .dt.tz_localize(None) ) # ============================================ # СОРТИРОВКА # ============================================ df["timestamp"] = ( df["Дата"].astype("int64") // 10**9 ) df["ID_num"] = pd.to_numeric( df["ID"], errors="coerce" ) df = df.sort_values( by=["timestamp", "ID_num"], ascending=[False, False] ).reset_index(drop=True) # ============================================ # УВЕДОМЛЕНИЯ # ============================================ if notifications_text: notifications_output = f""" 🔥 ВАЖНЫЕ УВЕДОМЛЕНИЯ {notifications_text} """ else: notifications_output = ( "✅ Важных уведомлений нет" ) # ============================================ # НОВОСТИ # ============================================ news_output = "" for _, row in df.iterrows(): news_output += f""" ================================================== 🕒 ДАТА: {row['Дата'].strftime('%Y-%m-%d %H:%M')} 📌 ЗАГОЛОВОК: {row['Заголовок']} 📢 СТАТУС: {row['Статус']} 📝 ТЕКСТ: {row['Текст']} {row['Уведомления']} """ # ============================================ # EXCEL # ============================================ temp_file = tempfile.NamedTemporaryFile( delete=False, suffix=".xlsx" ) excel_path = temp_file.name excel_df = df.drop( columns=["timestamp", "ID_num"] ) excel_df.to_excel( excel_path, index=False ) return ( notifications_output, news_output, excel_path ) except Exception as e: return ( f"💥 Ошибка: {str(e)}", "", None ) # ============================================ # UI # ============================================ with gr.Blocks( css=custom_css, theme=gr.themes.Soft() ) as demo: gr.Markdown("""