Update app.py
Browse files31 unmodified lines32333435363738394016 unmodified lines5758596061626310 unmodified lines7475767778798019 unmodified lines1001011021031041051063 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421432 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781792 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112123 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392404 unmodified lines24524624724824925025125225325425525625725825926026126226326426526613 unmodified lines2802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123136 unmodified lines3203213223233243253263273283293303317 unmodified lines33934034134234334434531 unmodified lines"декабря": "12"}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 "дата","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, Nonetry:19 unmodified lines)# ============================================# УСПЕШНЫЙ ОТВЕТ# ============================================if response.status_code == 200:3 unmodified linesnews_list = data.get("data", [])if not news_list:return "✅ Новости не найдены", None, Nonerows = []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 linesor "Текст отсутствует")# ============================================# ЗАГОЛОВОК# ============================================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 "")# ============================================# СТАТУС# ============================================read_status = ("Прочитано"2 unmodified lines)# ============================================# ПОИСК ДАТ В ТЕКСТЕ# ============================================found_dates = extract_action_dates(text)notification_text = ""if found_dates:notification_text += "⚠️ ВАЖНЫЕ ДАТЫ:\n"for item in found_dates:notification_text += (f"{item['type']} {item['raw']}\n")rows.append({"ID": news_id,"Дата новости": date,"Статус": read_status,"Заголовок": title,"Текст": text,"Важные даты": notification_text,"Ссылка": url_link})# ============================================3 unmodified linesdf = pd.DataFrame(rows)# ============================================# ОБРАБОТКА ДАТ# ============================================if "Дата новости" in df.columns:df["Дата новости"] = pd.to_datetime(df["Дата новости"],errors="coerce",utc=True).dt.tz_localize(None)# ============================================# СОРТИРОВКА# ============================================df = df.sort_values(by="Дата новости",ascending=False)# ============================================# ТЕКСТОВЫЙ ВЫВОД4 unmodified linesfor _, row in df.iterrows():result_text += f"""==================================================ID: {row['ID']}Дата новости: {row['Дата новости']}Статус: {row['Статус']}Заголовок:{row['Заголовок']}Текст:{row['Текст']}{row['Важные даты']}Ссылка:{row['Ссылка']}"""13 unmodified linesindex=False)return result_text, df, excel_path# ============================================# ОШИБКИ# ============================================elif response.status_code == 401:return "❌ Ошибка 401: неверный API ключ", None, Noneelif response.status_code == 429:return "⚠️ Ошибка 429: превышен лимит запросов", None, Noneelif response.status_code == 400:return "❌ Ошибка 400: неправильный запрос", None, Noneelse:return f"❌ Ошибка {response.status_code}\n{response.text}", None, Noneexcept Exception as e:return f"💥 Ошибка: {str(e)}", None, None# ============================================# GRADIO UI# ============================================with gr.Blocks() as demo: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="Таблица новостей")download_file = gr.File(7 unmodified lines],outputs=[output_text,output_df,download_file])31 unmodified lines3233343536373839404142434445464716 unmodified lines6465666768697010 unmodified lines8182838485868719 unmodified lines1071081091101111121133 unmodified lines1171181191201211221231241251261271281291301311321331341351361372 unmodified lines1401411421431441451461471481491501511521531542 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951963 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222234 unmodified lines22822923023123223323423523623723823924024124224324424524624724824913 unmodified lines2632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952966 unmodified lines3033043053063073083093103117 unmodified lines31932032132232332431 unmodified lines"декабря": "12"}# Ищем:# с 1 мая 2026# до 1 декабря 2026pattern = 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,"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 ключ не введён", Nonetry:19 unmodified lines)# ============================================# УСПЕШНО# ============================================if response.status_code == 200:3 unmodified linesnews_list = data.get("data", [])if not news_list:return "✅ Новости не найдены", Nonerows = []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")2 unmodified linesor "Текст отсутствует")title = (news.get("title")or news.get("header")or news.get("name")or "")if not title:title = text[:100] + "..."read_status = ("Прочитано"2 unmodified lines)# ============================================# ИЩЕМ ДАТЫ В ТЕКСТЕ# ============================================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']}")rows.append({"ID": news_id,"Дата": date,"Статус": read_status,"Заголовок": title,"Текст": text,"Уведомления": important_dates})# ============================================3 unmodified linesdf = pd.DataFrame(rows)# ============================================# ДАТЫ# ============================================df["Дата"] = pd.to_datetime(df["Дата"],errors="coerce",utc=True).dt.tz_localize(None)# ============================================# СОРТИРОВКА# СВЕЖИЕ СВЕРХУ# ============================================df = df.sort_values(by="Дата",ascending=False)# ============================================# ТЕКСТОВЫЙ ВЫВОД4 unmodified linesfor _, row in df.iterrows():result_text += f"""==================================================🕒 ДАТА НОВОСТИ:{row['Дата']}📌 ЗАГОЛОВОК:{row['Заголовок']}📢 СТАТУС:{row['Статус']}📝 ТЕКСТ:{row['Текст']}{row['Уведомления']}"""13 unmodified linesindex=False)return result_text, excel_path# ============================================# ОШИБКИ# ============================================elif response.status_code == 401:return "❌ Ошибка 401: неверный API ключ", Noneelif response.status_code == 429:return "⚠️ Ошибка 429: превышен лимит запросов", Noneelif response.status_code == 400:return "❌ Ошибка 400: неправильный запрос", Noneelse:return f"❌ Ошибка {response.status_code}\n{response.text}", Noneexcept Exception as e:return f"💥 Ошибка: {str(e)}", None# ============================================# UI# ============================================with gr.Blocks() as demo:gr.Markdown("# 📰 WB Новости + уведомления")api_key_input = gr.Textbox(label="WB API Key",6 unmodified lines)output_text = gr.Textbox(label="Новости",lines=35,autoscroll=True)download_file = gr.File(7 unmodified lines],outputs=[output_text,download_file])
app.py+66-87