openmodelai commited on
Commit
595722e
·
verified ·
1 Parent(s): cb3cd1b

Delete hasimion_internet.py

Browse files
Files changed (1) hide show
  1. hasimion_internet.py +0 -438
hasimion_internet.py DELETED
@@ -1,438 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Internet memory and router for Hasimion 1.0.
3
-
4
- The neural modules glued into the checkpoint are small and were not trained on
5
- the open web. This module is the part that actually answers from stored
6
- internet knowledge: a catalog of real sites (from BrowserClick) and short
7
- explanations of how the internet works (from ``data/internet_ru.jsonl``).
8
-
9
- No third-party packages are required.
10
- """
11
-
12
- from __future__ import annotations
13
-
14
- import json
15
- import re
16
- import unicodedata
17
- from pathlib import Path
18
- from urllib.parse import quote_plus
19
-
20
-
21
- STOPWORDS = {
22
- "что", "такое", "такой", "такая", "такие", "как", "чем", "зачем", "кто",
23
- "это", "простыми", "словами", "отличается", "отличие", "разница", "между",
24
- "и", "в", "на", "по", "из", "для", "ли", "же", "бы", "не", "а", "или",
25
- "the", "a", "an", "of", "is", "are", "what", "how", "does", "do", "to",
26
- "vs", "про", "мне", "пожалуйста", "скажи", "расскажи", "объясни",
27
- }
28
-
29
- NAV_MARKERS = (
30
- "открой", "открыть", "откройте", "зайди", "зайти", "зайдите", "перейди",
31
- "перейти", "покажи сайт", "open", "visit", "go to", "launch", "запусти",
32
- )
33
- SEARCH_MARKERS = (
34
- "найди", "найти", "поищи", "поискать", "поиск", "ищи", "искать",
35
- "search", "find", "look up", "загугли", "погугли", "гугли",
36
- )
37
- EXPLAIN_MARKERS = (
38
- "что такое", "что это", "как работает", "как устроен", "чем отличается",
39
- "объясни", "расскажи про", "what is", "how does", "how do", "define",
40
- )
41
- RELOAD_MARKERS = ("обнови страницу", "обнови", "обновить", "reload", "refresh")
42
- BACK_MARKERS = ("назад", "вернись", "go back", "back")
43
- FORWARD_MARKERS = ("вперед", "вперёд", "forward")
44
- SCREENSHOT_MARKERS = ("скриншот", "снимок экрана", "screenshot")
45
- CLICK_MARKERS = ("нажми", "нажать", "кликни", "кликнуть", "click", "press the", "hit the")
46
- TYPE_MARKERS = ("введи", "ввести", "напечатай", "напиши в", "type", "fill")
47
- SCROLL_MARKERS = ("прокрути", "прокрутить", "scroll")
48
-
49
- # Whole-token aliases that are easy to confuse with ordinary words.
50
- SHORT_ALIAS_OK = {"vk", "вк", "x", "икс", "ok", "ок"}
51
-
52
- # Extra surface forms that the site catalog does not list.
53
- EXTRA_ALIASES = {
54
- "youtube": ["ютюб", "ютьюб", "ютуба", "ютубе"],
55
- "google": ["гугл", "гугле", "гугла"],
56
- "yandex": ["яндекс", "яндексе", "яндекса"],
57
- "wikipedia": ["вики", "википедии", "википедию"],
58
- "wiki_en": ["english wikipedia", "wikipedia english"],
59
- "github": ["гитхабе", "гитхаба", "github.com"],
60
- "telegram": ["телега", "телеге", "тг"],
61
- "vk": ["вк", "вконтакте", "вконтакте.ру"],
62
- "gmail": ["гмейл", "гмеил", "почта гугл", "гугл почта"],
63
- "chatgpt": ["чатгпт", "чат гпт", "chatgpt"],
64
- "huggingface": ["huggingface", "hugging face", "хаггингфейс", "хаггинг фейс"],
65
- "wildberries": ["вб", "вайлдберриз", "валберис", "wildberries"],
66
- "aliexpress": ["али", "алиэкспресс", "алиэкспрессе"],
67
- "stackoverflow": ["стек оверфлоу", "stackoverflow"],
68
- "kinopoisk": ["кинопоиск", "кинопоиске"],
69
- "tiktok": ["тикток", "тик токе", "tiktok"],
70
- "instagram": ["инста", "инстаграм", "инсте"],
71
- "whatsapp": ["ватсап", "вотсап", "whatsapp"],
72
- "discord": ["дискорд", "discord"],
73
- "reddit": ["реддит", "reddit"],
74
- "habr": ["хабр", "хабре"],
75
- "ozon": ["озон", "озоне"],
76
- "avito": ["авито"],
77
- "netflix": ["нетфликс", "нетфликсе"],
78
- "spotify": ["спотифай"],
79
- "twitch": ["твич", "твиче"],
80
- "steam": ["стим", "стиме"],
81
- "wikipedia_search_hint": [],
82
- }
83
-
84
-
85
- def normalize(text: str) -> str:
86
- text = unicodedata.normalize("NFKC", text).lower().replace("ё", "е")
87
- text = text.replace("https://", " ").replace("http://", " ").replace("www.", " ")
88
- text = re.sub(r"[^\w\s.+-]+", " ", text, flags=re.UNICODE)
89
- text = re.sub(r"\s+", " ", text).strip()
90
- return text
91
-
92
-
93
- def tokens(text: str) -> set[str]:
94
- return {tok for tok in normalize(text).split() if tok not in STOPWORDS and len(tok) > 1}
95
-
96
-
97
- def _dumps(payload: dict) -> str:
98
- return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
99
-
100
-
101
- def _has_marker(text: str, markers: tuple[str, ...]) -> bool:
102
- for marker in markers:
103
- if re.search(rf"(?<!\w){re.escape(marker)}(?!\w)", text):
104
- return True
105
- return False
106
-
107
-
108
- def word_pattern(alias: str) -> str:
109
- return rf"(?<!\w){re.escape(alias)}(?!\w)"
110
-
111
-
112
- def inflect_alias(alias: str) -> set[str]:
113
- """Add common Russian case forms. Endings are replaced, not only appended."""
114
- forms = {alias}
115
- if not re.fullmatch(r"[а-я]+", alias) or len(alias) < 4:
116
- return forms
117
- for ending in ("а", "у", "е", "ом", "ах", "ы", "и"):
118
- forms.add(alias + ending)
119
- if alias[-1] in "аяьйиы":
120
- stem = alias[:-1]
121
- for ending in ("а", "я", "у", "ю", "е", "и", "ы", "ой", "ей", "ою", "ею", "ам", "ям"):
122
- forms.add(stem + ending)
123
- return {form for form in forms if len(form) >= 4}
124
-
125
-
126
- def _strip_markers(text: str, markers: tuple[str, ...]) -> str:
127
- cleaned = text
128
- for marker in sorted(markers, key=len, reverse=True):
129
- cleaned = re.sub(word_pattern(marker), " ", cleaned, flags=re.IGNORECASE)
130
- return re.sub(r"\s+", " ", cleaned).strip(" .,!?-—")
131
-
132
-
133
- class InternetMemory:
134
- def __init__(self, sites: list[dict], concepts: list[dict]):
135
- self.sites = sites
136
- self.concepts = concepts
137
- grouped: dict[str, list[dict]] = {}
138
- for site in sites:
139
- seen = set()
140
- expanded = []
141
- for alias in site.get("aliases", []):
142
- norm = normalize(alias)
143
- if not norm or norm in seen:
144
- continue
145
- seen.add(norm)
146
- expanded.append(norm)
147
- # Inflect single-word Cyrillic names only. Multiword aliases stay exact.
148
- if " " not in norm:
149
- expanded.extend(inflect_alias(norm))
150
- for norm in expanded:
151
- if len(norm) < 3 and norm not in SHORT_ALIAS_OK:
152
- continue
153
- grouped.setdefault(norm, [])
154
- if site not in grouped[norm]:
155
- grouped[norm].append(site)
156
- self._alias_groups = sorted(grouped.items(), key=lambda item: len(item[0]), reverse=True)
157
- self._concepts = []
158
- for concept in concepts:
159
- question = concept.get("question") or ""
160
- answer = concept.get("answer") or ""
161
- q_tokens = tokens(question)
162
- if q_tokens and answer:
163
- self._concepts.append((q_tokens, question, answer))
164
-
165
- @classmethod
166
- def from_pretrained(cls, path: str | Path) -> "InternetMemory":
167
- root = Path(path)
168
- if (root / "internet" / "sites.json").is_file():
169
- base = root / "internet"
170
- elif (root / "sites.json").is_file():
171
- base = root
172
- else:
173
- raise FileNotFoundError(f"не найдена интернет-память в {root}")
174
- sites = json.loads((base / "sites.json").read_text(encoding="utf-8"))["sites"]
175
- concepts = []
176
- concepts_path = base / "concepts.jsonl"
177
- if concepts_path.is_file():
178
- for line in concepts_path.read_text(encoding="utf-8").splitlines():
179
- if line.strip():
180
- concepts.append(json.loads(line))
181
- return cls(sites, concepts)
182
-
183
- def chat(self, text: str) -> str:
184
- return self.respond(text)["text"]
185
-
186
- def respond(self, text: str) -> dict:
187
- raw = (text or "").strip()
188
- if not raw:
189
- return {"route": "empty", "text": self._help()}
190
- norm = normalize(raw)
191
- cyr = len(re.findall(r"[а-я]", norm))
192
- lat = len(re.findall(r"[a-z]", norm))
193
- russian = cyr >= lat
194
- site_hits = self._match_sites(norm)
195
- explain = _has_marker(norm, EXPLAIN_MARKERS)
196
- search = _has_marker(norm, SEARCH_MARKERS) or "погугли" in norm or "загугли" in norm
197
- navigate = _has_marker(norm, NAV_MARKERS)
198
-
199
- if explain and not navigate:
200
- concept = self._match_concept(norm)
201
- if concept is not None:
202
- return {"route": "explain", "text": concept, "question": raw}
203
- if site_hits:
204
- return self._describe_site(site_hits[0], russian)
205
-
206
- short = len(norm.split()) <= 4
207
- if short and not explain and not search:
208
- if _has_marker(norm, SCREENSHOT_MARKERS) and not site_hits:
209
- return {"route": "browser", "text": _dumps({"action": "screenshot"})}
210
- if _has_marker(norm, RELOAD_MARKERS) and not site_hits:
211
- return {"route": "browser", "text": _dumps({"action": "reload"})}
212
- if _has_marker(norm, BACK_MARKERS) and not site_hits:
213
- return {"route": "browser", "text": _dumps({"action": "back"})}
214
- if _has_marker(norm, FORWARD_MARKERS) and not site_hits:
215
- return {"route": "browser", "text": _dumps({"action": "forward"})}
216
-
217
- if search:
218
- return self._search(raw, norm, site_hits, russian)
219
- if navigate or site_hits:
220
- if site_hits:
221
- site = self._prefer_site(site_hits, russian, norm)
222
- return {
223
- "route": "navigate",
224
- "site": site["key"],
225
- "text": _dumps({"action": "navigate", "url": site["url"]}),
226
- }
227
- if _has_marker(norm, CLICK_MARKERS):
228
- label = _strip_markers(norm, CLICK_MARKERS + NAV_MARKERS) or raw
229
- return {"route": "click", "text": _dumps({"action": "click", "text": label})}
230
- if _has_marker(norm, TYPE_MARKERS):
231
- label = _strip_markers(norm, TYPE_MARKERS + NAV_MARKERS) or raw
232
- return {"route": "type", "text": _dumps({"action": "type", "text": label})}
233
- if _has_marker(norm, SCROLL_MARKERS):
234
- direction = "up" if any(word in norm for word in ("вверх", "up")) else "down"
235
- return {"route": "scroll", "text": _dumps({"action": "scroll", "direction": direction, "amount": 600})}
236
-
237
- concept = self._match_concept(norm)
238
- if concept is not None and (explain or self._concept_score(norm) >= 0.67):
239
- return {"route": "explain", "text": concept}
240
-
241
- if site_hits and not explain:
242
- site = self._prefer_site(site_hits, russian, norm)
243
- return {
244
- "route": "navigate",
245
- "site": site["key"],
246
- "text": _dumps({"action": "navigate", "url": site["url"]}),
247
- }
248
- return {"route": "fallback", "text": self._help()}
249
-
250
- def _match_sites(self, norm: str) -> list[dict]:
251
- hits = []
252
- occupied = [False] * len(norm)
253
- for alias, sites in self._alias_groups:
254
- match = re.search(word_pattern(alias), norm)
255
- if match is None:
256
- continue
257
- span = range(match.start(), match.end())
258
- if any(occupied[i] for i in span):
259
- continue
260
- for i in span:
261
- occupied[i] = True
262
- for site in sites:
263
- if site not in hits:
264
- hits.append(site)
265
- return hits
266
-
267
- def _prefer_site(self, hits: list[dict], russian: bool, norm: str) -> dict:
268
- if any(word in norm for word in ("english", "англ")):
269
- for site in hits:
270
- if site["key"] == "wiki_en":
271
- return site
272
- if russian:
273
- for site in hits:
274
- if site["key"] == "wikipedia":
275
- return site
276
- else:
277
- for site in hits:
278
- if site["key"] == "wiki_en":
279
- return site
280
- return hits[0]
281
-
282
- def _query_after_site(self, norm: str, site: dict) -> str:
283
- cleaned = self._remove_aliases(norm, only_site=site)
284
- cleaned = _strip_markers(cleaned, NAV_MARKERS + SEARCH_MARKERS)
285
- cleaned = re.sub(r"^(и|and|на|в)\s+", "", cleaned.strip())
286
- words = [word for word in cleaned.strip(" .,!?-").split() if word not in {"на", "в", "и", "and", "по", "к", "с", "со", "из", "от", "для", "про", "the", "a"}]
287
- return " ".join(words)
288
-
289
- def _search(self, raw: str, norm: str, site_hits: list[dict], russian: bool) -> dict:
290
- engine = None
291
- if "погугли" in norm or "загугли" in norm or re.search(r"(?<!\w)гугл(?!\w)", norm):
292
- engine = self._site_by_key("google")
293
- elif re.search(r"(?<!\w)яндекс(?!\w)", norm):
294
- engine = self._site_by_key("yandex")
295
- site = None
296
- if site_hits:
297
- site = self._prefer_site(site_hits, russian, norm)
298
- if engine is None and site["key"] in {"google", "yandex", "bing", "duckduckgo"}:
299
- engine = site
300
- site = None
301
- query = self._surface_query(raw, norm)
302
- if not query:
303
- if site is not None:
304
- return {
305
- "route": "navigate",
306
- "site": site["key"],
307
- "text": _dumps({"action": "navigate", "url": site["url"]}),
308
- }
309
- return {"route": "fallback", "text": "Напишите, что именно найти. Например: найди погода в Витебске."}
310
- target = site or engine or self._site_by_key("yandex" if russian else "google")
311
- if target is None:
312
- url = ("https://yandex.ru/search/?text=" if russian else "https://www.google.com/search?q=") + quote_plus(query)
313
- key = "yandex" if russian else "google"
314
- else:
315
- template = target.get("search_url") or (target["url"].rstrip("/") + "/search?q={q}")
316
- url = template.replace("{q}", quote_plus(query))
317
- key = target["key"]
318
- return {
319
- "route": "search",
320
- "site": key,
321
- "query": query,
322
- "text": _dumps({"action": "search", "query": query, "url": url}),
323
- }
324
-
325
- def _remove_aliases(self, norm: str, only_site: dict | None = None) -> str:
326
- cleaned = norm
327
- for alias, owners in self._alias_groups:
328
- if only_site is not None and only_site not in owners:
329
- continue
330
- cleaned = re.sub(word_pattern(alias), " ", cleaned)
331
- return re.sub(r"\s+", " ", cleaned)
332
-
333
- def _surface_query(self, raw: str, norm: str) -> str:
334
- """Drop site names and command words, but keep the user's spelling."""
335
- text = raw
336
- phrases = [alias for alias, _owners in self._alias_groups]
337
- phrases.extend(SEARCH_MARKERS + NAV_MARKERS + ("через",))
338
- for phrase in sorted(set(phrases), key=len, reverse=True):
339
- text = re.sub(word_pattern(normalize(phrase)), " ", text, flags=re.IGNORECASE)
340
- text = re.sub(r"\s+", " ", text).strip(" .,!?-—\"'«»")
341
- text = re.sub(r"^(и|and|на|в)\s+", "", text, flags=re.IGNORECASE)
342
- text = re.sub(r"\s+(и|and|на|в)$", "", text, flags=re.IGNORECASE).strip()
343
- if text:
344
- return text
345
- # Fall back to the normalized leftover if case-preserving cleanup ate everything.
346
- leftover = self._remove_aliases(norm)
347
- leftover = _strip_markers(leftover, SEARCH_MARKERS + NAV_MARKERS + ("через",))
348
- leftover = re.sub(r"^(и|and|на|в)\s+", "", leftover.strip())
349
- return leftover.strip(" .,!?-")
350
-
351
- def _site_by_key(self, key: str) -> dict | None:
352
- for site in self.sites:
353
- if site["key"] == key:
354
- return site
355
- return None
356
-
357
- def _describe_site(self, site: dict, russian: bool) -> dict:
358
- if russian:
359
- text = (
360
- f"{site.get('name_ru') or site.get('name_en')} — сайт в интернете, категория «{site.get('category')}». "
361
- f"Адрес: {site['url']}"
362
- )
363
- else:
364
- text = (
365
- f"{site.get('name_en') or site.get('name_ru')} is a website in the «{site.get('category')}» category. "
366
- f"Address: {site['url']}"
367
- )
368
- return {"route": "describe", "site": site["key"], "text": text}
369
-
370
- def _concept_score(self, norm: str) -> float:
371
- user = tokens(norm)
372
- best = 0.0
373
- for q_tokens, _question, _answer in self._concepts:
374
- if not q_tokens:
375
- continue
376
- inter = user & q_tokens
377
- if q_tokens <= user:
378
- score = 1.0
379
- else:
380
- score = len(inter) / len(q_tokens)
381
- if score > best:
382
- best = score
383
- return best
384
-
385
- def _match_concept(self, norm: str) -> str | None:
386
- user = tokens(norm)
387
- if not user:
388
- return None
389
- best = None
390
- best_key = (-1.0, -1, 0)
391
- for q_tokens, question, answer in self._concepts:
392
- inter = user & q_tokens
393
- if not inter:
394
- continue
395
- covered = q_tokens <= user
396
- score = 1.0 if covered else len(inter) / len(q_tokens)
397
- if score < 0.67 and not covered:
398
- continue
399
- # Prefer a full cover of a more specific question, then the closer length.
400
- key = (score, len(inter), -abs(len(q_tokens) - len(user)))
401
- if key > best_key:
402
- best_key = key
403
- best = answer
404
- if best is not None:
405
- return best
406
- # «что такое HTTPS?» may share only one distinctive word with a longer card.
407
- if any(marker in norm for marker in EXPLAIN_MARKERS):
408
- for token in sorted(user, key=len, reverse=True):
409
- if len(token) < 3:
410
- continue
411
- owners = [answer for q_tokens, _question, answer in self._concepts if token in q_tokens]
412
- if len(owners) == 1:
413
- return owners[0]
414
- return None
415
-
416
- @staticmethod
417
- def _help() -> str:
418
- return (
419
- "Я Hasimion 1.0. Могу открыть известный сайт, собрать ссылку поиска "
420
- "или коротко объяснить, как устроен интернет: DNS, HTTPS, cookie, VPN и другие темы из памяти. "
421
- "Пример: «открой ютуб» или «что такое DNS?». "
422
- "Я не храню весь интернет и не выдумываю адрес, если сайта нет в каталоге."
423
- )
424
-
425
-
426
- def main() -> None:
427
- import argparse
428
-
429
- parser = argparse.ArgumentParser(description="Спросить Hasimion 1.0 без загрузки нейросетей")
430
- parser.add_argument("--model", default=".", help="каталог распакованной модели")
431
- parser.add_argument("text", nargs="*", help="реплика")
432
- args = parser.parse_args()
433
- text = " ".join(args.text).strip() or input("Вы: ")
434
- print(InternetMemory.from_pretrained(args.model).chat(text))
435
-
436
-
437
- if __name__ == "__main__":
438
- main()