Spaces:
Runtime error

File size: 6,407 Bytes
05c90b9
 
 
92079b6
 
 
 
05c90b9
92079b6
 
 
 
 
 
 
 
 
 
05c90b9
 
92079b6
 
05c90b9
92079b6
 
 
 
 
 
 
 
 
 
 
05c90b9
92079b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05c90b9
92079b6
 
 
05c90b9
92079b6
 
 
 
05c90b9
92079b6
 
 
 
05c90b9
 
92079b6
 
 
 
 
 
 
 
 
 
 
 
 
05c90b9
92079b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05c90b9
92079b6
 
05c90b9
92079b6
 
 
 
05c90b9
 
92079b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05c90b9
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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()