Update app.py
Browse files31 unmodified lines32333435353637383739404142434445464716 unmodified lines646566606768697010 unmodified lines818283778485868719 unmodified lines1071081091031101111121133 unmodified lines1171181191131201211221231241251191201211221261271251261271281281291301311331321331341371381391401351361372 unmodified lines1401411421491501511521431441451461571471481491501621631641651661671681691701711721731741751761511521531542 unmodified lines1571581591851601611621631641901651661671681941691701711721731741981992001751761771781791801811821831841851861871882041891901911922082091931941951963 unmodified lines2002012022192032042052222232242252262272282062072082092102112302312322122132142152162342352362372172182192202212222234 unmodified lines22822923023123223325025125223423523625423723823925725824024124226024324424526226324624724824913 unmodified lines2632642652832662672682692702712722902732742752932762772782962792802812992822832843022852862873052882892902912923102932942952966 unmodified lines3033043053233243253263273283063073083093103117 unmodified lines31932032134232232332431 unmodified lines "декабря": "12" }
pattern = r"(с|до)?\s*(\d{1,2})\s+(января|февраля|марта|апреля|мая|июня|июля|августа|сентября|октября|ноября|декабря)\s+(\d{4})" # Ищем: # с 1 мая 2026 # до 1 декабря 2026
matches = re.findall(pattern, text.lower()) pattern = r"(с|до)\s+(\d{1,2})\s+(января|февраля|марта|апреля|мая|июня|июля|августа|сентября|октября|ноября|декабря)\s+(\d{4})"
matches = re.findall( pattern, text.lower() )
result_dates = []
16 unmodified lines )
result_dates.append({ "type": action_type if action_type else "дата", "type": action_type, "date": parsed_date.strftime("%Y-%m-%d"), "raw": f"{day} {month_name} {year}" })10 unmodified linesdef get_wb_news(api_key):
if not api_key.strip(): return "⛔ API ключ не введён", None, None return "⛔ API ключ не введён", None
try:
19 unmodified lines )
# ============================================ # УСПЕШНЫЙ ОТВЕТ # УСПЕШНО # ============================================
if response.status_code == 200:3 unmodified lines news_list = data.get("data", [])
if not news_list: return "✅ Новости не найдены", None, None return "✅ Новости не найдены", None
rows = []
for news in news_list:
# ============================================ # ID # ============================================
news_id = news.get("id", "N/A")
# ============================================ # ДАТА НОВОСТИ # ============================================
date = ( news.get("createdAt") or news.get("publishedAt") or news.get("date") or news.get("created") or "" )
# ============================================ # ТЕКСТ # ============================================
text = ( news.get("text") or news.get("content")2 unmodified lines or "Текст отсутствует" )
# ============================================ # ЗАГОЛОВОК # ============================================
title = ( news.get("title") or news.get("header") or news.get("name") or news.get("subject") or "" )
if not title: title = text[:80] + "..."
# ============================================ # ССЫЛКА # ============================================
url_link = ( news.get("url") or news.get("link") or "" )
# ============================================ # СТАТУС # ============================================ title = text[:100] + "..."
read_status = ( "Прочитано"2 unmodified lines )
# ============================================ # ПОИСК ДАТ В ТЕКСТЕ # ИЩЕМ ДАТЫ В ТЕКСТЕ # ============================================
found_dates = extract_action_dates(text)
notification_text = "" important_dates = ""
if found_dates:
notification_text += "⚠️ ВАЖНЫЕ ДАТЫ:\n" important_dates += ( "\n🚨 НАЧАЛО ДЕЙСТВИЯ:\n" )
for item in found_dates:
notification_text += ( f"{item['type']} {item['raw']}\n" ) if item["type"] == "с":
important_dates += ( f"\n✅ С {item['raw']}" )
elif item["type"] == "до":
important_dates += ( f"\n⛔ ДО {item['raw']}" )
rows.append({ "ID": news_id, "Дата новости": date, "Дата": date, "Статус": read_status, "Заголовок": title, "Текст": text, "Важные даты": notification_text, "Ссылка": url_link "Уведомления": important_dates })
# ============================================3 unmodified lines df = pd.DataFrame(rows)
# ============================================ # ОБРАБОТКА ДАТ # ДАТЫ # ============================================
if "Дата новости" in df.columns:
df["Дата новости"] = pd.to_datetime( df["Дата новости"], errors="coerce", utc=True ).dt.tz_localize(None) df["Дата"] = pd.to_datetime( df["Дата"], errors="coerce", utc=True ).dt.tz_localize(None)
# ============================================ # СОРТИРОВКА # ============================================ # ============================================ # СОРТИРОВКА # СВЕЖИЕ СВЕРХУ # ============================================
df = df.sort_values( by="Дата новости", ascending=False ) df = df.sort_values( by="Дата", ascending=False )
# ============================================ # ТЕКСТОВЫЙ ВЫВОД4 unmodified lines for _, row in df.iterrows():
result_text += f"""
==================================================
ID: {row['ID']}Дата новости: {row['Дата новости']}Статус: {row['Статус']}🕒 ДАТА НОВОСТИ:{row['Дата']}
Заголовок:📌 ЗАГОЛОВОК:{row['Заголовок']}
Текст:{row['Текст']}📢 СТАТУС:{row['Статус']}
{row['Важные даты']}📝 ТЕКСТ:{row['Текст']}
Ссылка:{row['Ссылка']}{row['Уведомления']}
"""
13 unmodified lines index=False )
return result_text, df, excel_path return result_text, excel_path
# ============================================ # ОШИБКИ # ============================================
elif response.status_code == 401: return "❌ Ошибка 401: неверный API ключ", None, None return "❌ Ошибка 401: неверный API ключ", None
elif response.status_code == 429: return "⚠️ Ошибка 429: превышен лимит запросов", None, None return "⚠️ Ошибка 429: превышен лимит запросов", None
elif response.status_code == 400: return "❌ Ошибка 400: неправильный запрос", None, None return "❌ Ошибка 400: неправильный запрос", None
else: return f"❌ Ошибка {response.status_code}\n{response.text}", None, None return f"❌ Ошибка {response.status_code}\n{response.text}", None
except Exception as e: return f"💥 Ошибка: {str(e)}", None, None return f"💥 Ошибка: {str(e)}", None
# ============================================# GRADIO UI# UI# ============================================
with gr.Blocks() as demo:
gr.Markdown("# 📰 WB Новости продавцов + уведомления") gr.Markdown("# 📰 WB Новости + уведомления")
api_key_input = gr.Textbox( label="WB API Key",6 unmodified lines )
output_text = gr.Textbox( label="Результат", lines=30 )
output_df = gr.Dataframe( label="Таблица новостей" label="Новости", lines=35, autoscroll=True )
download_file = gr.File(7 unmodified lines ], outputs=[ output_text, output_df, download_file ] )app.py+66-87