Spaces:
Runtime error
Runtime error
Download app.py from DunaevStudio/Testt: direct link, hf CLI and curl.
- Browser
- Download file 6.41 kB
-
https://huggingface.co/spaces/DunaevStudio/Testt/resolve/main/app.py
- Command line
-
hf download hf://spaces/DunaevStudio/Testt/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DunaevStudio/Testt/resolve/main/app.py
6.41 kB
| import gradio as gr | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import re | |
| from datetime import datetime, timedelta | |
| import time | |
| import random | |
| # Список публичных инстансов SearXNG (проверенные, работающие) | |
| SEARXNG_INSTANCES = [ | |
| "https://searx.be", | |
| "https://search.freestater.org", | |
| "https://searx.tiekoetter.com", | |
| "https://searx.space", | |
| ] | |
| class WebReader: | |
| def __init__(self, cache_ttl=600, max_tokens=100): | |
| self.cache = {} | |
| self.cache_ttl = cache_ttl | |
| self.max_tokens = max_tokens | |
| self.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" | |
| def _get_working_instance(self): | |
| """Проверяет доступность инстансов и возвращает первый работающий.""" | |
| for instance in SEARXNG_INSTANCES: | |
| try: | |
| test_url = f"{instance}/search?q=test&format=json" | |
| resp = requests.get(test_url, timeout=5) | |
| if resp.status_code == 200: | |
| return instance | |
| except: | |
| continue | |
| return None | |
| def _search_searxng(self, query): | |
| """Выполняет поиск через доступный инстанс SearXNG.""" | |
| instance = self._get_working_instance() | |
| if not instance: | |
| return None | |
| url = f"{instance}/search" | |
| params = { | |
| "q": query, | |
| "format": "json", | |
| "categories": "general", | |
| "engines": "google,duckduckgo,bing,yandex", | |
| "language": "ru" | |
| } | |
| try: | |
| resp = requests.get(url, params=params, timeout=10) | |
| resp.raise_for_status() | |
| return resp.json() | |
| except: | |
| return None | |
| def _extract_text_from_url(self, url): | |
| """Загружает страницу и извлекает чистый текст.""" | |
| try: | |
| headers = {"User-Agent": self.user_agent} | |
| resp = requests.get(url, headers=headers, timeout=10) | |
| resp.raise_for_status() | |
| soup = BeautifulSoup(resp.text, "html.parser") | |
| # Удаляем мусорные теги | |
| for tag in soup(["script", "style", "nav", "footer", "header", "aside", "form", "noscript"]): | |
| tag.decompose() | |
| # Ищем основное содержимое (article, main, body) | |
| main = soup.find("article") or soup.find("main") or soup.body | |
| if not main: | |
| main = soup | |
| text = main.get_text(separator=" ", strip=True) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text | |
| except: | |
| return None | |
| def _trim_to_tokens(self, text, max_tokens): | |
| """Обрезает текст до приблизительного числа токенов (1 токен ≈ 3.5 символа).""" | |
| if not text: | |
| return "" | |
| avg_chars_per_token = 3.5 | |
| max_chars = int(max_tokens * avg_chars_per_token) | |
| if len(text) <= max_chars: | |
| return text | |
| trimmed = text[:max_chars] | |
| last_space = trimmed.rfind(" ") | |
| if last_space > 0: | |
| trimmed = trimmed[:last_space] | |
| return trimmed + "…" | |
| def get_summary(self, query): | |
| """Основной метод: поиск, извлечение, обрезка.""" | |
| cache_key = query.lower().strip() | |
| # Проверка кэша | |
| if cache_key in self.cache: | |
| data, timestamp = self.cache[cache_key] | |
| if datetime.now() - timestamp < timedelta(seconds=self.cache_ttl): | |
| return data | |
| # Поиск | |
| search_data = self._search_searxng(query) | |
| if not search_data: | |
| result = "❌ Поисковая система временно недоступна. Попробуйте позже." | |
| self.cache[cache_key] = (result, datetime.now()) | |
| return result | |
| results = search_data.get("results", []) | |
| if not results: | |
| result = "❌ Ничего не найдено по вашему запросу." | |
| self.cache[cache_key] = (result, datetime.now()) | |
| return result | |
| # Берём первый результат (самый релевантный) | |
| top = results[0] | |
| title = top.get("title", "Без заголовка") | |
| url = top.get("url", "") | |
| if not url: | |
| result = "❌ У найденного результата нет URL." | |
| self.cache[cache_key] = (result, datetime.now()) | |
| return result | |
| # Извлекаем текст | |
| content = self._extract_text_from_url(url) | |
| if not content: | |
| result = f"❌ Не удалось прочитать страницу: {url}" | |
| self.cache[cache_key] = (result, datetime.now()) | |
| return result | |
| # Обрезаем | |
| snippet = self._trim_to_tokens(content, self.max_tokens) | |
| result = f"**{title}**\n{snippet}\n\nИсточник: {url}" | |
| self.cache[cache_key] = (result, datetime.now()) | |
| return result | |
| # ---------- Gradio Интерфейс ---------- | |
| reader = WebReader(max_tokens=100) | |
| def process_query(query): | |
| if not query.strip(): | |
| return "Введите запрос." | |
| return reader.get_summary(query) | |
| iface = gr.Interface( | |
| fn=process_query, | |
| inputs=gr.Textbox( | |
| label="Введите запрос", | |
| placeholder="Например: погода в тамбове, новости, кто такой Пушкин", | |
| lines=2 | |
| ), | |
| outputs=gr.Markdown(label="Результат"), | |
| title="🌐 Веб-читалка (SearXNG + извлечение текста)", | |
| description="Ищет в интернете через публичные инстансы SearXNG, открывает самую релевантную страницу и показывает краткое содержание (100 токенов).", | |
| examples=[ | |
| ["погода в Москве"], | |
| ["последние новости науки"], | |
| ["биография Леонардо да Винчи"], | |
| ["как приготовить борщ"] | |
| ] | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() |