Download app.py from MyTG01/kosmos: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/MyTG01/kosmos/resolve/main/app.py
- Command line
-
hf download hf://spaces/MyTG01/kosmos/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MyTG01/kosmos/resolve/main/app.py
10 kB
| import feedparser | |
| import re | |
| import html | |
| import requests | |
| import os | |
| import json | |
| import time | |
| import threading | |
| from datetime import datetime | |
| from zai import ZaiClient | |
| import gradio as gr | |
| # Отключаем предупреждения SSL | |
| import urllib3 | |
| urllib3.disable_warnings() | |
| # === НАСТРОЙКИ === | |
| ZAI_API_KEY = os.environ.get("ZAI_API_KEY") | |
| BOT_TOKEN = os.environ.get("BOT_TOKEN") | |
| CHANNEL_ID = os.environ.get("CHANNEL_ID") | |
| HISTORY_FILE = "published_news.json" | |
| IMAGES_DIR = "news_images" | |
| os.makedirs(IMAGES_DIR, exist_ok=True) | |
| client = ZaiClient(api_key=ZAI_API_KEY) | |
| # Для защиты от частых ручных проверок | |
| last_manual_check_time = 0 | |
| # ===== РАБОТА С ИСТОРИЕЙ ПУБЛИКАЦИЙ ===== | |
| def load_history(): | |
| if os.path.exists(HISTORY_FILE): | |
| with open(HISTORY_FILE, 'r', encoding='utf-8') as f: | |
| return json.load(f) | |
| return [] | |
| def save_history(history): | |
| with open(HISTORY_FILE, 'w', encoding='utf-8') as f: | |
| json.dump(history, f, ensure_ascii=False, indent=2) | |
| def is_already_published(news_id, history): | |
| for published in history: | |
| if published.get('id') == news_id: | |
| return True | |
| return False | |
| def add_to_history(news_id, title, link): | |
| history = load_history() | |
| history.append({ | |
| 'id': news_id, | |
| 'title': title, | |
| 'link': link, | |
| 'published_at': datetime.now().isoformat() | |
| }) | |
| if len(history) > 100: | |
| history = history[-100:] | |
| save_history(history) | |
| # ===== ПОЛУЧЕНИЕ НОВОСТИ ИЗ RSS ===== | |
| def get_latest_news(): | |
| rss_url = "https://content-cdn.cian.site/realty/journal/yandex_feeds/rssnews.xml" | |
| feed = feedparser.parse(rss_url) | |
| if not feed.entries: | |
| return None | |
| return feed.entries[0] | |
| def get_news_id(entry): | |
| return entry.link if hasattr(entry, 'link') else entry.title | |
| # ===== ЗАПРОС К GLM С ЗАЩИТОЙ ОТ ЛИМИТОВ ===== | |
| def call_glm_with_retry(prompt, max_retries=3): | |
| for attempt in range(max_retries): | |
| try: | |
| response = client.chat.completions.create( | |
| model="glm-4.7-flash", | |
| messages=[{"role": "user", "content": prompt}], | |
| temperature=0.5 | |
| ) | |
| return response | |
| except Exception as e: | |
| error_str = str(e) | |
| if "429" in error_str or "rate limit" in error_str.lower(): | |
| wait_time = (attempt + 1) * 5 | |
| print(f"⚠️ Лимит запросов GLM. Жду {wait_time} сек... (попытка {attempt+1}/{max_retries})") | |
| time.sleep(wait_time) | |
| else: | |
| raise e | |
| raise Exception("Превышен лимит запросов GLM после нескольких попыток") | |
| def rewrite_news(original_title, full_text): | |
| prompt = f""" | |
| Перепиши новость в новом формате. | |
| Оригинальный заголовок: {original_title} | |
| Оригинальный текст: {full_text} | |
| Требования: | |
| 1. ПРИДУМАЙ НОВЫЙ ЗАГОЛОВОК (короткий, ёмкий, привлекающий внимание) | |
| 2. ПЕРЕПИШИ ТЕКСТ в 5-6 предложений | |
| 3. Сохрани главные факты и цифры | |
| Ответь строго в формате: | |
| ЗАГОЛОВОК: твой заголовок | |
| ТЕКСТ: твой текст из 5-6 предложений | |
| """ | |
| response = call_glm_with_retry(prompt) | |
| result = response.choices[0].message.content | |
| print(f"🔍 Ответ GLM: {result[:500]}") # Логируем ответ для отладки | |
| # Парсим ответ | |
| title_match = re.search(r'ЗАГОЛОВОК:\s*(.+?)(?=\nТЕКСТ:|\n*$)', result, re.DOTALL | re.IGNORECASE) | |
| text_match = re.search(r'ТЕКСТ:\s*(.+?)$', result, re.DOTALL | re.IGNORECASE) | |
| if title_match: | |
| new_title = title_match.group(1).strip() | |
| else: | |
| new_title = original_title | |
| print("⚠️ Не удалось распарсить заголовок, использую оригинал") | |
| if text_match: | |
| new_text = text_match.group(1).strip() | |
| else: | |
| new_text = full_text[:500] | |
| print("⚠️ Не удалось распарсить текст, использую первые 500 символов") | |
| return new_title, new_text | |
| # ===== ПУБЛИКАЦИЯ В TELEGRAM ===== | |
| def publish_to_telegram(title, text): | |
| """Отправляет текст в Telegram""" | |
| # Проверяем, что текст не пустой | |
| if not text or len(text.strip()) < 10: | |
| print(f"❌ Текст пустой или слишком короткий: '{text}'") | |
| return False | |
| message = f"🏠 *{title}*\n\n{text}" | |
| # Используем HTTP | |
| url = f"http://api.telegram.org/bot{BOT_TOKEN}/sendMessage" | |
| data = { | |
| 'chat_id': CHANNEL_ID, | |
| 'text': message, | |
| 'parse_mode': 'Markdown' | |
| } | |
| print(f"📝 Длина сообщения: {len(message)} символов") | |
| for attempt in range(3): | |
| try: | |
| print(f"🔗 Отправка на {url}") | |
| response = requests.post(url, data=data, timeout=60, verify=False) | |
| print(f"Telegram ответ: {response.status_code}") | |
| if response.status_code == 200: | |
| print("✅ Отправлено успешно") | |
| return True | |
| else: | |
| print(f"Ошибка Telegram: {response.text}") | |
| return False | |
| except requests.exceptions.Timeout: | |
| print(f"⚠️ Таймаут (попытка {attempt + 1}/3)") | |
| time.sleep(5) | |
| except Exception as e: | |
| print(f"Попытка {attempt + 1}/3 failed: {e}") | |
| time.sleep(5) | |
| return False | |
| # ===== ОСНОВНАЯ ФУНКЦИЯ ===== | |
| def main(): | |
| print(f"🚀 Проверка новостей ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})") | |
| try: | |
| history = load_history() | |
| news = get_latest_news() | |
| if not news: | |
| print("Новостей не найдено") | |
| return | |
| news_id = get_news_id(news) | |
| if is_already_published(news_id, history): | |
| print("Эта новость уже публиковалась") | |
| return | |
| print("✅ Новая новость! Обрабатываю...") | |
| # Получаем полный текст | |
| full_text = "" | |
| if hasattr(news, 'yandex_full_text'): | |
| full_text = news.yandex_full_text | |
| elif hasattr(news, 'content'): | |
| full_text = news.content[0].value | |
| elif hasattr(news, 'summary'): | |
| full_text = news.summary | |
| else: | |
| full_text = news.description | |
| # Чистим от HTML | |
| full_text_clean = html.unescape(re.sub(r'<[^>]+>', '', full_text)) | |
| print(f"📄 Оригинальный текст: {len(full_text_clean)} символов") | |
| # Переписываем новость через GLM | |
| print("🤖 Отправляю запрос к GLM...") | |
| new_title, new_text = rewrite_news(news.title, full_text_clean) | |
| print(f"✨ Новый заголовок: {new_title}") | |
| print(f"📝 Новый текст (первые 200 символов): {new_text[:200]}...") | |
| # Проверяем, что текст не пустой | |
| if not new_text or len(new_text.strip()) < 10: | |
| print("❌ Полученный текст пустой, использую оригинальный текст") | |
| new_text = full_text_clean[:500] | |
| # Публикуем в Telegram | |
| if publish_to_telegram(new_title, new_text): | |
| add_to_history(news_id, news.title, news.link if hasattr(news, 'link') else "") | |
| print("✅ Новость опубликована в Telegram!") | |
| else: | |
| print("❌ Не удалось опубликовать в Telegram") | |
| except Exception as e: | |
| print(f"❌ Ошибка в main(): {e}") | |
| import traceback | |
| traceback.print_exc() | |
| # ===== ФОНОВЫЙ ПЛАНИРОВЩИК ===== | |
| def run_scheduler(): | |
| print("🤖 Бот запущен. Первая проверка через 10 секунд...") | |
| time.sleep(10) | |
| last_run = datetime.now() | |
| main() | |
| while True: | |
| now = datetime.now() | |
| # Проверяем каждые 30 минут | |
| if (now - last_run).total_seconds() >= 1800: | |
| main() | |
| last_run = now | |
| time.sleep(60) | |
| # Запускаем планировщик в фоновом потоке | |
| scheduler_thread = threading.Thread(target=run_scheduler, daemon=True) | |
| scheduler_thread.start() | |
| # ===== ВЕБ-ИНТЕРФЕЙС ===== | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 🤖 Cian News Bot") | |
| gr.Markdown("Бот проверяет новые новости каждые 30 минут и публикует в Telegram") | |
| with gr.Row(): | |
| btn = gr.Button("🔄 Проверить сейчас") | |
| output = gr.Textbox(label="Результат", lines=5) | |
| def manual_check(): | |
| global last_manual_check_time | |
| now = time.time() | |
| if now - last_manual_check_time < 30: | |
| return "⏳ Слишком часто! Подождите 30 секунд." | |
| last_manual_check_time = now | |
| try: | |
| main() | |
| return "✅ Проверка выполнена!" | |
| except Exception as e: | |
| return f"❌ Ошибка: {e}" | |
| btn.click(manual_check, outputs=output) | |
| # Запускаем веб-интерфейс | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |