Douyin Account Crawling & Report Generation
Current document version: 0.7.5. music_download_url refers to the mixed audio track of the published video, not an independent pure BGM.
Trigger Scenarios
- Provide account homepage URL (
douyin.com/user/{sec_uid}) → Batch crawl all videos - Provide single video URL (
douyin.com/video/{aweme_id}) → Crawl a single video - Request to generate a benchmark analysis report based on the crawled data
Process Overview (4 Stages)
- Crawl (
tools/crawl.py, built-in MediaCrawler wrapper): Usedetailmode to crawl a single video,creatormode to batch crawl an account. Forcreator,--max Nis injected and validated by the skill with a hard upper limit, trimming the current page in the save callback and stopping pagination after reaching N; if the patch is incompatible, exit directly, then perform a hard truncation once based on the homepage return order in post-processing, not trusting a potentially invalid--crawler_max_notes_count. Automatically resolves MediaCrawler, supports resume from breakpoints, progress logs, and isolates the run directory. Each creator must use a unique--accountslug; pointing the same slug to a different account is rejected outright. If MediaCrawler fails, do not switch to other fallback crawling methods.- Comment crawling: Enabled by default, targeting 100 top-level comments per video (
--comments-count 100); skip only if--no-commentis explicitly passed. Comment artifacts land in<root>/crawl_<account>/douyin/jsonl/detail_comments_*.jsonl, which are then aggregated bycomments.pyby likes, keeping a maximum of 100 per video. The comment API requires a login session; if the session is unavailable or the 100-comment configuration cannot be guaranteed, fail directly without silent degradation. Note: Use Pythonsubprocessfor the batch processing loop, notpowershell -Filewith Chinese paths.
- Comment crawling: Enabled by default, targeting 100 top-level comments per video (
- Data Processing:
process.pydeduplication → manifest →download.pydownload videos/covers; for image-text posts, download original images and enter the unified frame analysis contract. - Content Analysis: Preferentially use
analyze.pyfor a one-click pipeline: "audio transcription → adaptive frame extraction & BGM parallel → per-frame visual analysis". For talking-head videos, prioritize usingpublished_audio_url(the mixed audio track of the published video) in the manifest for transcription; fall back to local MP4 extraction if download or decoding fails, and finally to the remote video. BGM reuses the same published cache and excludes talking-head windows based on transcript segments. Each video gets a minimum of 12 uniform sampling points, 3 FPS for the first three seconds, with interpolation for sudden scene changes; only low-confidence segments with a confidence interval get localized densification. Frame extraction defaults to NVDEC +scale_cudatwo-stage pipeline, with a maximum of 180 frames; GPU failures automatically fall back to CPU per video. Outputsframes.json, per-videovisual-summary.json, and account-level_visual-summary.json, covering artistic style, color, composition, scene candidates, subtitle style, and product exposure candidates; visual summaries further feed intoreport_html.pyfor the content matrix and viral comparison. Scene and product candidates must retain confidence/pending-review status, never presented as confirmed identifications. - Report Generation (v2 fixed skeleton, data and narrative separated): The benchmark report uses the built-in
tools/report_html.pyto directly output a fixed-skeleton HTML — a 10-zone skeleton, statistics, multiple SVG charts (weekly distribution / monthly trend / topic ring / like distribution / BGM comparison / emotion distribution), covers, and key frames auto-inlined solidly within the tool. All statistical numbers are computed in real-time by the tool from pipeline artifacts (manifest/comments/_cross/frames/covers); the AI only writesnarrative.jsonaccording to the slot schema ofreferences/report-template.md(qualitative conclusions / slogans / catchphrases / solutions), without manually writing any statistics; missing source sections are automatically omitted with an appended disclaimer about missing sources, and fabrication is forbidden. Design aesthetics are entirely determined by the AI — the AI provides a complete set of color palette / border radius / shadow / font tokens via thedesignkey in the narrative (or CLI--design); if the key is missing, fall back to a high-readability baseline, and proactively switch to a different set for each report to avoid repetition.render_report.pyis used only for blogger full-video summaries / decompose long-form articles (free markdown + fixed skeleton, design aesthetics entirely determined by the AI, pass visual tokens via--design '<json>'), and no longer renders benchmark reports (the two paths have been converged to prevent conflicts). If the user requests video-level reverse decomposition / account-level deep summary, followreferences/decompose-methodology.mdto complete the data chain (all videos per item, 11-section tags →decompose/tags.json→ viral TOP + typical 11-section deep dives), and first runtools/account_metrics.pyto automatically aggregate account-level dimensions (posting rhythm / interaction cross-clustering / topic strategy + high-like comments →decompose/<account>/_metrics.json, essential data for blogger summaries), then use the blogger full-video summary prompt fromreferences/blogger-summary-prompt.mdto create an account-level summary for all videos (positioning / topic map / Hook / content structure / visuals / user needs / viral comparison / DNA / opportunities / final output), producing Markdown that is then rendered into HTML viatools/render_report.py.
Authoritative Reference Skeleton Structure (must be followed when user requires "H1/H2/H3 strictly according to reference HTML"): The chapter skeleton of the reference file
https://share.traecontent.cn/artifact/69IZX28CO_67JPis 01~07 chapters — 01 How to add creators as benchmarking accounts / 02 Creator profile overview / 03 Content matrix breakdown / 04 Copywriting logic deep dive / 05 Product promotion and monetization logic / 06 Live streaming logic / 07 Differentiated content strategy, with an outer layer of data sample composition (five-source card) → key metrics (4 large numbers) → core conclusion. Note thatreport_html.pydefaults to chapters 01~08 (includes separate "Commentary Evidence" and "BGM×Interaction" chapters, no chapter 06 on live streaming), which differs from the reference skeleton; when the user requires strict adherence to the reference HTML structure, userender_report.py+ manually crafted_benchmark_src.md(following the 01~07 skeleton of report-template.md), notreport_html.py.
Detailed commands are in references/workflow.md, references/commands.md; lessons learned in references/lessons-learned.md; fixed report template in references/report-template.md; per-video reverse decomposition in references/decompose-methodology.md; blogger full-video summary prompt (account-level) in references/blogger-summary-prompt.md.
Before publishing or pushing this skill, you must read the "pre-publish checklist" in references/distribution.md: Commit messages must be in Chinese, and every commit must sync the README update; publish versions must also sync the version badge in manifest.json and README.
Practical Optimization Points (2026-08 iteration summary)
Speed Optimization
- Crawling: When crawl anomalies / missed items occur, prioritize fixing MediaCrawler itself (signature parameters, pagination parameters, login session), verify actual video count, do not switch to browser-based fallback (historically, a temporary fix using browser-internal fetch to directly call the API was used, but has been deprecated — it was disconnected from the MediaCrawler stack, prone to new issues, and violated the "fix the root cause" principle).
- Pipeline resume from breakpoints: Downloads / frame extraction / transcription all automatically skip completed items based on artifacts; processing new data only handles increments (in practice, only 105 out of 162 items were re-run).
- Unified reuse of published audio: The manifest's
published_audio_url(compatible with legacymusic_download_url/music_url/audio_url) is the mixed audio track of the published video.cached_published()atomically caches it tomedia-audio/<account>/published/<url_hash>.mp3based on URL hash; talking-head ASR uses it first; only fall back to local MP4 extraction if download or decoding fails, then to the remote video. BGM reuses the same file, not referred to as independent pure BGM. - Adaptive transcription precision: Talking-head transcription uniformly uses faster-whisper large-v3, with initial
beam_size=1; for low-confidence cases (language / average logprob / empty segments), re-run the same audio withbeam_size=5. GPU defaults to float16; falls back gracefully per code if unsupported; cache validation includes audio hash, configuration, actual device, and compute type. - BGM analysis only on mixed audio track evidence:
transcribe_bgm.pyreuses the published mixed audio track, excludes talking-head windows based on transcript segments, then computes energy/emotional evidence for non-speech intervals; by default, does not run a second Whisper pass. When non-speech evidence is insufficient, outputunknown/insufficient evidence, never present as pure BGM or lyrics conclusions. - Run logs and resumption: Each crawl generates an append-only
run.logand an atomically updatedrun-state.jsonin the current run directory root, withRunProgresscontinuously recording stage status,duration_sec, and crawl optimization throughput (e.g., saved detail requests, skipped comment requests); explicit reuse via--run-dirvalidates account identity and resumes from MediaCrawler cursor and stage completion markers. - Unique run root: On the first crawl, create a timestamped run root in the parent directory and write
.douyin-crawl-run.json; subsequent comment retries or supplementary crawls must reuse that root. Even if an Agent mistakenly passes an existing run root again via--root, the tool will recognize and reuse it; never generate<account>-timestamp/subdirectories inside the run root. - Cross-Agent current pointer: The parent directory maintains
.douyin-crawl-current-<account>.json, and an account-level directory lock is used when creating the run root. Other Agents, even if they only pass the parent directory, will reuse the run root pointed to by the pointer; if no pointer exists, only scan the first level of the parent directory and select the most recent valid root, never nested directories. Only create a new run when the user explicitly starts a new round with--new-run; do not habitually create new ones. - Stage parallelism: Downloads (network I/O) and frame extraction can run in parallel; frame extraction defaults to GPU single worker, BGM does not load Whisper, the compatibility parameter
--music-asris ignored, thus it can run in parallel with GPU frame extraction without competing for VRAM.
Quality Optimization
- Verify actual video count: After crawling, must compare with the number displayed on the homepage to prevent silent missing items due to signature invalidity (once only 57/162 items were caught).
- Data integrity validation: Newly crawled data must override old data (matched by aweme_id), ensuring complete fields and reasonable time span for completion.
- Reports based on full data: Hardcoded numbers in reports (total likes / average likes / category counts / viral list) must be consistent with the latest dataset, never using old samples.
- 100% transcription success rate: Automatically re-transcribe on errors, confirm 0 failures before reporting.
- Supplement: include captured content not explicitly in the skeleton into appropriate sections — if, after generation, pipeline artifacts contain empirical evidence not directly presented by the reference skeleton (user voice spectrum and high-like comment original text → merge into 03 Content Matrix; BGM×Interaction inter-group multiples → merge into 03 Sound Layer; origin/scene topic average likes vs. brand words → merge into 03/04), add as H3 sub-subsections, preserving the reference skeleton without adding new top-level chapters; citations must read data from original artifacts (manifest/_metrics/_cross/comments) and include a scope statement (comments as "sampled by likes, ≤100 per video, not complete", BGM inter-group multiples as "correlated, not causal", absence of hourly data for posting time as "topic-side inference").
Bug Fixes
a_bogussignature invalid (symptom: API returns truncated data, missed items): Check the signature parameters for that account's crawl stack (browser_version/os_name/pc_libra_divert/from_user_pageetc.) and fix MediaCrawler source code, then re-crawl, do not fall back to browser-based workarounds.- Premature pagination termination (symptom:
has_more=0but more data exists): Missing request parameters likefrom_user_page=1,show_live_replay_strategy=1,need_time_list=1, etc. Fix: add missing parameters and crawl page by page. - Risk control blocking (account blocked): Signature parameters (
browser_version,os_name) inconsistent with the real browser. Fix: dynamically generate parameters from the browser'snavigatorobject in real-time, and addpc_libra_divert. - CDP accidentally closes browser:
browser.close()inconnect_over_cdpmode will close the user's active Chrome browser. Fix: only disconnect at script end, do not callbrowser.close(). - Browser locked: TRAE browser control plugin may lock the CDP browser; confirm browser availability before crawling.
Key Constraints
- ~230 API limit per session; batch operations need resume from breakpoints over multiple runs
- Request intervals controlled by crawl parameters, default safe pace;
--sleep-min/--sleep-maxenables independent random sampling per request to prevent ArgusSecurityPlugin interception - Visual analysis must be authentic, not inferred or fabricated
- Live streaming speech requires manual verification for accent-related misrecognitions (product names / techniques / professional terms)
- Report images must use real extracted frames, not AI-generated images
Three Hard Constraints for Report Presentation (established 2026-08-19)
For blogger full-video summary / decompose long-form articles (render_report.py):
- No table of contents: Default single column without ToC (top brand banner replaces sidebar nav),
--no-tocis default; only--tocexplicitly restores the sidebar ToC. - Images must not be too large or intrusive: The renderer default formats inline extracted frames as a "photo grid" —
figure.imgin pairs (width:calc(50% - 8px)), single images centered ≤420px,imgmax height 460px + thin border + slight padding to create a polished photo card look, preventing a single image from filling the entire row. - Global fixed skeleton: Follow the fixed template (
https://share.traecontent.cn/artifact/69IZX28CO_67JP), only change design aesthetics (--design '<json>'for the complete set of color palette / font / border radius / shadow tokens), never alter the HTML skeleton structure like chapter index / big number cards / intake area callouts.
Runtime and Dependency Strategy (Important)
- Runtime installed in project directory: Analysis runtime is uniformly placed in each project's
<project root>/.runtime/py(faster-whisper / av / pillow / numpy / cublas, etc., 27 items), not installed on C drive. - Global registration for reuse (no re-installation when switching directories): The runtime path is written to the global pointer
~/.trae-cn/runtime-registry.json, and any project/directory call reuses the same runtime via the skill's built-in parsertools/runtime.py:py -3 <skill>/tools/runtime.py py(print runtime interpreter path)py -3 <skill>/tools/runtime.py doctor(verify dependencies + CUDA detection)py -3 <skill>/tools/runtime.py run --tool <name>.py --root <work root> --account <slug> [args](run tool with runtime interpreter)- Resolution priority:
DOUYIN_RUNTIME_PYenvironment variable > global pointer > project.runtime/py(only these three levels; skill's old.venvis deprecated and not resolved).
- Crawl engine MediaCrawler venv is also registered in the global pointer (
keys.mediacrawler); its source code is temporarily stored in~/.cache/codex-mediacrawler/. - All artifacts land in project directory: Videos →
videos/, extracted frames →video-analysis/<account>/frames, published mixed audio →media-audio/<account>/published/, transcripts →transcript/, model cache → projectmodels_cache/(HF_ENDPOINT/HF_HUB_DISABLE_XET=1already configured).
Built-in One-Click Pipeline (tools/)
This skill comes with executable scripts in tools/, covering the entire chain from "crawl → deduplicate → download → extract frames → talking-head transcription → report" in a single command, with unified input --root <work root> --account <account slug>, all executed via tools/runtime.py run --tool using the project runtime interpreter:
crawl.py (crawl), process.py (deduplication manifest), download.py (download), transcribe.py (audio transcription), extract_frames.py (adaptive frame extraction), analyze_frames.py (per-frame metrics/OCR), transcribe_bgm.py (BGM), bgm_cross.py (BGM×Interaction), comments.py (comments), decompose_prep.py (video profiles), account_metrics.py (account aggregation), report_html.py (fixed skeleton report), render_report.py (free Markdown report). Each script supports resume from breakpoints based on its artifacts. See references/workflow.md and references/commands.md for complete usage.
Output Contract
| Stage | Artifact | Path |
|---|---|---|
| Crawl | JSONL (raw + filtered deduplicated) + logs | crawl_<account>/, crawl_<account>/<account>_dedup.jsonl |
| Processing | Download manifest (sorted by interaction, includes work type/audio source) | video-analysis/<account>/manifest.json |
| Download | Videos / image-text original images / covers | videos/<account>/, images/<account>/, covers/<account>/ |
| Analysis | Extracted frames + talking-head transcription | video-analysis/<account>/frames/<aweme_id>/, transcript/<account>/, media-audio/<account>/published/ |
| BGM | Mixed audio non-speech evidence archive + cross statistics | media-audio/<account>/published/, bgm/<account>/, bgm/<account>/_cross.json |
| Report | Benchmark HTML (v2 fixed skeleton, self-contained single file) | {account}-benchmark-report.html (report_html.py) + video-analysis/<account>/narrative.json |
| Report | Reference skeleton benchmark HTML (01~07 including 06 Live, strictly follows reference HTML) | {account}-benchmark-report-(reference-skeleton).html (render_report.py + manual _benchmark_src.md) |
| Report | Blogger summary HTML (free markdown rendering) | {account}-blogger-full-video-summary.html (render_report.py) |
| Comments | Aggregated (per video, truncated by likes) | video-analysis/<account>/comments.json |
| Decomposition | Full video profiles + account-level aggregation | decompose/<account>/video_profiles.{json,md}, decompose/<account>/_metrics.json |
Output Quality Guardrails
- Repair generic headings, cluttered notes, fragile visual assumptions, weak tables, and missing verification cues before handing work back.
- Map role, task, and format into skill behavior rather than copying a large prompt template into
SKILL.md. - Let the artifact's content choose the visual system; do not copy a fixed palette or report style from another skill without a clear reason.
- If output-specific evidence is missing, state the gap instead of inventing screenshots, citations, data, or examples.
Honest Boundaries
- Use this skill for the recurring job described in the trigger, not for one-off adjacent requests.
- Treat missing inputs, unclear outputs, or conflicting constraints as reasons to ask one focused clarification.
- Do not add new references, scripts, evals, or governance unless they improve reliability more than they add weight.
- Comply with platform rules and legal boundaries: only crawl public information, do not perform platform reverse engineering or large-scale scraping.
Version Synchronization
Any Agent updating this skill must also increate the version number in agents/openai.yaml under interface.display_name. The display name format is fixed as GM 中文用途 V<version>; do not only update skill content while forgetting the list version.
File Encoding
Text files within this skill must be saved with UTF-8 (without BOM). When reading, generating, or validating Chinese files, explicitly specify UTF-8; on Windows, use python -X utf8 or set PYTHONUTF8=1 when running Python validators, do not rely on the system default GBK encoding.