Spaces:
Sleeping

New_WB / app.py
Den200K's picture
Update app.py
a503204 verified
Raw History Blame Contribute Delete
10.5 kB
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("""
<div class='main-title'>
📰 WB Новости + Уведомления
</div>
<div class='sub-title'>
50 последних новостей Wildberries • Важные даты • Excel экспорт
</div>
""")
api_key_input = gr.Textbox(
label="WB API Key",
placeholder="Вставьте API ключ",
type="password"
)
with gr.Row():
run_button = gr.Button(
"🚀 Получить 50 новостей"
)
scroll_to_top = gr.Button(
"⬆️ В начало"
)
notifications_box = gr.Textbox(
label="🔥 Важные уведомления",
lines=14,
elem_classes=["notification-box"],
show_copy_button=True
)
news_box = gr.Textbox(
label="📰 Лента новостей",
lines=35,
elem_classes=["news-box"],
show_copy_button=True
)
download_file = gr.File(
label="📥 Скачать Excel"
)
run_button.click(
fn=get_wb_news,
inputs=[
api_key_input
],
outputs=[
notifications_box,
news_box,
download_file
]
)
scroll_to_top.click(
None,
None,
None,
js="""
() => {
const textareas = document.querySelectorAll('textarea');
textareas.forEach((textarea) => {
textarea.scrollTop = 0;
});
}
"""
)
# ============================================
# ЗАПУСК
# ============================================
demo.launch(
server_name="0.0.0.0",
server_port=7860,
ssr_mode=False
)