mastodon-crawler: реализация — crawler/mastodon_crawler.py, источники mastodon (base_url+hashtag/lookup_acct), интеграция crawl_sources

- crawler/mastodon_crawler.py: публичная/хэштег/аккаунт-ленты (Mastodon API, httpx),
  пагинация max_id (первый запуск — свежая страница), дедуп по status.id, состояние
  mastodon_state (last_id, ошибки→dead), runs как mastodon:<slug>, CLI --all/--source/--dry-run
- sources.py: валидация crawler=mastodon + base_url, sync/CRUD/normalize новых полей,
  parse_address_mastodon (инстанс/тег/аккаунт), delete_source чистит mastodon_state
- sources.yaml: 6 примеров mastodon-источников (enabled: false)
- classifier/keywords.py: SOURCE_RULES для mastodon-источников
- crawl_sources.py: --crawler mastodon
- db/schema.sql+db.py: колонки base_url/hashtag/lookup_acct в sources, таблица mastodon_state
  (db/ в .gitignore — применяется локально)
- tasks.md: все [x]; STATUS.md обновлён
This commit is contained in:
kpa39l
2026-10-03 13:35:07 +00:00
parent ed9d5b9370
commit 4b641774b8
7 changed files with 535 additions and 44 deletions
+86 -16
View File
@@ -32,20 +32,23 @@ def sync_sources_to_db(data=None):
if not slug:
continue
cur = conn.execute(
"""INSERT INTO sources (slug, name, url, channel, crawler, feed_url, direction, lang, priority, enabled, status, own)
VALUES (?,?,?,?,?,?,?,?,?,?, 'new', ?)
ON CONFLICT(slug) DO UPDATE SET
name=excluded.name, url=excluded.url, channel=excluded.channel,
crawler=excluded.crawler, feed_url=excluded.feed_url,
direction=excluded.direction,
lang=excluded.lang, priority=excluded.priority, enabled=excluded.enabled,
own=excluded.own""",
(slug, s.get("name"), s.get("url"), s.get("channel"),
s.get("crawler", "telegram"), s.get("feed_url"),
s.get("direction"), s.get("lang", "ru"),
s.get("priority", "P1"), int(s.get("enabled", True)),
int(s.get("own", False) or 0)),
)
"""INSERT INTO sources (slug, name, url, channel, crawler, feed_url, base_url, hashtag, lookup_acct, direction, lang, priority, enabled, status, own)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?, 'new', ?)
ON CONFLICT(slug) DO UPDATE SET
name=excluded.name, url=excluded.url, channel=excluded.channel,
crawler=excluded.crawler, feed_url=excluded.feed_url,
base_url=excluded.base_url, hashtag=excluded.hashtag,
lookup_acct=excluded.lookup_acct,
direction=excluded.direction,
lang=excluded.lang, priority=excluded.priority, enabled=excluded.enabled,
own=excluded.own""",
(slug, s.get("name"), s.get("url"), s.get("channel"),
s.get("crawler", "telegram"), s.get("feed_url"),
s.get("base_url"), s.get("hashtag"), s.get("lookup_acct"),
s.get("direction"), s.get("lang", "ru"),
s.get("priority", "P1"), int(s.get("enabled", True)),
int(s.get("own", False) or 0)),
)
mapping[slug] = cur.lastrowid
return mapping
@@ -181,6 +184,9 @@ def db_source_to_yaml(source: dict) -> dict:
"channel": source.get("channel"),
"crawler": source.get("crawler", "telegram"),
"feed_url": source.get("feed_url"),
"base_url": source.get("base_url"),
"hashtag": source.get("hashtag"),
"lookup_acct": source.get("lookup_acct"),
"direction": source.get("direction"),
"lang": source.get("lang", "ru"),
"priority": source.get("priority", "P1"),
@@ -229,6 +235,8 @@ def parse_address(address: str, crawler: str) -> dict:
return {}
handle = m.group(1)
return {"slug": handle, "channel": handle, "url": f"https://t.me/{handle}"}
if crawler == "mastodon":
return parse_address_mastodon(addr)
# rss
if not _RSS_URL_RE.match(addr):
return {}
@@ -237,19 +245,69 @@ def parse_address(address: str, crawler: str) -> dict:
return {"feed_url": addr, "url": addr, "slug": host}
_MASTODON_TAG_RE = re.compile(r"^https?://([^/]+)/tags/([a-zA-Z0-9_]+)/?$")
_MASTODON_ACCT_RE = re.compile(r"^@?([a-zA-Z0-9_]+)@([a-zA-Z0-9_.-]+)$")
def parse_address_mastodon(addr: str) -> dict:
"""Разбирает address для crawler=mastodon.
https://host/tags/<tag> → {base_url, hashtag, url, slug: host-tag}
https://host/@user [@instance] → account-лента (lookup_acct = user@host)
https://host → публичная лента, slug = host
@user@host | user@host → account-лента (lookup_acct)
Возвращает {} если не разобрано.
"""
addr = (addr or "").strip()
if not addr:
return {}
base = addr.rstrip("/")
m = _MASTODON_TAG_RE.match(addr)
if m:
host, tag = m.group(1), m.group(2).lower()
return {
"base_url": f"https://{host}",
"hashtag": tag,
"url": addr,
"slug": f"{host.split('.')[0]}-{tag}",
}
if addr.startswith(("http://", "https://")):
from urllib.parse import urlparse
host = urlparse(base).netloc
if not host:
return {}
# https://host/@user — account-лента
m2 = re.match(r"^https?://([^/]+)/@([a-zA-Z0-9_]+)/?$", addr)
if m2:
acct = f"{m2.group(2)}@{m2.group(1)}"
return {"base_url": f"https://{m2.group(1)}", "lookup_acct": acct,
"url": addr, "slug": f"{m2.group(1).split('.')[0]}-{m2.group(2)}"}
return {"base_url": f"https://{host}", "url": addr,
"slug": host.split(".")[0] or "mastodon"}
m3 = _MASTODON_ACCT_RE.match(addr)
if m3:
user, instance = m3.group(1), m3.group(2)
acct = f"{user}@{instance}"
return {"base_url": f"https://{instance}", "lookup_acct": acct,
"url": f"https://{instance}/@{user}", "slug": f"{instance.split('.')[0]}-{user}"}
return {}
def _validate_source(data: dict) -> str | None:
"""Валидация полей источника. Возвращает текст ошибки или None."""
slug = str(data.get("slug") or "").strip()
if not slug or not _SLUG_RE.match(slug):
return "slug: только [a-z0-9_-]"
if data.get("crawler", "telegram") not in ("telegram", "rss"):
return 'crawler: только "telegram" или "rss"'
if data.get("crawler", "telegram") not in ("telegram", "rss", "mastodon"):
return 'crawler: только "telegram", "rss" или "mastodon"'
if str(data.get("priority", "P1")) not in ("P0", "P1", "P2", "P3"):
return "priority: только P0..P3"
if data.get("crawler") == "rss" and not str(data.get("feed_url") or "").strip():
return "rss-источнику нужен feed_url"
if data.get("crawler") == "telegram" and not str(data.get("channel") or "").strip():
return "telegram-источнику нужен channel"
if data.get("crawler") == "mastodon" and not str(data.get("base_url") or "").startswith(("http://", "https://")):
return "mastodon-источнику нужен base_url (https://инстанс)"
return None
@@ -269,6 +327,9 @@ def add_or_update_source(data: dict) -> tuple[bool, str]:
"channel": (data.get("channel") or "").strip() or None,
"crawler": data.get("crawler", "telegram"),
"feed_url": (data.get("feed_url") or "").strip() or None,
"base_url": (data.get("base_url") or "").strip() or None,
"hashtag": (data.get("hashtag") or "").strip() or None,
"lookup_acct": (data.get("lookup_acct") or "").strip() or None,
"direction": (data.get("direction") or "").strip() or None,
"lang": (data.get("lang") or "ru").strip() or "ru",
"priority": str(data.get("priority", "P1")).upper(),
@@ -289,6 +350,15 @@ def delete_source(slug: str) -> bool:
conn.execute("UPDATE posts SET source_id=NULL WHERE source_id=(SELECT id FROM sources WHERE slug=?)", (slug,))
conn.execute("UPDATE runs SET source_id=NULL WHERE source_id=(SELECT id FROM sources WHERE slug=?)", (slug,))
conn.execute("DELETE FROM rss_state WHERE slug=?", (slug,))
# mastodon_state ключуется по инстансу (base_url) — удаляем только если
# ни один оставшийся источник больше не использует этот инстанс
conn.execute(
"""DELETE FROM mastodon_state WHERE instance IN (
SELECT base_url FROM sources WHERE slug=?
AND NOT EXISTS (SELECT 1 FROM sources s2 WHERE s2.base_url=sources.base_url AND s2.slug<>?)
)""",
(slug, slug),
)
conn.execute("DELETE FROM sources WHERE slug=?", (slug,))
return True
+93 -14
View File
@@ -81,6 +81,31 @@
priority: P1
enabled: true
notes: git/devops — смежный с linux
- slug: huggingface-blog
name: Hugging Face Blog
url: https://huggingface.co/blog
channel: null
crawler: rss
feed_url: https://huggingface.co/blog/feed.xml
direction: llm
lang: en
priority: P1
enabled: true
own: false
notes: официальный блог HF — релизы моделей, гайды fine-tuning, новости платформы
- slug: huggingface-papers
name: Hugging Face Daily Papers
url: https://huggingface.co/papers
channel: null
crawler: rss
feed_url: https://papers.takara.ai/api/feed
direction: llm
lang: en
priority: P1
enabled: true
own: false
notes: ежедневная кураторская лента научных статей (arXiv-препринты, комментарии
сообщества) — официальный /papers.rss 404, используется сторонний papers.takara.ai
- slug: krxnotes
name: KRX Notes
url: https://t.me/krxnotes
@@ -128,6 +153,32 @@
priority: P1
enabled: true
own: false
- slug: fosstodon-selfhosting
name: Fosstodon
url: https://fosstodon.org/tags/selfhosting
channel: null
crawler: mastodon
base_url: https://fosstodon.org
hashtag: selfhosting
feed_url: null
direction: tech
lang: en
priority: P1
enabled: false
own: false
- slug: mastodon-social-linux
name: mastodon.social
url: https://mastodon.social/tags/linux
channel: null
crawler: mastodon
base_url: https://mastodon.social
hashtag: linux
feed_url: null
direction: linux
lang: en
priority: P1
enabled: false
own: false
- slug: omarchy
name: omarchy
url: https://omarchy.org/
@@ -139,30 +190,58 @@
priority: P1
enabled: false
own: false
- slug: huggingface-blog
name: Hugging Face Blog
url: https://huggingface.co/blog
- slug: sebastian-raschka
name: Sebastian Raschka (fedi)
url: https://mastodon.social/@SebRaschka
channel: null
crawler: rss
feed_url: https://huggingface.co/blog/feed.xml
crawler: mastodon
base_url: https://mastodon.social
lookup_acct: SebRaschka@mastodon.social
feed_url: null
direction: llm
lang: en
priority: P1
enabled: true
enabled: false
own: false
notes: официальный блог HF — релизы моделей, гайды fine-tuning, новости платформы
- slug: huggingface-papers
name: Hugging Face Daily Papers
url: https://huggingface.co/papers
- slug: simon-willison
name: Simon Willison (fedi)
url: https://fedi.simonwillison.net/@simon
channel: null
crawler: rss
feed_url: https://papers.takara.ai/api/feed
crawler: mastodon
base_url: https://fedi.simonwillison.net
lookup_acct: simon@fedi.simonwillison.net
feed_url: null
direction: llm
lang: en
priority: P1
enabled: true
enabled: false
own: false
- slug: stroughtonsmith
name: Steve Troughton-Smith (fedi)
url: https://mastodon.social/@stroughtonsmith
channel: null
crawler: mastodon
base_url: https://mastodon.social
lookup_acct: stroughtonsmith@mastodon.social
feed_url: null
direction: llm
lang: en
priority: P1
enabled: false
own: false
- slug: terence-eden
name: Terence Eden (fedi)
url: https://mastodon.social/@Edent
channel: null
crawler: mastodon
base_url: https://mastodon.social
lookup_acct: Edent@mastodon.social
feed_url: null
direction: llm
lang: en
priority: P1
enabled: false
own: false
notes: ежедневная кураторская лента научных статей (arXiv-препринты, комментарии сообщества) — официальный /papers.rss 404, используется сторонний papers.takara.ai
# Пример (включить, раскомментировав и поправив direction/приоритет):
# - slug: opennet