deepmodebot 0.0.0-stage → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +26 -0
- package/.omp-plugin/marketplace.json +26 -0
- package/LICENSE +24 -0
- package/README.md +377 -2
- package/bin/deepmodebot.mjs +229 -0
- package/lib/autoupdate.mjs +47 -0
- package/lib/clients.mjs +139 -0
- package/lib/run.mjs +32 -0
- package/lib/state.mjs +52 -0
- package/lib/tree.mjs +48 -0
- package/package.json +44 -4
- package/plugins/deepmodebot/.antigravity-plugin/plugin.json +35 -0
- package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +13 -0
- package/plugins/deepmodebot/.antigravity-plugin/skills/land-pr/SKILL.md +23 -0
- package/plugins/deepmodebot/.antigravity-plugin/skills/pr-thread/SKILL.md +17 -0
- package/plugins/deepmodebot/.antigravity-plugin/skills/review-pr/SKILL.md +16 -0
- package/plugins/deepmodebot/.antigravity-plugin/skills/tournament/SKILL.md +14 -0
- package/plugins/deepmodebot/.claude-plugin/plugin.json +27 -0
- package/plugins/deepmodebot/agents/reviewer/agent.md +33 -0
- package/plugins/deepmodebot/agents/scout/agent.md +34 -0
- package/plugins/deepmodebot/agents/security-reviewer/agent.md +30 -0
- package/plugins/deepmodebot/assets/logo.svg +8 -0
- package/plugins/deepmodebot/commands/contribute.md +8 -0
- package/plugins/deepmodebot/commands/deep.md +11 -0
- package/plugins/deepmodebot/commands/land-pr.md +12 -0
- package/plugins/deepmodebot/commands/pr-thread.md +14 -0
- package/plugins/deepmodebot/commands/project-brief.md +8 -0
- package/plugins/deepmodebot/commands/review-pr.md +10 -0
- package/plugins/deepmodebot/commands/tournament.md +12 -0
- package/plugins/deepmodebot/hooks/hooks.json +26 -0
- package/plugins/deepmodebot/hooks.json +24 -0
- package/plugins/deepmodebot/mcp_config.json +11 -0
- package/plugins/deepmodebot/scripts/antigravity-guard.mjs +413 -0
- package/plugins/deepmodebot/scripts/omp-mcp-server.mjs +1091 -0
- package/plugins/deepmodebot/skills/agent-harnesses/SKILL.md +57 -0
- package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/bun.lock +391 -0
- package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check.ts +53 -0
- package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_antigravity.py +38 -0
- package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/check_claude.mjs +11 -0
- package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/package.json +11 -0
- package/plugins/deepmodebot/skills/agent-harnesses/assets/sdks/requirements.txt +1 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/ai-native-tooling.md +190 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/ai-sdk-selection.md +50 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +108 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/claude-code.md +166 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/codex.md +151 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/delegation-efficiency.md +230 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/langchain-ecosystem.md +124 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/omp.md +183 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/protocols.md +172 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/sdks.md +228 -0
- package/plugins/deepmodebot/skills/agent-harnesses/references/self-authoring.md +171 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/SKILL.md +24 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/aws.md +264 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/azure.md +261 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/containers.md +96 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/devops-tools.md +297 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/devsecops-pipeline.md +258 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/gcp.md +258 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/kubernetes.md +74 -0
- package/plugins/deepmodebot/skills/cloud-devsecops/references/local-emulators.md +265 -0
- package/plugins/deepmodebot/skills/contribute/SKILL.md +134 -0
- package/plugins/deepmodebot/skills/create-verification-skill/LICENSE +21 -0
- package/plugins/deepmodebot/skills/create-verification-skill/SKILL.md +101 -0
- package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/README.md +47 -0
- package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/create-note.md +39 -0
- package/plugins/deepmodebot/skills/create-verification-skill/references/feature-map-example/search.md +45 -0
- package/plugins/deepmodebot/skills/deep-stack/SKILL.md +53 -0
- package/plugins/deepmodebot/skills/deep-stack/references/AGENTS.template.md +52 -0
- package/plugins/deepmodebot/skills/deep-stack/references/agentic-workflow.md +114 -0
- package/plugins/deepmodebot/skills/deep-stack/references/any-app-stack.md +51 -0
- package/plugins/deepmodebot/skills/deep-stack/references/design-workflow.md +101 -0
- package/plugins/deepmodebot/skills/deep-stack/references/isolate.md +23 -0
- package/plugins/deepmodebot/skills/deep-stack/references/philosophy.md +306 -0
- package/plugins/deepmodebot/skills/deep-stack/references/prove.md +31 -0
- package/plugins/deepmodebot/skills/deep-stack/references/stack.md +119 -0
- package/plugins/deepmodebot/skills/deep-stack/references/structure.md +22 -0
- package/plugins/deepmodebot/skills/deep-stack/references/unslop/LICENSE +21 -0
- package/plugins/deepmodebot/skills/deep-stack/references/unslop/unslop.md +80 -0
- package/plugins/deepmodebot/skills/deepmodebot/LICENSE +23 -0
- package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +198 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +207 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/test_agents_md.py +146 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/architecture-review/report-template.html +92 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +42 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +135 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain-link.ts +12 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +115 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_antigravity_guard.py +483 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_audit_regressions.py +139 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_contain.py +301 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/test_omp_mcp.py +602 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/design.py +242 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/evidence.py +293 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/record.py +387 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/review.py +339 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_design.py +69 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_evidence.py +160 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_record.py +180 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/e2e/test_review.py +265 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +44 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +132 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +122 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/test_git_guard.py +192 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/bot.py +3037 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/brand.json +11 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/brand.py +51 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/ghapp.py +361 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/install.py +274 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/local_updates.py +576 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/review_context.py +204 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_bot.py +2182 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_brand.py +19 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_local_updates.py +691 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_review_context.py +127 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/test_workspace_cleanup.py +496 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/github-app/workspace_cleanup.py +351 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +2394 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/plan.py +583 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_loop.py +1426 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_plan.py +320 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/test_windows_job.py +326 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/windows_job.py +244 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/bench_harness.py +165 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/perf_audit.py +240 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_bench_harness.py +55 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/perf-audit/test_perf_audit.py +53 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/diff_coverage.py +350 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/pr_agent_local.py +370 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-agent/test_diff_coverage.py +94 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.html +425 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena.py +579 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/arena_tui.py +839 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/font8x8_basic.hex +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/show_thread.py +329 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/pr-conversation/test_arena.py +610 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/repo-references.json +637 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/test_yt_enrich.py +250 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_enrich.py +1820 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_meta.py +156 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/scrape/yt_transcript_relay.js +54 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/audit-pr.sh +122 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/gate.cjs +155 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/security-audit/prompt.md +13 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/test_tournament.py +654 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/tournament/tournament.py +1285 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/wizard/wizard.sh +234 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/test_workspace_map.py +879 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/workspace-map/workspace_map.py +2436 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/README.md +61 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +105 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/contain.md +39 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/factory-landscape.md +147 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/flows.md +50 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +37 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/babysit.md +77 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/bug-fix.md +34 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/end-to-end.md +50 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/eval.md +39 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/feature.md +60 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/handoff.md +52 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +46 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/investigation.md +20 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/opening-a-pr.md +97 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/pause-safely.md +30 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/perf-issue.md +31 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/phased-build.md +146 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/prototype.md +31 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/refactoring.md +60 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/reference-rebuild.md +45 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/run-a-goal.md +143 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/runtime-forensics.md +22 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +130 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/session-pickup.md +33 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/setup.md +105 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/shipping.md +52 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/spec.md +67 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/tickets.md +56 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/trace-forensics.md +24 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/triage.md +102 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/visual-parity.md +19 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/wayfinder.md +44 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/work-a-queue.md +189 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/worktree-cleanup.md +35 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/attack-the-premise.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/boundary-discipline.md +8 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/build-the-lever.md +8 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/encode-lessons-in-structure.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/exhaust-the-design-space.md +4 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/experience-first.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/explain-the-number.md +9 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/fix-root-causes.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/foundational-thinking.md +9 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/guard-the-context-window.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/laziness-protocol.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/make-operations-idempotent.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/migrate-callers-then-delete-legacy-apis.md +5 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/minimize-reader-load.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/model-the-domain.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/never-block-on-the-human.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/outcome-oriented-execution.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/prove-it-works.md +8 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/redesign-from-first-principles.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/separate-before-serializing-shared-state.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/sequence-verifiable-units.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/subtract-before-you-add.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/test-behavior-not-implementation.md +7 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/type-system-discipline.md +6 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/rust-migration-case-studies.md +26 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/startup-ideas.md +21 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/agent-collaboration.md +82 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architect.md +32 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/architecture-review.md +43 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/arena.md +20 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/benchmark-checklist.md +31 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/blast-radius.md +19 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +20 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/course.md +47 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/coworkers.md +70 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/domain-model.md +69 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/figure-it-out.md +25 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/git-guardrails.md +44 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/github-app.md +160 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/goal-review.md +156 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/grill.md +27 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/how.md +23 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/in-your-own-words.md +12 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +39 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/interrogate.md +16 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/issue-conversation.md +52 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +29 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/open-design-evidence.md +65 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +34 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-agent.md +39 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-conversation.md +135 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pr-review.md +138 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/pre-commit.md +31 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/prior-art.md +44 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/questionnaire.md +46 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/re-explain.md +23 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/recall.md +19 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/reflect.md +20 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/research.md +99 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/retro.md +30 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/scrape.md +32 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/security-audit.md +40 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sharpen.md +15 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/show-me-your-work.md +19 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sme-review.md +49 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/swarm.md +14 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +55 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/teach.md +20 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/technical-writing.md +22 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tool-routing.md +85 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +44 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tracker.md +78 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/unslop.md +15 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/visual-e2e.md +78 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/why.md +31 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/wizard.md +25 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/workspace-map.md +35 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/writing-for-agents.md +66 -0
- package/plugins/deepmodebot/skills/deepmodebot/scripts/check_skill.py +93 -0
- package/plugins/deepmodebot/skills/deepmodebot/scripts/trending.py +598 -0
- package/plugins/deepmodebot/skills/domain-rules/SKILL.md +131 -0
- package/plugins/deepmodebot/skills/domain-rules/references/agent-engineering.md +105 -0
- package/plugins/deepmodebot/skills/domain-rules/references/ai-concepts.md +103 -0
- package/plugins/deepmodebot/skills/domain-rules/references/aws-networking.md +121 -0
- package/plugins/deepmodebot/skills/domain-rules/references/backend-system-design.md +162 -0
- package/plugins/deepmodebot/skills/domain-rules/references/data-structures-and-cache-optimization.md +48 -0
- package/plugins/deepmodebot/skills/domain-rules/references/devops-and-fundamentals.md +137 -0
- package/plugins/deepmodebot/skills/domain-rules/references/engineering-practice.md +100 -0
- package/plugins/deepmodebot/skills/domain-rules/references/high-scale-server-optimization.md +181 -0
- package/plugins/deepmodebot/skills/domain-rules/references/language-ecosystems.md +56 -0
- package/plugins/deepmodebot/skills/frontend-ui/SKILL.md +146 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/patterns/live-demos.md +38 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/patterns/mobbin-shipped-apps.md +28 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-clips.md +269 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/patterns/motion-graphics.md +62 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-animations.md +217 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/patterns/pinterest-patterns.md +101 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/01-workflow.md +25 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/02-review-rubric.md +21 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/03-ai-tells.md +46 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04-components.md +21 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/04a-agent-ui.md +153 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05-motion.md +106 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/05a-motion-graphics.md +121 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06-typography-layout.md +48 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/06a-color.md +26 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/07-copy.md +11 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/08-quality-floor.md +63 -0
- package/plugins/deepmodebot/skills/frontend-ui/references/playbook/09-steering-agents.md +13 -0
- package/plugins/deepmodebot/skills/maintain-verification-skill/LICENSE +21 -0
- package/plugins/deepmodebot/skills/maintain-verification-skill/SKILL.md +47 -0
- package/plugins/deepmodebot/skills/project-brief/SKILL.md +100 -0
- package/plugins/deepmodebot/skills/project-brief/assets/CONTRIBUTING.template.md +124 -0
- package/plugins/deepmodebot/skills/project-brief/assets/ISSUE_TEMPLATE/task.yml +61 -0
- package/plugins/deepmodebot/skills/project-brief/assets/PROJECT_BRIEF.template.md +98 -0
- package/plugins/deepmodebot/skills/project-brief/assets/PULL_REQUEST_TEMPLATE.md +35 -0
- package/plugins/deepmodebot/skills/project-brief/assets/pr-overlap.py +643 -0
- package/plugins/deepmodebot/skills/project-brief/assets/sync-roadmap.py +314 -0
- package/plugins/deepmodebot/skills/secrets-and-auth/SKILL.md +60 -0
- package/plugins/deepmodebot/skills/secrets-and-auth/references/agent-authentication.md +198 -0
- package/plugins/deepmodebot/skills/secrets-and-auth/references/leak-prevention.md +206 -0
- package/plugins/deepmodebot/skills/secrets-and-auth/references/logins-and-passwords.md +165 -0
- package/plugins/deepmodebot/skills/secrets-and-auth/references/secrets-and-env.md +182 -0
- package/plugins/deepmodebot/skills/software-architecture/SKILL.md +47 -0
- package/plugins/deepmodebot/skills/software-architecture/references/backend-infrastructure.md +273 -0
- package/plugins/deepmodebot/skills/software-architecture/references/databases.md +277 -0
- package/plugins/deepmodebot/skills/software-architecture/references/monorepos.md +210 -0
- package/plugins/deepmodebot/skills/software-architecture/references/ontology.md +287 -0
|
@@ -0,0 +1,1820 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Media-free YouTube enrichment CLI for the ai-video-learning skill.
|
|
3
|
+
|
|
4
|
+
Extracts richer signal from YouTube videos and channels using official APIs,
|
|
5
|
+
public feeds, static thumbnails, single-request watch-page metadata, companion
|
|
6
|
+
link mining, and official Gemini multimodal YouTube URL analysis—without
|
|
7
|
+
fetching googlevideo.com media streams or retrying on HTTP 403/429 denials.
|
|
8
|
+
|
|
9
|
+
Exit codes:
|
|
10
|
+
0 Success
|
|
11
|
+
1 Usage, missing dependency/env, or parse error
|
|
12
|
+
3 Blocked (HTTP 403/429, API quota/forbidden, login wall, or bot challenge)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import csv
|
|
19
|
+
import datetime as dt
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import random
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
import time
|
|
27
|
+
import urllib.error
|
|
28
|
+
import urllib.parse
|
|
29
|
+
import urllib.request
|
|
30
|
+
import xml.etree.ElementTree as ET
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Any
|
|
33
|
+
|
|
34
|
+
USER_AGENT = (
|
|
35
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
|
36
|
+
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
EXIT_OK = 0
|
|
40
|
+
EXIT_ERR = 1
|
|
41
|
+
EXIT_BLOCKED = 3
|
|
42
|
+
|
|
43
|
+
VIDEO_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$")
|
|
44
|
+
URL_RE = re.compile(r"https?://[^\s<>()\"'\]\\]+")
|
|
45
|
+
CHAPTER_LINE_RE = re.compile(
|
|
46
|
+
r"(?m)^\s*(?:[-*•]\s*)?((?:\d{1,2}:)?\d{1,2}:\d{2})\s*(?:[-–—:|]\s*|\s+)(.+?)\s*$"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
CANVAS_HOSTS = ("tldraw.com", "excalidraw.com", "figma.com", "miro.com", "whimsical.com")
|
|
50
|
+
SLIDE_HOSTS = ("speakerdeck.com", "slides.com", "slideshare.net", "docs.google.com")
|
|
51
|
+
PAPER_HOSTS = ("arxiv.org", "openreview.net", "aclanthology.org", "semanticscholar.org", "huggingface.co")
|
|
52
|
+
PODCAST_HOSTS = ("podcasts.apple.com", "open.spotify.com", "overcast.fm", "transistor.fm", "simplecast.com", "buzzsprout.com")
|
|
53
|
+
SOCIAL_HOSTS = ("x.com", "twitter.com", "linkedin.com", "bsky.app", "threads.net", "discord.gg", "discord.com")
|
|
54
|
+
IGNORE_HOSTS = ("youtube.com", "www.youtube.com", "youtu.be", "m.youtube.com", "i.ytimg.com", "yt3.ggpht.com")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class BlockedError(Exception):
|
|
58
|
+
"""Raised immediately on HTTP 403/429, login wall, or bot challenge (never retried)."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, *, source_url: str | None, status: int | None, reason: str, evidence: str):
|
|
61
|
+
super().__init__(evidence)
|
|
62
|
+
self.payload = {
|
|
63
|
+
"state": "blocked",
|
|
64
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
65
|
+
"source_url": source_url,
|
|
66
|
+
"http_status": status,
|
|
67
|
+
"reason": reason,
|
|
68
|
+
"evidence": evidence,
|
|
69
|
+
"action": "Stopped immediately without retry. Record blocked.json and wait for user clearance.",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_video_id(value: str) -> str:
|
|
74
|
+
"""Extract an 11-character YouTube video ID from a bare ID or URL."""
|
|
75
|
+
s = value.strip()
|
|
76
|
+
if VIDEO_ID_RE.match(s):
|
|
77
|
+
return s
|
|
78
|
+
parsed = urllib.parse.urlparse(s)
|
|
79
|
+
host = parsed.netloc.lower()
|
|
80
|
+
if host in ("youtu.be", "www.youtu.be"):
|
|
81
|
+
cand = parsed.path.lstrip("/").split("/")[0]
|
|
82
|
+
if VIDEO_ID_RE.match(cand):
|
|
83
|
+
return cand
|
|
84
|
+
if "youtube.com" in host:
|
|
85
|
+
qs = urllib.parse.parse_qs(parsed.query)
|
|
86
|
+
if "v" in qs and VIDEO_ID_RE.match(qs["v"][0]):
|
|
87
|
+
return qs["v"][0]
|
|
88
|
+
parts = [p for p in parsed.path.split("/") if p]
|
|
89
|
+
if len(parts) >= 2 and parts[0] in ("shorts", "live", "embed", "v") and VIDEO_ID_RE.match(parts[1]):
|
|
90
|
+
return parts[1]
|
|
91
|
+
raise ValueError(f"Could not extract YouTube video ID from: {value}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def http_get_once(url: str, *, headers: dict[str, str] | None = None, timeout: int = 25) -> tuple[int, str]:
|
|
95
|
+
"""Single HTTP GET with zero retries. Fails fast on 403/429."""
|
|
96
|
+
req_headers = {"User-Agent": USER_AGENT, "Accept-Language": "en-US,en;q=0.9"}
|
|
97
|
+
if headers:
|
|
98
|
+
req_headers.update(headers)
|
|
99
|
+
req = urllib.request.Request(url, headers=req_headers, method="GET")
|
|
100
|
+
try:
|
|
101
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
102
|
+
status = getattr(resp, "status", 200)
|
|
103
|
+
body = resp.read().decode("utf-8", errors="replace")
|
|
104
|
+
if status in (403, 429):
|
|
105
|
+
raise BlockedError(
|
|
106
|
+
source_url=url,
|
|
107
|
+
status=status,
|
|
108
|
+
reason=f"http_{status}",
|
|
109
|
+
evidence=f"Single GET returned HTTP {status}.",
|
|
110
|
+
)
|
|
111
|
+
return status, body
|
|
112
|
+
except urllib.error.HTTPError as exc:
|
|
113
|
+
err_body = ""
|
|
114
|
+
try:
|
|
115
|
+
err_body = exc.read().decode("utf-8", errors="replace")[:400]
|
|
116
|
+
except Exception:
|
|
117
|
+
pass
|
|
118
|
+
if exc.code in (403, 429):
|
|
119
|
+
raise BlockedError(
|
|
120
|
+
source_url=url,
|
|
121
|
+
status=exc.code,
|
|
122
|
+
reason=f"http_{exc.code}",
|
|
123
|
+
evidence=f"Single GET returned HTTP {exc.code}: {err_body.strip() or exc.reason}",
|
|
124
|
+
) from exc
|
|
125
|
+
raise RuntimeError(f"HTTP {exc.code} for {url}: {err_body.strip() or exc.reason}") from exc
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def http_get_bytes_once(url: str, *, headers: dict[str, str] | None = None, timeout: int = 25) -> tuple[int, bytes | None]:
|
|
129
|
+
"""Single binary HTTP GET with zero retries. Returns (404, None) on 404; fails fast on 403/429."""
|
|
130
|
+
req_headers = {"User-Agent": USER_AGENT}
|
|
131
|
+
if headers:
|
|
132
|
+
req_headers.update(headers)
|
|
133
|
+
req = urllib.request.Request(url, headers=req_headers, method="GET")
|
|
134
|
+
try:
|
|
135
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
136
|
+
status = getattr(resp, "status", 200)
|
|
137
|
+
data = resp.read()
|
|
138
|
+
if status in (403, 429):
|
|
139
|
+
raise BlockedError(
|
|
140
|
+
source_url=url,
|
|
141
|
+
status=status,
|
|
142
|
+
reason=f"http_{status}",
|
|
143
|
+
evidence=f"Single binary GET returned HTTP {status}.",
|
|
144
|
+
)
|
|
145
|
+
return status, data
|
|
146
|
+
except urllib.error.HTTPError as exc:
|
|
147
|
+
if exc.code == 404:
|
|
148
|
+
return 404, None
|
|
149
|
+
if exc.code in (403, 429):
|
|
150
|
+
raise BlockedError(
|
|
151
|
+
source_url=url,
|
|
152
|
+
status=exc.code,
|
|
153
|
+
reason=f"http_{exc.code}",
|
|
154
|
+
evidence=f"Single binary GET returned HTTP {exc.code}: {exc.reason}",
|
|
155
|
+
) from exc
|
|
156
|
+
raise RuntimeError(f"HTTP {exc.code} for {url}: {exc.reason}") from exc
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def unwrap_youtube_redirect(url: str) -> str:
|
|
160
|
+
"""Unwrap youtube.com/redirect?q=... links to their destination URL."""
|
|
161
|
+
cleaned = url.rstrip(".,;:!?)\"'")
|
|
162
|
+
parsed = urllib.parse.urlparse(cleaned)
|
|
163
|
+
if parsed.netloc.lower().endswith("youtube.com") and parsed.path == "/redirect":
|
|
164
|
+
qs = urllib.parse.parse_qs(parsed.query)
|
|
165
|
+
if "q" in qs and qs["q"]:
|
|
166
|
+
return urllib.parse.unquote(qs["q"][0]).rstrip(".,;:!?)\"'")
|
|
167
|
+
return cleaned
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def classify_url(url: str) -> str | None:
|
|
171
|
+
"""Classify an external companion URL into a source bucket; returns None for YouTube-internal links."""
|
|
172
|
+
parsed = urllib.parse.urlparse(url)
|
|
173
|
+
host = parsed.netloc.lower()
|
|
174
|
+
path = parsed.path.lower()
|
|
175
|
+
if not host or any(host == h or host.endswith("." + h) for h in IGNORE_HOSTS):
|
|
176
|
+
return None
|
|
177
|
+
if host in ("github.com", "www.github.com", "gist.github.com", "gitlab.com"):
|
|
178
|
+
return "github"
|
|
179
|
+
if any(host == h or host.endswith("." + h) for h in CANVAS_HOSTS):
|
|
180
|
+
return "canvas"
|
|
181
|
+
if any(host == h or host.endswith("." + h) for h in SLIDE_HOSTS) or path.endswith((".pdf", ".pptx", ".key")):
|
|
182
|
+
if host == "docs.google.com" and "/presentation/" not in path:
|
|
183
|
+
return "docs_or_web"
|
|
184
|
+
return "slides"
|
|
185
|
+
if any(host == h or host.endswith("." + h) for h in PAPER_HOSTS):
|
|
186
|
+
return "paper"
|
|
187
|
+
if any(host == h or host.endswith("." + h) for h in PODCAST_HOSTS):
|
|
188
|
+
return "podcast"
|
|
189
|
+
if any(host == h or host.endswith("." + h) for h in SOCIAL_HOSTS):
|
|
190
|
+
return "social"
|
|
191
|
+
return "docs_or_web"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def extract_companion_links(texts: list[str], extra_urls: list[str] | None = None) -> dict[str, list[str]]:
|
|
195
|
+
"""Extract, unwrap, deduplicate, and categorize companion URLs from text and structured link lists."""
|
|
196
|
+
buckets: dict[str, list[str]] = {
|
|
197
|
+
"github": [],
|
|
198
|
+
"slides": [],
|
|
199
|
+
"canvas": [],
|
|
200
|
+
"paper": [],
|
|
201
|
+
"podcast": [],
|
|
202
|
+
"docs_or_web": [],
|
|
203
|
+
"social": [],
|
|
204
|
+
}
|
|
205
|
+
seen: set[str] = set()
|
|
206
|
+
candidates: list[str] = list(extra_urls or [])
|
|
207
|
+
for blob in texts:
|
|
208
|
+
if blob:
|
|
209
|
+
candidates.extend(URL_RE.findall(blob))
|
|
210
|
+
for raw in candidates:
|
|
211
|
+
url = unwrap_youtube_redirect(raw)
|
|
212
|
+
if url in seen:
|
|
213
|
+
continue
|
|
214
|
+
bucket = classify_url(url)
|
|
215
|
+
if bucket is None:
|
|
216
|
+
continue
|
|
217
|
+
seen.add(url)
|
|
218
|
+
buckets[bucket].append(url)
|
|
219
|
+
return {k: v for k, v in buckets.items() if v}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def parse_timestamp_seconds(ts: str) -> int | None:
|
|
223
|
+
"""Convert MM:SS or HH:MM:SS into integer seconds."""
|
|
224
|
+
parts = ts.strip().split(":")
|
|
225
|
+
if len(parts) not in (2, 3) or not all(p.isdigit() for p in parts):
|
|
226
|
+
return None
|
|
227
|
+
nums = [int(p) for p in parts]
|
|
228
|
+
if len(nums) == 2:
|
|
229
|
+
return nums[0] * 60 + nums[1]
|
|
230
|
+
return nums[0] * 3600 + nums[1] * 60 + nums[2]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def parse_chapters_from_description(description: str | None) -> list[dict[str, Any]]:
|
|
234
|
+
"""Parse creator timestamp chapters from a video description."""
|
|
235
|
+
if not description:
|
|
236
|
+
return []
|
|
237
|
+
chapters: list[dict[str, Any]] = []
|
|
238
|
+
seen: set[tuple[str, str]] = set()
|
|
239
|
+
for match in CHAPTER_LINE_RE.finditer(description):
|
|
240
|
+
ts, title = match.group(1), match.group(2).strip()
|
|
241
|
+
key = (ts, title)
|
|
242
|
+
if key in seen:
|
|
243
|
+
continue
|
|
244
|
+
seen.add(key)
|
|
245
|
+
chapters.append({"time": ts, "start_seconds": parse_timestamp_seconds(ts), "title": title})
|
|
246
|
+
return chapters
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def static_thumbnail_urls(video_id: str) -> dict[str, str]:
|
|
250
|
+
"""Standard static i.ytimg.com thumbnail and keyframe preview URLs (no media stream access)."""
|
|
251
|
+
base = f"https://i.ytimg.com/vi/{video_id}"
|
|
252
|
+
return {
|
|
253
|
+
"maxres": f"{base}/maxresdefault.jpg",
|
|
254
|
+
"sd": f"{base}/sddefault.jpg",
|
|
255
|
+
"hq": f"{base}/hqdefault.jpg",
|
|
256
|
+
"keyframe_1": f"{base}/hq1.jpg",
|
|
257
|
+
"keyframe_2": f"{base}/hq2.jpg",
|
|
258
|
+
"keyframe_3": f"{base}/hq3.jpg",
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def extract_json_var(html: str, var_name: str) -> dict[str, Any] | None:
|
|
263
|
+
"""Extract an embedded JSON object assigned to a JS variable in HTML."""
|
|
264
|
+
m = re.search(r'(?:var |window\[")' + re.escape(var_name) + r'(?:"\])?\s*=\s*', html)
|
|
265
|
+
if not m:
|
|
266
|
+
return None
|
|
267
|
+
try:
|
|
268
|
+
obj, _ = json.JSONDecoder().raw_decode(html, m.end())
|
|
269
|
+
return obj if isinstance(obj, dict) else None
|
|
270
|
+
except json.JSONDecodeError:
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def yt_text(node: Any) -> str | None:
|
|
275
|
+
if not node:
|
|
276
|
+
return None
|
|
277
|
+
if isinstance(node, str):
|
|
278
|
+
return node
|
|
279
|
+
if isinstance(node, dict):
|
|
280
|
+
if "simpleText" in node:
|
|
281
|
+
return node["simpleText"]
|
|
282
|
+
if "runs" in node:
|
|
283
|
+
return "".join(r.get("text", "") for r in node.get("runs", []) if isinstance(r, dict))
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def walk_key(obj: Any, key: str):
|
|
288
|
+
if isinstance(obj, dict):
|
|
289
|
+
for k, v in obj.items():
|
|
290
|
+
if k == key:
|
|
291
|
+
yield v
|
|
292
|
+
yield from walk_key(v, key)
|
|
293
|
+
elif isinstance(obj, list):
|
|
294
|
+
for item in obj:
|
|
295
|
+
yield from walk_key(item, key)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
# --- Subcommand: feed (Tier 0) ---
|
|
299
|
+
|
|
300
|
+
def cmd_feed(args: argparse.Namespace) -> dict[str, Any]:
|
|
301
|
+
if bool(args.channel_id) == bool(args.playlist_id):
|
|
302
|
+
raise ValueError("Specify exactly one of --channel-id or --playlist-id.")
|
|
303
|
+
if args.channel_id:
|
|
304
|
+
url = f"https://www.youtube.com/feeds/videos.xml?channel_id={urllib.parse.quote(args.channel_id)}"
|
|
305
|
+
else:
|
|
306
|
+
url = f"https://www.youtube.com/feeds/videos.xml?playlist_id={urllib.parse.quote(args.playlist_id)}"
|
|
307
|
+
_, xml_text = http_get_once(url)
|
|
308
|
+
root = ET.fromstring(xml_text)
|
|
309
|
+
ns = {
|
|
310
|
+
"atom": "http://www.w3.org/2005/Atom",
|
|
311
|
+
"yt": "http://www.youtube.com/xml/schemas/2015",
|
|
312
|
+
"media": "http://search.yahoo.com/mrss/",
|
|
313
|
+
}
|
|
314
|
+
entries = []
|
|
315
|
+
for entry in root.findall("atom:entry", ns):
|
|
316
|
+
vid = entry.findtext("yt:videoId", default="", namespaces=ns)
|
|
317
|
+
title = entry.findtext("atom:title", default="", namespaces=ns)
|
|
318
|
+
published = entry.findtext("atom:published", default="", namespaces=ns)
|
|
319
|
+
updated = entry.findtext("atom:updated", default="", namespaces=ns)
|
|
320
|
+
author = entry.findtext("atom:author/atom:name", default="", namespaces=ns)
|
|
321
|
+
group = entry.find("media:group", ns)
|
|
322
|
+
description = group.findtext("media:description", default="", namespaces=ns) if group is not None else ""
|
|
323
|
+
thumb_el = group.find("media:thumbnail", ns) if group is not None else None
|
|
324
|
+
stats_el = group.find("media:community/media:statistics", ns) if group is not None else None
|
|
325
|
+
views = int(stats_el.attrib["views"]) if (stats_el is not None and "views" in stats_el.attrib) else None
|
|
326
|
+
entries.append(
|
|
327
|
+
{
|
|
328
|
+
"id": vid,
|
|
329
|
+
"url": f"https://www.youtube.com/watch?v={vid}" if vid else None,
|
|
330
|
+
"title": title,
|
|
331
|
+
"author": author,
|
|
332
|
+
"published": published,
|
|
333
|
+
"updated": updated,
|
|
334
|
+
"views": views,
|
|
335
|
+
"thumbnail": thumb_el.attrib.get("url") if thumb_el is not None else None,
|
|
336
|
+
"description": description,
|
|
337
|
+
"chapters": parse_chapters_from_description(description),
|
|
338
|
+
"companion_links": extract_companion_links([description]),
|
|
339
|
+
}
|
|
340
|
+
)
|
|
341
|
+
return {
|
|
342
|
+
"state": "ok",
|
|
343
|
+
"source_tier": "tier0_atom_feed",
|
|
344
|
+
"source_url": url,
|
|
345
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
346
|
+
"feed_title": root.findtext("atom:title", default="", namespaces=ns),
|
|
347
|
+
"entry_count": len(entries),
|
|
348
|
+
"entries": entries,
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
# --- Subcommand: oembed (Tier 0) ---
|
|
353
|
+
|
|
354
|
+
def cmd_oembed(args: argparse.Namespace) -> dict[str, Any]:
|
|
355
|
+
vid = parse_video_id(args.video)
|
|
356
|
+
watch_url = f"https://www.youtube.com/watch?v={vid}"
|
|
357
|
+
url = f"https://www.youtube.com/oembed?url={urllib.parse.quote(watch_url, safe='')}&format=json"
|
|
358
|
+
_, body = http_get_once(url)
|
|
359
|
+
data = json.loads(body)
|
|
360
|
+
return {
|
|
361
|
+
"state": "ok",
|
|
362
|
+
"source_tier": "tier0_oembed",
|
|
363
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
364
|
+
"id": vid,
|
|
365
|
+
"url": watch_url,
|
|
366
|
+
"title": data.get("title"),
|
|
367
|
+
"author_name": data.get("author_name"),
|
|
368
|
+
"author_url": data.get("author_url"),
|
|
369
|
+
"thumbnail_url": data.get("thumbnail_url"),
|
|
370
|
+
"thumbnail_width": data.get("thumbnail_width"),
|
|
371
|
+
"thumbnail_height": data.get("thumbnail_height"),
|
|
372
|
+
"static_thumbnails": static_thumbnail_urls(vid),
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# --- Subcommand: api-video & api-channel (Tier 1: Official YouTube Data API v3) ---
|
|
377
|
+
|
|
378
|
+
def require_youtube_api_key() -> str:
|
|
379
|
+
key = os.environ.get("YOUTUBE_API_KEY") or os.environ.get("GOOGLE_API_KEY")
|
|
380
|
+
if not key:
|
|
381
|
+
raise RuntimeError("Missing YOUTUBE_API_KEY (or GOOGLE_API_KEY) environment variable.")
|
|
382
|
+
return key
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def yt_api_get(endpoint: str, params: dict[str, str]) -> dict[str, Any]:
|
|
386
|
+
key = require_youtube_api_key()
|
|
387
|
+
safe_params = dict(params)
|
|
388
|
+
full_params = dict(params, key=key)
|
|
389
|
+
safe_url = f"https://www.googleapis.com/youtube/v3/{endpoint}?{urllib.parse.urlencode(safe_params)}"
|
|
390
|
+
full_url = f"https://www.googleapis.com/youtube/v3/{endpoint}?{urllib.parse.urlencode(full_params)}"
|
|
391
|
+
try:
|
|
392
|
+
_, body = http_get_once(full_url)
|
|
393
|
+
except BlockedError as exc:
|
|
394
|
+
exc.payload["source_url"] = safe_url # Never leak API key into logs or blocked.json
|
|
395
|
+
raise
|
|
396
|
+
except RuntimeError as exc:
|
|
397
|
+
raise RuntimeError(str(exc).replace(key, "<REDACTED>")) from exc
|
|
398
|
+
return json.loads(body)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def cmd_api_video(args: argparse.Namespace) -> dict[str, Any]:
|
|
402
|
+
video_ids = [parse_video_id(v) for v in args.videos]
|
|
403
|
+
items_out: list[dict[str, Any]] = []
|
|
404
|
+
for i in range(0, len(video_ids), 50):
|
|
405
|
+
batch = video_ids[i : i + 50]
|
|
406
|
+
resp = yt_api_get(
|
|
407
|
+
"videos",
|
|
408
|
+
{
|
|
409
|
+
"part": "snippet,contentDetails,statistics,topicDetails,liveStreamingDetails",
|
|
410
|
+
"id": ",".join(batch),
|
|
411
|
+
},
|
|
412
|
+
)
|
|
413
|
+
for item in resp.get("items", []):
|
|
414
|
+
vid = item["id"]
|
|
415
|
+
snippet = item.get("snippet", {})
|
|
416
|
+
details = item.get("contentDetails", {})
|
|
417
|
+
stats = item.get("statistics", {})
|
|
418
|
+
desc = snippet.get("description", "")
|
|
419
|
+
record: dict[str, Any] = {
|
|
420
|
+
"id": vid,
|
|
421
|
+
"url": f"https://www.youtube.com/watch?v={vid}",
|
|
422
|
+
"title": snippet.get("title"),
|
|
423
|
+
"channel_id": snippet.get("channelId"),
|
|
424
|
+
"channel_title": snippet.get("channelTitle"),
|
|
425
|
+
"published_at": snippet.get("publishedAt"),
|
|
426
|
+
"duration_iso8601": details.get("duration"),
|
|
427
|
+
"has_captions": details.get("caption") == "true",
|
|
428
|
+
"tags": snippet.get("tags", []),
|
|
429
|
+
"category_id": snippet.get("categoryId"),
|
|
430
|
+
"topic_categories": item.get("topicDetails", {}).get("topicCategories", []),
|
|
431
|
+
"live_streaming_details": item.get("liveStreamingDetails"),
|
|
432
|
+
"views": int(stats["viewCount"]) if "viewCount" in stats else None,
|
|
433
|
+
"likes": int(stats["likeCount"]) if "likeCount" in stats else None,
|
|
434
|
+
"comment_count": int(stats["commentCount"]) if "commentCount" in stats else None,
|
|
435
|
+
"description": desc,
|
|
436
|
+
"chapters": parse_chapters_from_description(desc),
|
|
437
|
+
"thumbnails": snippet.get("thumbnails", {}),
|
|
438
|
+
"static_thumbnails": static_thumbnail_urls(vid),
|
|
439
|
+
}
|
|
440
|
+
comment_texts: list[str] = []
|
|
441
|
+
if args.comments > 0:
|
|
442
|
+
c_resp = yt_api_get(
|
|
443
|
+
"commentThreads",
|
|
444
|
+
{
|
|
445
|
+
"part": "snippet",
|
|
446
|
+
"videoId": vid,
|
|
447
|
+
"order": "relevance",
|
|
448
|
+
"maxResults": str(min(args.comments, 100)),
|
|
449
|
+
"textFormat": "plainText",
|
|
450
|
+
},
|
|
451
|
+
)
|
|
452
|
+
comments = []
|
|
453
|
+
for c_item in c_resp.get("items", []):
|
|
454
|
+
top = c_item.get("snippet", {}).get("topLevelComment", {}).get("snippet", {})
|
|
455
|
+
text_val = top.get("textDisplay", "")
|
|
456
|
+
comment_texts.append(text_val)
|
|
457
|
+
comments.append(
|
|
458
|
+
{
|
|
459
|
+
"author": top.get("authorDisplayName"),
|
|
460
|
+
"author_channel_id": top.get("authorChannelId", {}).get("value"),
|
|
461
|
+
"is_channel_owner": top.get("authorChannelId", {}).get("value") == snippet.get("channelId"),
|
|
462
|
+
"published_at": top.get("publishedAt"),
|
|
463
|
+
"likes": top.get("likeCount"),
|
|
464
|
+
"text": text_val,
|
|
465
|
+
}
|
|
466
|
+
)
|
|
467
|
+
record["top_comments"] = comments
|
|
468
|
+
if args.captions_meta:
|
|
469
|
+
# captions.list needs OAuth 2.0; an API key alone is refused. Record that and keep the video.
|
|
470
|
+
try:
|
|
471
|
+
cap_resp = yt_api_get("captions", {"part": "snippet", "videoId": vid})
|
|
472
|
+
except (BlockedError, RuntimeError) as exc:
|
|
473
|
+
cap_resp = {}
|
|
474
|
+
status = exc.payload.get("http_status") if isinstance(exc, BlockedError) else None
|
|
475
|
+
record["caption_tracks_error"] = (
|
|
476
|
+
f"captions.list refused the API key (HTTP {status or 'error'}); it requires OAuth 2.0")
|
|
477
|
+
record["caption_tracks"] = [
|
|
478
|
+
{
|
|
479
|
+
"language": c.get("snippet", {}).get("language"),
|
|
480
|
+
"name": c.get("snippet", {}).get("name"),
|
|
481
|
+
"track_kind": c.get("snippet", {}).get("trackKind"),
|
|
482
|
+
"status": c.get("snippet", {}).get("status"),
|
|
483
|
+
}
|
|
484
|
+
for c in cap_resp.get("items", [])
|
|
485
|
+
]
|
|
486
|
+
record["companion_links"] = extract_companion_links([desc, *comment_texts])
|
|
487
|
+
items_out.append(record)
|
|
488
|
+
return {
|
|
489
|
+
"state": "ok",
|
|
490
|
+
"source_tier": "tier1_youtube_data_api_v3",
|
|
491
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
492
|
+
"requested_count": len(video_ids),
|
|
493
|
+
"returned_count": len(items_out),
|
|
494
|
+
"items": items_out,
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def cmd_api_channel(args: argparse.Namespace) -> dict[str, Any]:
|
|
499
|
+
ch_resp = yt_api_get("channels", {"part": "snippet,contentDetails,statistics", "id": args.channel_id})
|
|
500
|
+
ch_items = ch_resp.get("items", [])
|
|
501
|
+
if not ch_items:
|
|
502
|
+
raise RuntimeError(f"Channel not found: {args.channel_id}")
|
|
503
|
+
ch = ch_items[0]
|
|
504
|
+
uploads_id = ch.get("contentDetails", {}).get("relatedPlaylists", {}).get("uploads")
|
|
505
|
+
if not uploads_id:
|
|
506
|
+
raise RuntimeError(f"No uploads playlist found for channel: {args.channel_id}")
|
|
507
|
+
|
|
508
|
+
videos: list[dict[str, Any]] = []
|
|
509
|
+
page_token: str | None = None
|
|
510
|
+
while len(videos) < args.limit:
|
|
511
|
+
page_size = min(50, args.limit - len(videos))
|
|
512
|
+
params = {"part": "snippet,contentDetails", "playlistId": uploads_id, "maxResults": str(page_size)}
|
|
513
|
+
if page_token:
|
|
514
|
+
params["pageToken"] = page_token
|
|
515
|
+
pl_resp = yt_api_get("playlistItems", params)
|
|
516
|
+
for item in pl_resp.get("items", []):
|
|
517
|
+
sn = item.get("snippet", {})
|
|
518
|
+
cd = item.get("contentDetails", {})
|
|
519
|
+
vid = cd.get("videoId") or sn.get("resourceId", {}).get("videoId")
|
|
520
|
+
videos.append(
|
|
521
|
+
{
|
|
522
|
+
"id": vid,
|
|
523
|
+
"url": f"https://www.youtube.com/watch?v={vid}" if vid else None,
|
|
524
|
+
"title": sn.get("title"),
|
|
525
|
+
"published_at": cd.get("videoPublishedAt") or sn.get("publishedAt"),
|
|
526
|
+
"position": sn.get("position"),
|
|
527
|
+
}
|
|
528
|
+
)
|
|
529
|
+
page_token = pl_resp.get("nextPageToken")
|
|
530
|
+
if not page_token:
|
|
531
|
+
break
|
|
532
|
+
return {
|
|
533
|
+
"state": "ok",
|
|
534
|
+
"source_tier": "tier1_youtube_data_api_v3_channel",
|
|
535
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
536
|
+
"channel_id": args.channel_id,
|
|
537
|
+
"channel_title": ch.get("snippet", {}).get("title"),
|
|
538
|
+
"uploads_playlist_id": uploads_id,
|
|
539
|
+
"reported_video_count": ch.get("statistics", {}).get("videoCount"),
|
|
540
|
+
"returned_count": len(videos),
|
|
541
|
+
"videos": videos,
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
# --- Subcommand: inspect (Tier 2: Single-GET Watch Page, zero retries, zero media playback) ---
|
|
546
|
+
|
|
547
|
+
def parse_watch_html(video_id: str, html: str, source_url: str) -> dict[str, Any]:
|
|
548
|
+
"""Parse rich metadata, chapters+thumbs, heatmap peaks, caption inventory, and links from one watch-page HTML."""
|
|
549
|
+
initial_data = extract_json_var(html, "ytInitialData")
|
|
550
|
+
player_resp = extract_json_var(html, "ytInitialPlayerResponse") or {}
|
|
551
|
+
|
|
552
|
+
playability = player_resp.get("playabilityStatus", {})
|
|
553
|
+
playability_status = playability.get("status")
|
|
554
|
+
playability_reason = playability.get("reason") or ""
|
|
555
|
+
|
|
556
|
+
if not initial_data:
|
|
557
|
+
if "LOGIN_REQUIRED" in html or "Sign in to confirm" in html:
|
|
558
|
+
raise BlockedError(
|
|
559
|
+
source_url=source_url,
|
|
560
|
+
status=200,
|
|
561
|
+
reason="bot_or_login_wall",
|
|
562
|
+
evidence="Watch page omitted ytInitialData and indicated a login/bot check.",
|
|
563
|
+
)
|
|
564
|
+
raise RuntimeError("Watch page HTML did not contain ytInitialData.")
|
|
565
|
+
|
|
566
|
+
results_contents = (
|
|
567
|
+
initial_data.get("contents", {})
|
|
568
|
+
.get("twoColumnWatchNextResults", {})
|
|
569
|
+
.get("results", {})
|
|
570
|
+
.get("results", {})
|
|
571
|
+
.get("contents", [])
|
|
572
|
+
)
|
|
573
|
+
prim = next((c["videoPrimaryInfoRenderer"] for c in results_contents if "videoPrimaryInfoRenderer" in c), {})
|
|
574
|
+
sec = next((c["videoSecondaryInfoRenderer"] for c in results_contents if "videoSecondaryInfoRenderer" in c), {})
|
|
575
|
+
|
|
576
|
+
# Description + structured redirect URLs
|
|
577
|
+
desc_obj = sec.get("attributedDescription", {})
|
|
578
|
+
description = desc_obj.get("content") or yt_text(sec.get("description")) or ""
|
|
579
|
+
extra_urls: list[str] = []
|
|
580
|
+
for cmd in walk_key(desc_obj, "urlEndpoint"):
|
|
581
|
+
if isinstance(cmd, dict) and cmd.get("url"):
|
|
582
|
+
u = cmd["url"]
|
|
583
|
+
if u.startswith("/redirect"):
|
|
584
|
+
u = "https://www.youtube.com" + u
|
|
585
|
+
extra_urls.append(u)
|
|
586
|
+
|
|
587
|
+
# Chapters + per-chapter thumbnails (i.ytimg.com)
|
|
588
|
+
chapters: list[dict[str, Any]] = []
|
|
589
|
+
seen_ch: set[tuple[str | None, str | None]] = set()
|
|
590
|
+
for mm in walk_key(initial_data, "macroMarkersListItemRenderer"):
|
|
591
|
+
if not isinstance(mm, dict):
|
|
592
|
+
continue
|
|
593
|
+
t_str = yt_text(mm.get("timeDescription"))
|
|
594
|
+
title = yt_text(mm.get("title"))
|
|
595
|
+
key = (t_str, title)
|
|
596
|
+
if not t_str or key in seen_ch:
|
|
597
|
+
continue
|
|
598
|
+
seen_ch.add(key)
|
|
599
|
+
thumbs = mm.get("thumbnail", {}).get("thumbnails", [])
|
|
600
|
+
thumb_url = thumbs[-1].get("url") if thumbs else None
|
|
601
|
+
chapters.append(
|
|
602
|
+
{
|
|
603
|
+
"time": t_str,
|
|
604
|
+
"start_seconds": parse_timestamp_seconds(t_str),
|
|
605
|
+
"title": title,
|
|
606
|
+
"thumbnail": thumb_url,
|
|
607
|
+
}
|
|
608
|
+
)
|
|
609
|
+
if not chapters:
|
|
610
|
+
chapters = parse_chapters_from_description(description)
|
|
611
|
+
|
|
612
|
+
# Most Replayed heatmap peaks (high-signal timestamps for diagrams/code/key points)
|
|
613
|
+
heatmap_segments: list[dict[str, Any]] = []
|
|
614
|
+
for hm in walk_key(initial_data, "heatMarkerRenderer"):
|
|
615
|
+
if not isinstance(hm, dict):
|
|
616
|
+
continue
|
|
617
|
+
score = hm.get("intensityScoreNormalized")
|
|
618
|
+
start_ms = hm.get("timeRangeStartMillis")
|
|
619
|
+
dur_ms = hm.get("markerDurationMillis")
|
|
620
|
+
if score is not None and start_ms is not None:
|
|
621
|
+
heatmap_segments.append(
|
|
622
|
+
{
|
|
623
|
+
"start_seconds": round(float(start_ms) / 1000.0, 1),
|
|
624
|
+
"duration_seconds": round(float(dur_ms or 0) / 1000.0, 1),
|
|
625
|
+
"intensity": round(float(score), 4),
|
|
626
|
+
}
|
|
627
|
+
)
|
|
628
|
+
heatmap_peaks = sorted(
|
|
629
|
+
[s for s in heatmap_segments if s["intensity"] >= 0.55],
|
|
630
|
+
key=lambda x: x["intensity"],
|
|
631
|
+
reverse=True,
|
|
632
|
+
)[:8]
|
|
633
|
+
|
|
634
|
+
# Microformat & videoDetails (exact ISO dates, length, tags, caption inventory)
|
|
635
|
+
micro = player_resp.get("microformat", {}).get("playerMicroformatRenderer", {})
|
|
636
|
+
vdetails = player_resp.get("videoDetails", {})
|
|
637
|
+
owner = sec.get("owner", {}).get("videoOwnerRenderer", {})
|
|
638
|
+
owner_name = yt_text(owner.get("title"))
|
|
639
|
+
owner_channel_id = (
|
|
640
|
+
owner.get("navigationEndpoint", {}).get("browseEndpoint", {}).get("browseId")
|
|
641
|
+
)
|
|
642
|
+
caption_tracks = []
|
|
643
|
+
for tr in (
|
|
644
|
+
player_resp.get("captions", {})
|
|
645
|
+
.get("playerCaptionsTracklistRenderer", {})
|
|
646
|
+
.get("captionTracks", [])
|
|
647
|
+
):
|
|
648
|
+
caption_tracks.append(
|
|
649
|
+
{
|
|
650
|
+
"language_code": tr.get("languageCode"),
|
|
651
|
+
"name": yt_text(tr.get("name")),
|
|
652
|
+
"kind": tr.get("kind") or "manual",
|
|
653
|
+
"is_translatable": bool(tr.get("isTranslatable")),
|
|
654
|
+
}
|
|
655
|
+
)
|
|
656
|
+
if caption_tracks:
|
|
657
|
+
caption_tracks_status = "present"
|
|
658
|
+
elif playability_status and playability_status != "OK":
|
|
659
|
+
caption_tracks_status = f"unknown_player_{playability_status.lower()}"
|
|
660
|
+
elif not player_resp:
|
|
661
|
+
caption_tracks_status = "unknown_no_player_response"
|
|
662
|
+
else:
|
|
663
|
+
caption_tracks_status = "absent"
|
|
664
|
+
|
|
665
|
+
# Likes fallback: modern segmentedLikeDislikeButtonViewModel or legacy likeCountIfLikedNumber
|
|
666
|
+
likes_val = next(walk_key(prim, "likeCountIfLikedNumber"), None)
|
|
667
|
+
if likes_val is None:
|
|
668
|
+
for like_vm in walk_key(prim, "likeButtonViewModel"):
|
|
669
|
+
if isinstance(like_vm, dict):
|
|
670
|
+
toggles = list(walk_key(like_vm, "defaultButtonViewModel"))
|
|
671
|
+
for btn in toggles:
|
|
672
|
+
if isinstance(btn, dict):
|
|
673
|
+
txt = btn.get("buttonViewModel", {}).get("title")
|
|
674
|
+
if txt:
|
|
675
|
+
likes_val = txt
|
|
676
|
+
break
|
|
677
|
+
if likes_val is not None:
|
|
678
|
+
break
|
|
679
|
+
|
|
680
|
+
# Build suggested Gemini video_metadata windows from top heatmap peaks, falling back to chapters
|
|
681
|
+
length_s = int(micro["lengthSeconds"]) if str(micro.get("lengthSeconds", "")).isdigit() else (
|
|
682
|
+
int(vdetails["lengthSeconds"]) if str(vdetails.get("lengthSeconds", "")).isdigit() else None
|
|
683
|
+
)
|
|
684
|
+
suggested_windows: list[dict[str, Any]] = []
|
|
685
|
+
for peak in heatmap_peaks[:4]:
|
|
686
|
+
start_s = max(0, int(peak["start_seconds"]) - 15)
|
|
687
|
+
end_s = int(peak["start_seconds"] + max(peak["duration_seconds"], 30)) + 15
|
|
688
|
+
if length_s is not None:
|
|
689
|
+
end_s = min(length_s, end_s)
|
|
690
|
+
suggested_windows.append(
|
|
691
|
+
{
|
|
692
|
+
"start_offset": f"{start_s}s",
|
|
693
|
+
"end_offset": f"{end_s}s",
|
|
694
|
+
"fps": 1.0,
|
|
695
|
+
"reason": f"Most Replayed peak (intensity={peak['intensity']})",
|
|
696
|
+
}
|
|
697
|
+
)
|
|
698
|
+
if not suggested_windows and chapters:
|
|
699
|
+
for idx, ch in enumerate(chapters):
|
|
700
|
+
st = ch.get("start_seconds")
|
|
701
|
+
if st is None:
|
|
702
|
+
continue
|
|
703
|
+
next_st = chapters[idx + 1].get("start_seconds") if idx + 1 < len(chapters) else length_s
|
|
704
|
+
window: dict[str, Any] = {
|
|
705
|
+
"start_offset": f"{st}s",
|
|
706
|
+
"fps": 0.5,
|
|
707
|
+
"reason": f"Chapter: {ch.get('title') or ch.get('time')}",
|
|
708
|
+
}
|
|
709
|
+
if next_st is not None and next_st > st:
|
|
710
|
+
window["end_offset"] = f"{next_st}s"
|
|
711
|
+
suggested_windows.append(window)
|
|
712
|
+
|
|
713
|
+
resolved_channel_id = micro.get("externalChannelId") or vdetails.get("channelId") or owner_channel_id
|
|
714
|
+
|
|
715
|
+
return {
|
|
716
|
+
"state": "ok",
|
|
717
|
+
"source_tier": "tier2_watch_page_single_get",
|
|
718
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
719
|
+
"id": video_id,
|
|
720
|
+
"url": f"https://www.youtube.com/watch?v={video_id}",
|
|
721
|
+
"title": yt_text(prim.get("title")) or vdetails.get("title") or yt_text(micro.get("title")),
|
|
722
|
+
"channel_name": micro.get("ownerChannelName") or vdetails.get("author") or owner_name,
|
|
723
|
+
"channel_id": resolved_channel_id,
|
|
724
|
+
"channel_feed_url": (
|
|
725
|
+
f"https://www.youtube.com/feeds/videos.xml?channel_id={resolved_channel_id}"
|
|
726
|
+
if resolved_channel_id
|
|
727
|
+
else None
|
|
728
|
+
),
|
|
729
|
+
"date_text": yt_text(prim.get("dateText")),
|
|
730
|
+
"publish_date": micro.get("publishDate"),
|
|
731
|
+
"upload_date": micro.get("uploadDate"),
|
|
732
|
+
"length_seconds": length_s,
|
|
733
|
+
"category": micro.get("category"),
|
|
734
|
+
"is_live_content": micro.get("isLiveContent", vdetails.get("isLiveContent")),
|
|
735
|
+
"is_unlisted": micro.get("isUnlisted"),
|
|
736
|
+
"views_text": yt_text(prim.get("viewCount", {}).get("videoViewCountRenderer", {}).get("viewCount")),
|
|
737
|
+
"likes": likes_val,
|
|
738
|
+
"player_playability": {"status": playability_status, "reason": playability_reason} if playability_status else None,
|
|
739
|
+
"keywords": vdetails.get("keywords", []),
|
|
740
|
+
"description": description,
|
|
741
|
+
"chapters": chapters,
|
|
742
|
+
"heatmap_segment_count": len(heatmap_segments),
|
|
743
|
+
"heatmap_peaks": heatmap_peaks,
|
|
744
|
+
"caption_tracks_status": caption_tracks_status,
|
|
745
|
+
"caption_tracks": caption_tracks,
|
|
746
|
+
"has_storyboards": bool(player_resp.get("storyboards")),
|
|
747
|
+
"static_thumbnails": static_thumbnail_urls(video_id),
|
|
748
|
+
"companion_links": extract_companion_links([description], extra_urls=extra_urls),
|
|
749
|
+
"suggested_gemini_windows": suggested_windows,
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def cmd_inspect(args: argparse.Namespace) -> dict[str, Any]:
|
|
754
|
+
vid = parse_video_id(args.video)
|
|
755
|
+
url = f"https://www.youtube.com/watch?v={vid}&hl=en"
|
|
756
|
+
_, html = http_get_once(url, headers={"Cookie": "SOCS=CAI"})
|
|
757
|
+
return parse_watch_html(vid, html, url)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
# --- Subcommand: gemini (Tier 4: Official Gemini API Multimodal Video Understanding) ---
|
|
761
|
+
|
|
762
|
+
DEFAULT_GEMINI_PROMPT = (
|
|
763
|
+
"Analyze this public YouTube video segment as an engineering reference. Return structured Markdown with:\n"
|
|
764
|
+
"1. Timestamped key claims and concrete workflows/commands spoken or shown on screen.\n"
|
|
765
|
+
"2. On-screen text: slide titles, architecture diagram labels/arrows, code snippets, terminal commands, and URLs visible in browser bars or slides.\n"
|
|
766
|
+
"3. Gaps or ambiguities where text was too small or cut off.\n"
|
|
767
|
+
"Cite MM:SS timestamps for every item. Distinguish spoken assertions from text visibly shown on screen."
|
|
768
|
+
)
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def cmd_gemini(args: argparse.Namespace) -> dict[str, Any]:
|
|
772
|
+
vid = parse_video_id(args.video)
|
|
773
|
+
watch_url = f"https://www.youtube.com/watch?v={vid}"
|
|
774
|
+
video_meta: dict[str, Any] = {}
|
|
775
|
+
if args.start:
|
|
776
|
+
video_meta["start_offset"] = args.start if args.start.endswith("s") else f"{args.start}s"
|
|
777
|
+
if args.end:
|
|
778
|
+
video_meta["end_offset"] = args.end if args.end.endswith("s") else f"{args.end}s"
|
|
779
|
+
if args.fps is not None:
|
|
780
|
+
video_meta["fps"] = args.fps
|
|
781
|
+
|
|
782
|
+
prompt_text = args.prompt or DEFAULT_GEMINI_PROMPT
|
|
783
|
+
if args.dry_run:
|
|
784
|
+
return {
|
|
785
|
+
"state": "dry_run",
|
|
786
|
+
"source_tier": "tier4_gemini_multimodal_youtube",
|
|
787
|
+
"model": args.model,
|
|
788
|
+
"file_uri": watch_url,
|
|
789
|
+
"video_metadata": video_meta or None,
|
|
790
|
+
"prompt": prompt_text,
|
|
791
|
+
"api_key_present": bool(os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")),
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
|
|
795
|
+
if not api_key:
|
|
796
|
+
raise RuntimeError("Missing GEMINI_API_KEY (or GOOGLE_API_KEY) environment variable.")
|
|
797
|
+
try:
|
|
798
|
+
from google import genai
|
|
799
|
+
from google.genai import types
|
|
800
|
+
except ImportError as exc:
|
|
801
|
+
raise RuntimeError("google-genai is not installed. Run: pip install google-genai") from exc
|
|
802
|
+
|
|
803
|
+
client = genai.Client(api_key=api_key)
|
|
804
|
+
part_kwargs: dict[str, Any] = {"file_data": types.FileData(file_uri=watch_url)}
|
|
805
|
+
if video_meta:
|
|
806
|
+
part_kwargs["video_metadata"] = types.VideoMetadata(**video_meta)
|
|
807
|
+
|
|
808
|
+
try:
|
|
809
|
+
response = client.models.generate_content(
|
|
810
|
+
model=args.model,
|
|
811
|
+
contents=types.Content(
|
|
812
|
+
parts=[
|
|
813
|
+
types.Part(**part_kwargs),
|
|
814
|
+
types.Part(text=prompt_text),
|
|
815
|
+
]
|
|
816
|
+
),
|
|
817
|
+
)
|
|
818
|
+
except Exception as exc:
|
|
819
|
+
msg = str(exc)
|
|
820
|
+
if any(code in msg for code in ("403", "429", "RESOURCE_EXHAUSTED", "PERMISSION_DENIED")):
|
|
821
|
+
raise BlockedError(
|
|
822
|
+
source_url=watch_url,
|
|
823
|
+
status=429 if ("429" in msg or "RESOURCE_EXHAUSTED" in msg) else 403,
|
|
824
|
+
reason="gemini_api_blocked_or_quota",
|
|
825
|
+
evidence=msg[:400],
|
|
826
|
+
) from exc
|
|
827
|
+
raise
|
|
828
|
+
|
|
829
|
+
return {
|
|
830
|
+
"state": "ok",
|
|
831
|
+
"source_tier": "tier4_gemini_multimodal_youtube",
|
|
832
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
833
|
+
"id": vid,
|
|
834
|
+
"url": watch_url,
|
|
835
|
+
"model": args.model,
|
|
836
|
+
"video_metadata": video_meta or None,
|
|
837
|
+
"text": response.text,
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
# --- Subcommand: links (Tier 3 offline companion-link miner) ---
|
|
842
|
+
|
|
843
|
+
def cmd_links(args: argparse.Namespace) -> dict[str, Any]:
|
|
844
|
+
texts: list[str] = []
|
|
845
|
+
for p_str in args.files:
|
|
846
|
+
path = Path(p_str)
|
|
847
|
+
raw = path.read_text(encoding="utf-8", errors="replace")
|
|
848
|
+
texts.append(raw)
|
|
849
|
+
links = extract_companion_links(texts)
|
|
850
|
+
return {
|
|
851
|
+
"state": "ok",
|
|
852
|
+
"source_tier": "tier3_companion_links_offline",
|
|
853
|
+
"files_scanned": len(args.files),
|
|
854
|
+
"total_links": sum(len(v) for v in links.values()),
|
|
855
|
+
"companion_links": links,
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
# --- Subcommand: channel-tabs (Tier 2: Tab-verified public initial HTML channel inventory) ---
|
|
860
|
+
|
|
861
|
+
def normalize_channel_base_url(raw: str) -> str:
|
|
862
|
+
"""Normalize a channel ID, @handle, or URL into https://www.youtube.com/<base>."""
|
|
863
|
+
s = raw.strip().rstrip("/")
|
|
864
|
+
if s.startswith("http://") or s.startswith("https://"):
|
|
865
|
+
parsed = urllib.parse.urlparse(s)
|
|
866
|
+
parts = [p for p in parsed.path.split("/") if p]
|
|
867
|
+
if parts and parts[-1].lower() in ("videos", "shorts", "streams", "featured", "playlists", "community", "about"):
|
|
868
|
+
parts = parts[:-1]
|
|
869
|
+
if not parts:
|
|
870
|
+
raise ValueError(f"Could not resolve channel path from URL: {raw}")
|
|
871
|
+
return f"https://www.youtube.com/{'/'.join(parts)}"
|
|
872
|
+
if s.startswith("@"):
|
|
873
|
+
return f"https://www.youtube.com/{s}"
|
|
874
|
+
if re.match(r"^UC[A-Za-z0-9_-]{20,}$", s):
|
|
875
|
+
return f"https://www.youtube.com/channel/{s}"
|
|
876
|
+
raise ValueError(f"Provide a UC... channel ID, @handle, or YouTube channel URL; got: {raw}")
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def parse_channel_tab_html(html: str, requested_tab: str, source_url: str) -> dict[str, Any]:
|
|
880
|
+
"""Parse initial items from a YouTube channel tab HTML and verify which tab was actually selected."""
|
|
881
|
+
initial_data = extract_json_var(html, "ytInitialData")
|
|
882
|
+
if not initial_data:
|
|
883
|
+
if "LOGIN_REQUIRED" in html or "Sign in to confirm" in html:
|
|
884
|
+
raise BlockedError(
|
|
885
|
+
source_url=source_url,
|
|
886
|
+
status=200,
|
|
887
|
+
reason="bot_or_login_wall",
|
|
888
|
+
evidence=f"Channel tab /{requested_tab} omitted ytInitialData and indicated a login/bot check.",
|
|
889
|
+
)
|
|
890
|
+
raise RuntimeError(f"Channel tab /{requested_tab} HTML did not contain ytInitialData.")
|
|
891
|
+
|
|
892
|
+
tabs = (
|
|
893
|
+
initial_data.get("contents", {})
|
|
894
|
+
.get("twoColumnBrowseResultsRenderer", {})
|
|
895
|
+
.get("tabs", [])
|
|
896
|
+
)
|
|
897
|
+
selected_tab = None
|
|
898
|
+
for t in tabs:
|
|
899
|
+
tr = t.get("tabRenderer")
|
|
900
|
+
if isinstance(tr, dict) and tr.get("selected"):
|
|
901
|
+
selected_tab = tr
|
|
902
|
+
break
|
|
903
|
+
|
|
904
|
+
selected_title = selected_tab.get("title") if selected_tab else None
|
|
905
|
+
selected_url = (
|
|
906
|
+
selected_tab.get("endpoint", {})
|
|
907
|
+
.get("commandMetadata", {})
|
|
908
|
+
.get("webCommandMetadata", {})
|
|
909
|
+
.get("url", "")
|
|
910
|
+
if selected_tab
|
|
911
|
+
else ""
|
|
912
|
+
)
|
|
913
|
+
expected_suffix = {"videos": "/videos", "shorts": "/shorts", "streams": "/streams"}.get(
|
|
914
|
+
requested_tab, f"/{requested_tab}"
|
|
915
|
+
)
|
|
916
|
+
tab_verified = bool(
|
|
917
|
+
selected_tab
|
|
918
|
+
and (
|
|
919
|
+
selected_url.rstrip("/").lower().endswith(expected_suffix)
|
|
920
|
+
or (selected_title or "").strip().lower() in (requested_tab, "live" if requested_tab == "streams" else requested_tab)
|
|
921
|
+
)
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
tab_content = selected_tab.get("content", {}) if selected_tab else {}
|
|
925
|
+
has_continuation = any(True for _ in walk_key(tab_content, "continuationItemRenderer"))
|
|
926
|
+
|
|
927
|
+
items: list[dict[str, Any]] = []
|
|
928
|
+
seen_ids: set[str] = set()
|
|
929
|
+
|
|
930
|
+
# Modern 2026 channel grid items (lockupViewModel)
|
|
931
|
+
for lv in walk_key(tab_content, "lockupViewModel"):
|
|
932
|
+
if not isinstance(lv, dict):
|
|
933
|
+
continue
|
|
934
|
+
vid = lv.get("contentId")
|
|
935
|
+
if not vid or not VIDEO_ID_RE.match(str(vid)) or vid in seen_ids:
|
|
936
|
+
continue
|
|
937
|
+
seen_ids.add(vid)
|
|
938
|
+
lmeta = lv.get("metadata", {}).get("lockupMetadataViewModel", {})
|
|
939
|
+
title = lmeta.get("title", {}).get("content")
|
|
940
|
+
duration_text = None
|
|
941
|
+
badge_styles: list[str] = []
|
|
942
|
+
for badge in walk_key(lv.get("contentImage", {}), "thumbnailBadgeViewModel"):
|
|
943
|
+
if isinstance(badge, dict):
|
|
944
|
+
bs = str(badge.get("badgeStyle") or "")
|
|
945
|
+
badge_styles.append(bs.upper())
|
|
946
|
+
txt = badge.get("text")
|
|
947
|
+
if txt and re.match(r"^(?:\d{1,2}:)?\d{1,2}:\d{2}$", str(txt).strip()):
|
|
948
|
+
duration_text = str(txt).strip()
|
|
949
|
+
elif txt and str(txt).strip().upper() in ("LIVE", "UPCOMING", "PREMIERE"):
|
|
950
|
+
badge_styles.append(str(txt).strip().upper())
|
|
951
|
+
|
|
952
|
+
views_text = None
|
|
953
|
+
published_time_text = None
|
|
954
|
+
meta_texts: list[str] = []
|
|
955
|
+
for row in lmeta.get("metadata", {}).get("contentMetadataViewModel", {}).get("metadataRows", []):
|
|
956
|
+
for part in row.get("metadataParts", []):
|
|
957
|
+
ptxt = part.get("text", {}).get("content")
|
|
958
|
+
alabel = part.get("accessibilityLabel") or ""
|
|
959
|
+
if ptxt:
|
|
960
|
+
meta_texts.append(ptxt)
|
|
961
|
+
if "view" in alabel.lower() or "view" in ptxt.lower() or "watching" in ptxt.lower():
|
|
962
|
+
views_text = views_text or ptxt
|
|
963
|
+
elif "ago" in alabel.lower() or "ago" in ptxt.lower() or "scheduled" in ptxt.lower() or "streamed" in ptxt.lower():
|
|
964
|
+
published_time_text = published_time_text or ptxt
|
|
965
|
+
if views_text is None and meta_texts:
|
|
966
|
+
views_text = meta_texts[0]
|
|
967
|
+
if published_time_text is None and len(meta_texts) > 1:
|
|
968
|
+
published_time_text = meta_texts[1]
|
|
969
|
+
|
|
970
|
+
joined_badges = " ".join(badge_styles)
|
|
971
|
+
joined_meta = " ".join(meta_texts).upper()
|
|
972
|
+
if "UPCOMING" in joined_badges or "PREMIERE" in joined_badges or "SCHEDULED" in joined_meta:
|
|
973
|
+
status = "upcoming"
|
|
974
|
+
elif "LIVE" in joined_badges or "WATCHING" in joined_meta:
|
|
975
|
+
status = "live"
|
|
976
|
+
elif requested_tab == "shorts":
|
|
977
|
+
status = "short"
|
|
978
|
+
else:
|
|
979
|
+
status = "regular"
|
|
980
|
+
|
|
981
|
+
items.append(
|
|
982
|
+
{
|
|
983
|
+
"id": vid,
|
|
984
|
+
"url": f"https://www.youtube.com/shorts/{vid}" if status == "short" else f"https://www.youtube.com/watch?v={vid}",
|
|
985
|
+
"tab": requested_tab,
|
|
986
|
+
"title": title,
|
|
987
|
+
"published_time_text": published_time_text,
|
|
988
|
+
"duration_text": duration_text,
|
|
989
|
+
"views_text": views_text,
|
|
990
|
+
"status": status,
|
|
991
|
+
}
|
|
992
|
+
)
|
|
993
|
+
|
|
994
|
+
# Standard videos / streams (videoRenderer)
|
|
995
|
+
for vr in walk_key(tab_content, "videoRenderer"):
|
|
996
|
+
if not isinstance(vr, dict):
|
|
997
|
+
continue
|
|
998
|
+
vid = vr.get("videoId")
|
|
999
|
+
if not vid or vid in seen_ids:
|
|
1000
|
+
continue
|
|
1001
|
+
seen_ids.add(vid)
|
|
1002
|
+
overlays_text = " ".join(
|
|
1003
|
+
str(s) for s in walk_key(vr.get("thumbnailOverlays", []), "style")
|
|
1004
|
+
).upper()
|
|
1005
|
+
badge_labels = " ".join(
|
|
1006
|
+
str(yt_text(b.get("metadataBadgeRenderer", {}).get("label")) or b.get("metadataBadgeRenderer", {}).get("style") or "")
|
|
1007
|
+
for b in vr.get("badges", [])
|
|
1008
|
+
if isinstance(b, dict)
|
|
1009
|
+
).upper()
|
|
1010
|
+
if vr.get("upcomingEventData") or "UPCOMING" in overlays_text or "UPCOMING" in badge_labels:
|
|
1011
|
+
status = "upcoming"
|
|
1012
|
+
elif "LIVE" in overlays_text or "BADGE_STYLE_TYPE_LIVE_NOW" in badge_labels:
|
|
1013
|
+
status = "live"
|
|
1014
|
+
else:
|
|
1015
|
+
status = "regular"
|
|
1016
|
+
items.append(
|
|
1017
|
+
{
|
|
1018
|
+
"id": vid,
|
|
1019
|
+
"url": f"https://www.youtube.com/watch?v={vid}",
|
|
1020
|
+
"tab": requested_tab,
|
|
1021
|
+
"title": yt_text(vr.get("title")),
|
|
1022
|
+
"published_time_text": yt_text(vr.get("publishedTimeText")),
|
|
1023
|
+
"duration_text": yt_text(vr.get("lengthText")),
|
|
1024
|
+
"views_text": yt_text(vr.get("viewCountText")) or yt_text(vr.get("shortViewCountText")),
|
|
1025
|
+
"status": status,
|
|
1026
|
+
}
|
|
1027
|
+
)
|
|
1028
|
+
|
|
1029
|
+
# Shorts (shortsLockupViewModel and legacy reelItemRenderer)
|
|
1030
|
+
for sm in walk_key(tab_content, "shortsLockupViewModel"):
|
|
1031
|
+
if not isinstance(sm, dict):
|
|
1032
|
+
continue
|
|
1033
|
+
vid = (
|
|
1034
|
+
sm.get("onTap", {})
|
|
1035
|
+
.get("innertubeCommand", {})
|
|
1036
|
+
.get("reelWatchEndpoint", {})
|
|
1037
|
+
.get("videoId")
|
|
1038
|
+
)
|
|
1039
|
+
if not vid or vid in seen_ids:
|
|
1040
|
+
continue
|
|
1041
|
+
seen_ids.add(vid)
|
|
1042
|
+
ov = sm.get("overlayMetadata", {})
|
|
1043
|
+
items.append(
|
|
1044
|
+
{
|
|
1045
|
+
"id": vid,
|
|
1046
|
+
"url": f"https://www.youtube.com/shorts/{vid}",
|
|
1047
|
+
"tab": requested_tab,
|
|
1048
|
+
"title": ov.get("primaryText", {}).get("content") or sm.get("accessibilityText"),
|
|
1049
|
+
"published_time_text": None,
|
|
1050
|
+
"duration_text": None,
|
|
1051
|
+
"views_text": ov.get("secondaryText", {}).get("content"),
|
|
1052
|
+
"status": "short",
|
|
1053
|
+
}
|
|
1054
|
+
)
|
|
1055
|
+
for rr in walk_key(tab_content, "reelItemRenderer"):
|
|
1056
|
+
if not isinstance(rr, dict):
|
|
1057
|
+
continue
|
|
1058
|
+
vid = rr.get("videoId")
|
|
1059
|
+
if not vid or vid in seen_ids:
|
|
1060
|
+
continue
|
|
1061
|
+
seen_ids.add(vid)
|
|
1062
|
+
items.append(
|
|
1063
|
+
{
|
|
1064
|
+
"id": vid,
|
|
1065
|
+
"url": f"https://www.youtube.com/shorts/{vid}",
|
|
1066
|
+
"tab": requested_tab,
|
|
1067
|
+
"title": yt_text(rr.get("headline")),
|
|
1068
|
+
"published_time_text": None,
|
|
1069
|
+
"duration_text": None,
|
|
1070
|
+
"views_text": yt_text(rr.get("viewCountText")),
|
|
1071
|
+
"status": "short",
|
|
1072
|
+
}
|
|
1073
|
+
)
|
|
1074
|
+
|
|
1075
|
+
ch_meta = initial_data.get("metadata", {}).get("channelMetadataRenderer", {})
|
|
1076
|
+
return {
|
|
1077
|
+
"requested_tab": requested_tab,
|
|
1078
|
+
"source_url": source_url,
|
|
1079
|
+
"channel_id": ch_meta.get("externalId"),
|
|
1080
|
+
"channel_title": ch_meta.get("title"),
|
|
1081
|
+
"selected_tab_title": selected_title,
|
|
1082
|
+
"selected_tab_url": selected_url,
|
|
1083
|
+
"tab_verified": tab_verified,
|
|
1084
|
+
"has_continuation": has_continuation,
|
|
1085
|
+
"item_count": len(items),
|
|
1086
|
+
"items": items if tab_verified else [],
|
|
1087
|
+
"unverified_fallback_count": 0 if tab_verified else len(items),
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
|
|
1091
|
+
def cmd_channel_tabs(args: argparse.Namespace) -> dict[str, Any]:
|
|
1092
|
+
base = normalize_channel_base_url(args.channel)
|
|
1093
|
+
tabs_req = [t.strip().lower() for t in args.tabs.split(",") if t.strip()]
|
|
1094
|
+
tab_results: dict[str, Any] = {}
|
|
1095
|
+
all_ids: list[str] = []
|
|
1096
|
+
seen: set[str] = set()
|
|
1097
|
+
channel_id = None
|
|
1098
|
+
channel_title = None
|
|
1099
|
+
for idx, tab in enumerate(tabs_req):
|
|
1100
|
+
if idx > 0 and args.delay > 0:
|
|
1101
|
+
time.sleep(args.delay)
|
|
1102
|
+
url = f"{base}/{tab}?hl=en"
|
|
1103
|
+
_, html = http_get_once(url, headers={"Cookie": "SOCS=CAI"})
|
|
1104
|
+
res = parse_channel_tab_html(html, tab, url)
|
|
1105
|
+
tab_results[tab] = res
|
|
1106
|
+
channel_id = channel_id or res.get("channel_id")
|
|
1107
|
+
channel_title = channel_title or res.get("channel_title")
|
|
1108
|
+
if res["tab_verified"]:
|
|
1109
|
+
for it in res["items"]:
|
|
1110
|
+
if it["id"] not in seen:
|
|
1111
|
+
seen.add(it["id"])
|
|
1112
|
+
all_ids.append(it["id"])
|
|
1113
|
+
return {
|
|
1114
|
+
"state": "ok",
|
|
1115
|
+
"source_tier": "tier2_channel_tabs_initial_html",
|
|
1116
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1117
|
+
"channel_base_url": base,
|
|
1118
|
+
"channel_id": channel_id,
|
|
1119
|
+
"channel_title": channel_title,
|
|
1120
|
+
"channel_feed_url": (
|
|
1121
|
+
f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}" if channel_id else None
|
|
1122
|
+
),
|
|
1123
|
+
"tabs": tab_results,
|
|
1124
|
+
"unique_verified_count": len(all_ids),
|
|
1125
|
+
"all_video_ids": all_ids,
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
|
|
1129
|
+
# --- Subcommand: batch (Resumable paced JSONL collector with instant blocked.json halt) ---
|
|
1130
|
+
|
|
1131
|
+
def load_video_ids_from_input(path: Path) -> list[str]:
|
|
1132
|
+
"""Load deduplicated video IDs from JSON list, yt_enrich outputs, or newline text."""
|
|
1133
|
+
raw = path.read_text(encoding="utf-8").strip()
|
|
1134
|
+
candidates: list[str] = []
|
|
1135
|
+
if raw.startswith("{") or raw.startswith("["):
|
|
1136
|
+
data = json.loads(raw)
|
|
1137
|
+
if isinstance(data, list):
|
|
1138
|
+
for el in data:
|
|
1139
|
+
if isinstance(el, str):
|
|
1140
|
+
candidates.append(el)
|
|
1141
|
+
elif isinstance(el, dict) and el.get("id"):
|
|
1142
|
+
candidates.append(str(el["id"]))
|
|
1143
|
+
elif isinstance(data, dict):
|
|
1144
|
+
if isinstance(data.get("all_video_ids"), list):
|
|
1145
|
+
candidates.extend(str(x) for x in data["all_video_ids"])
|
|
1146
|
+
elif isinstance(data.get("entries"), list):
|
|
1147
|
+
candidates.extend(str(x["id"]) for x in data["entries"] if isinstance(x, dict) and x.get("id"))
|
|
1148
|
+
elif isinstance(data.get("videos"), list):
|
|
1149
|
+
candidates.extend(str(x["id"]) for x in data["videos"] if isinstance(x, dict) and x.get("id"))
|
|
1150
|
+
elif isinstance(data.get("items"), list):
|
|
1151
|
+
candidates.extend(str(x["id"]) for x in data["items"] if isinstance(x, dict) and x.get("id"))
|
|
1152
|
+
elif data.get("id"):
|
|
1153
|
+
candidates.append(str(data["id"]))
|
|
1154
|
+
else:
|
|
1155
|
+
for line in raw.splitlines():
|
|
1156
|
+
s = line.strip()
|
|
1157
|
+
if s and not s.startswith("#"):
|
|
1158
|
+
candidates.append(s)
|
|
1159
|
+
|
|
1160
|
+
seen: set[str] = set()
|
|
1161
|
+
out: list[str] = []
|
|
1162
|
+
for c in candidates:
|
|
1163
|
+
vid = parse_video_id(c)
|
|
1164
|
+
if vid not in seen:
|
|
1165
|
+
seen.add(vid)
|
|
1166
|
+
out.append(vid)
|
|
1167
|
+
return out
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
def load_done_ids(jsonl_path: Path) -> set[str]:
|
|
1171
|
+
done: set[str] = set()
|
|
1172
|
+
if not jsonl_path.exists():
|
|
1173
|
+
return done
|
|
1174
|
+
for line in jsonl_path.read_text(encoding="utf-8").splitlines():
|
|
1175
|
+
if not line.strip():
|
|
1176
|
+
continue
|
|
1177
|
+
try:
|
|
1178
|
+
rec = json.loads(line)
|
|
1179
|
+
if rec.get("state") == "ok" and rec.get("id"):
|
|
1180
|
+
done.add(rec["id"])
|
|
1181
|
+
except json.JSONDecodeError:
|
|
1182
|
+
continue
|
|
1183
|
+
return done
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
def cmd_batch(args: argparse.Namespace) -> dict[str, Any]:
|
|
1187
|
+
out_dir = Path(args.out_dir)
|
|
1188
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
1189
|
+
items_path = out_dir / "items.jsonl"
|
|
1190
|
+
blocked_path = out_dir / "blocked.json"
|
|
1191
|
+
if os.path.lexists(blocked_path):
|
|
1192
|
+
# Do not let a caller's --out overwrite the original stop evidence.
|
|
1193
|
+
if args.out and Path(args.out).resolve() == blocked_path.resolve():
|
|
1194
|
+
args.out = None
|
|
1195
|
+
raise BlockedError(
|
|
1196
|
+
source_url=None,
|
|
1197
|
+
status=None,
|
|
1198
|
+
reason="existing_stop",
|
|
1199
|
+
evidence=f"{blocked_path} already records a stop; no collection started.",
|
|
1200
|
+
)
|
|
1201
|
+
|
|
1202
|
+
all_ids = load_video_ids_from_input(Path(args.input_file))
|
|
1203
|
+
if args.limit is not None and args.limit > 0:
|
|
1204
|
+
all_ids = all_ids[: args.limit]
|
|
1205
|
+
done = load_done_ids(items_path)
|
|
1206
|
+
todo = [vid for vid in all_ids if vid not in done]
|
|
1207
|
+
|
|
1208
|
+
has_api_key = bool(os.environ.get("YOUTUBE_API_KEY") or os.environ.get("GOOGLE_API_KEY"))
|
|
1209
|
+
mode = args.mode
|
|
1210
|
+
if mode == "auto":
|
|
1211
|
+
mode = "api" if has_api_key else "inspect"
|
|
1212
|
+
|
|
1213
|
+
fetched_ok = 0
|
|
1214
|
+
fetched_err = 0
|
|
1215
|
+
|
|
1216
|
+
def record_blocked(exc: BlockedError, vid: str | None) -> None:
|
|
1217
|
+
payload = dict(exc.payload)
|
|
1218
|
+
payload.update(
|
|
1219
|
+
{
|
|
1220
|
+
"source_id": vid,
|
|
1221
|
+
"mode": mode,
|
|
1222
|
+
"selected_count": len(all_ids),
|
|
1223
|
+
"previously_done": len(done),
|
|
1224
|
+
"fetched_ok_this_run": fetched_ok,
|
|
1225
|
+
"remaining_count": max(0, len(todo) - fetched_ok - fetched_err),
|
|
1226
|
+
"items_jsonl": str(items_path),
|
|
1227
|
+
}
|
|
1228
|
+
)
|
|
1229
|
+
blocked_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
1230
|
+
exc.payload = payload
|
|
1231
|
+
|
|
1232
|
+
with items_path.open("a", encoding="utf-8") as fh:
|
|
1233
|
+
if mode == "api":
|
|
1234
|
+
for i in range(0, len(todo), 50):
|
|
1235
|
+
batch_ids = todo[i : i + 50]
|
|
1236
|
+
ns = argparse.Namespace(
|
|
1237
|
+
videos=batch_ids,
|
|
1238
|
+
comments=args.comments,
|
|
1239
|
+
captions_meta=args.captions_meta,
|
|
1240
|
+
)
|
|
1241
|
+
try:
|
|
1242
|
+
resp = cmd_api_video(ns)
|
|
1243
|
+
except BlockedError as exc:
|
|
1244
|
+
record_blocked(exc, batch_ids[0] if batch_ids else None)
|
|
1245
|
+
raise
|
|
1246
|
+
returned_map = {it["id"]: it for it in resp.get("items", [])}
|
|
1247
|
+
obs = resp["observed_utc"]
|
|
1248
|
+
for vid in batch_ids:
|
|
1249
|
+
if vid in returned_map:
|
|
1250
|
+
rec = dict(returned_map[vid])
|
|
1251
|
+
rec["state"] = "ok"
|
|
1252
|
+
rec["source_tier"] = "tier1_youtube_data_api_v3"
|
|
1253
|
+
rec["observed_utc"] = obs
|
|
1254
|
+
fetched_ok += 1
|
|
1255
|
+
else:
|
|
1256
|
+
rec = {
|
|
1257
|
+
"state": "unavailable",
|
|
1258
|
+
"source_tier": "tier1_youtube_data_api_v3",
|
|
1259
|
+
"observed_utc": obs,
|
|
1260
|
+
"id": vid,
|
|
1261
|
+
"url": f"https://www.youtube.com/watch?v={vid}",
|
|
1262
|
+
"error": "Video ID not returned by YouTube Data API v3 videos.list (deleted, private, or invalid).",
|
|
1263
|
+
}
|
|
1264
|
+
fetched_err += 1
|
|
1265
|
+
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
1266
|
+
fh.flush()
|
|
1267
|
+
else:
|
|
1268
|
+
for idx, vid in enumerate(todo):
|
|
1269
|
+
if idx > 0 and args.delay > 0:
|
|
1270
|
+
time.sleep(args.delay + random.uniform(0.0, args.jitter))
|
|
1271
|
+
try:
|
|
1272
|
+
rec = cmd_inspect(argparse.Namespace(video=vid))
|
|
1273
|
+
fetched_ok += 1
|
|
1274
|
+
except BlockedError as exc:
|
|
1275
|
+
record_blocked(exc, vid)
|
|
1276
|
+
raise
|
|
1277
|
+
except Exception as exc:
|
|
1278
|
+
rec = {
|
|
1279
|
+
"state": "error",
|
|
1280
|
+
"source_tier": "tier2_watch_page_single_get",
|
|
1281
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1282
|
+
"id": vid,
|
|
1283
|
+
"url": f"https://www.youtube.com/watch?v={vid}",
|
|
1284
|
+
"error": str(exc),
|
|
1285
|
+
}
|
|
1286
|
+
fetched_err += 1
|
|
1287
|
+
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
1288
|
+
fh.flush()
|
|
1289
|
+
|
|
1290
|
+
return {
|
|
1291
|
+
"state": "ok",
|
|
1292
|
+
"source_tier": "tier1_youtube_data_api_v3" if mode == "api" else "tier2_watch_page_single_get",
|
|
1293
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1294
|
+
"mode": mode,
|
|
1295
|
+
"items_jsonl": str(items_path),
|
|
1296
|
+
"selected_count": len(all_ids),
|
|
1297
|
+
"previously_done": len(done),
|
|
1298
|
+
"fetched_ok": fetched_ok,
|
|
1299
|
+
"fetched_non_ok": fetched_err,
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
# --- Subcommand: thumbs (Media-free i.ytimg.com cover, keyframes & chapter stills) ---
|
|
1304
|
+
|
|
1305
|
+
def _load_records_for_thumbs(target: str) -> list[dict[str, Any]]:
|
|
1306
|
+
p = Path(target)
|
|
1307
|
+
if p.exists() and p.is_file():
|
|
1308
|
+
raw = p.read_text(encoding="utf-8").strip()
|
|
1309
|
+
if p.suffix.lower() == ".jsonl":
|
|
1310
|
+
return list(reduce_items_jsonl(p).values())
|
|
1311
|
+
data = json.loads(raw)
|
|
1312
|
+
if isinstance(data, dict) and data.get("id"):
|
|
1313
|
+
return [data]
|
|
1314
|
+
if isinstance(data, dict) and isinstance(data.get("items"), list):
|
|
1315
|
+
return [it for it in data["items"] if isinstance(it, dict) and it.get("id")]
|
|
1316
|
+
if isinstance(data, list):
|
|
1317
|
+
return [{"id": parse_video_id(x)} if isinstance(x, str) else x for x in data]
|
|
1318
|
+
vid = parse_video_id(target)
|
|
1319
|
+
return [{"id": vid, "static_thumbnails": static_thumbnail_urls(vid), "chapters": []}]
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
def cmd_thumbs(args: argparse.Namespace) -> dict[str, Any]:
|
|
1323
|
+
records = _load_records_for_thumbs(args.target)
|
|
1324
|
+
out_root = Path(args.out_dir)
|
|
1325
|
+
out_root.mkdir(parents=True, exist_ok=True)
|
|
1326
|
+
summaries: list[dict[str, Any]] = []
|
|
1327
|
+
|
|
1328
|
+
for rec in records:
|
|
1329
|
+
vid = rec["id"]
|
|
1330
|
+
vdir = out_root / vid
|
|
1331
|
+
vdir.mkdir(parents=True, exist_ok=True)
|
|
1332
|
+
static = rec.get("static_thumbnails") or static_thumbnail_urls(vid)
|
|
1333
|
+
saved_files: list[dict[str, Any]] = []
|
|
1334
|
+
|
|
1335
|
+
# Cover: try maxres -> sd -> hq
|
|
1336
|
+
cover_path = vdir / "cover.jpg"
|
|
1337
|
+
if not cover_path.exists():
|
|
1338
|
+
for cand_name in ("maxres", "sd", "hq"):
|
|
1339
|
+
cand_url = static.get(cand_name)
|
|
1340
|
+
if not cand_url:
|
|
1341
|
+
continue
|
|
1342
|
+
status, data = http_get_bytes_once(cand_url)
|
|
1343
|
+
if status == 200 and data:
|
|
1344
|
+
cover_path.write_bytes(data)
|
|
1345
|
+
saved_files.append(
|
|
1346
|
+
{
|
|
1347
|
+
"kind": "cover",
|
|
1348
|
+
"variant": cand_name,
|
|
1349
|
+
"file": cover_path.name,
|
|
1350
|
+
"source_url": cand_url,
|
|
1351
|
+
"bytes": len(data),
|
|
1352
|
+
"sha256": hashlib.sha256(data).hexdigest(),
|
|
1353
|
+
}
|
|
1354
|
+
)
|
|
1355
|
+
break
|
|
1356
|
+
if args.delay > 0:
|
|
1357
|
+
time.sleep(args.delay)
|
|
1358
|
+
else:
|
|
1359
|
+
b = cover_path.read_bytes()
|
|
1360
|
+
saved_files.append(
|
|
1361
|
+
{"kind": "cover", "variant": "cached", "file": cover_path.name, "bytes": len(b), "sha256": hashlib.sha256(b).hexdigest()}
|
|
1362
|
+
)
|
|
1363
|
+
|
|
1364
|
+
# Static automatic keyframes (hq1, hq2, hq3)
|
|
1365
|
+
for kf in ("keyframe_1", "keyframe_2", "keyframe_3"):
|
|
1366
|
+
kf_url = static.get(kf)
|
|
1367
|
+
if not kf_url:
|
|
1368
|
+
continue
|
|
1369
|
+
kf_path = vdir / f"{kf}.jpg"
|
|
1370
|
+
if not kf_path.exists():
|
|
1371
|
+
if args.delay > 0:
|
|
1372
|
+
time.sleep(args.delay)
|
|
1373
|
+
status, data = http_get_bytes_once(kf_url)
|
|
1374
|
+
if status == 200 and data:
|
|
1375
|
+
kf_path.write_bytes(data)
|
|
1376
|
+
saved_files.append(
|
|
1377
|
+
{
|
|
1378
|
+
"kind": "keyframe",
|
|
1379
|
+
"file": kf_path.name,
|
|
1380
|
+
"source_url": kf_url,
|
|
1381
|
+
"bytes": len(data),
|
|
1382
|
+
"sha256": hashlib.sha256(data).hexdigest(),
|
|
1383
|
+
}
|
|
1384
|
+
)
|
|
1385
|
+
else:
|
|
1386
|
+
b = kf_path.read_bytes()
|
|
1387
|
+
saved_files.append(
|
|
1388
|
+
{"kind": "keyframe", "file": kf_path.name, "bytes": len(b), "sha256": hashlib.sha256(b).hexdigest()}
|
|
1389
|
+
)
|
|
1390
|
+
|
|
1391
|
+
# Per-chapter thumbnails from inspect output
|
|
1392
|
+
for idx, ch in enumerate(rec.get("chapters") or [], 1):
|
|
1393
|
+
t_url = ch.get("thumbnail")
|
|
1394
|
+
if not t_url:
|
|
1395
|
+
continue
|
|
1396
|
+
st = ch.get("start_seconds")
|
|
1397
|
+
t_tag = f"{st // 60:02d}m{st % 60:02d}s" if isinstance(st, int) else f"ch{idx:02d}"
|
|
1398
|
+
ch_path = vdir / f"chapter_{idx:02d}_{t_tag}.jpg"
|
|
1399
|
+
if not ch_path.exists():
|
|
1400
|
+
if args.delay > 0:
|
|
1401
|
+
time.sleep(args.delay)
|
|
1402
|
+
status, data = http_get_bytes_once(t_url)
|
|
1403
|
+
if status == 200 and data:
|
|
1404
|
+
ch_path.write_bytes(data)
|
|
1405
|
+
saved_files.append(
|
|
1406
|
+
{
|
|
1407
|
+
"kind": "chapter",
|
|
1408
|
+
"chapter_index": idx,
|
|
1409
|
+
"time": ch.get("time"),
|
|
1410
|
+
"start_seconds": st,
|
|
1411
|
+
"title": ch.get("title"),
|
|
1412
|
+
"file": ch_path.name,
|
|
1413
|
+
"source_url": t_url,
|
|
1414
|
+
"bytes": len(data),
|
|
1415
|
+
"sha256": hashlib.sha256(data).hexdigest(),
|
|
1416
|
+
}
|
|
1417
|
+
)
|
|
1418
|
+
else:
|
|
1419
|
+
b = ch_path.read_bytes()
|
|
1420
|
+
saved_files.append(
|
|
1421
|
+
{
|
|
1422
|
+
"kind": "chapter",
|
|
1423
|
+
"chapter_index": idx,
|
|
1424
|
+
"time": ch.get("time"),
|
|
1425
|
+
"start_seconds": st,
|
|
1426
|
+
"title": ch.get("title"),
|
|
1427
|
+
"file": ch_path.name,
|
|
1428
|
+
"bytes": len(b),
|
|
1429
|
+
"sha256": hashlib.sha256(b).hexdigest(),
|
|
1430
|
+
}
|
|
1431
|
+
)
|
|
1432
|
+
|
|
1433
|
+
manifest = {
|
|
1434
|
+
"id": vid,
|
|
1435
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1436
|
+
"source_tier": "tier2_static_i_ytimg_thumbnails",
|
|
1437
|
+
"file_count": len(saved_files),
|
|
1438
|
+
"files": saved_files,
|
|
1439
|
+
}
|
|
1440
|
+
(vdir / "thumbs_manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
1441
|
+
summaries.append({"id": vid, "dir": str(vdir), "file_count": len(saved_files)})
|
|
1442
|
+
|
|
1443
|
+
return {
|
|
1444
|
+
"state": "ok",
|
|
1445
|
+
"source_tier": "tier2_static_i_ytimg_thumbnails",
|
|
1446
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1447
|
+
"videos_processed": len(summaries),
|
|
1448
|
+
"total_images": sum(s["file_count"] for s in summaries),
|
|
1449
|
+
"videos": summaries,
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
|
|
1453
|
+
# --- Subcommand: render (Contract-compliant videos/*.md, index.md, verified index.csv) ---
|
|
1454
|
+
|
|
1455
|
+
def reduce_items_jsonl(path: Path) -> dict[str, dict[str, Any]]:
|
|
1456
|
+
"""Reduce items.jsonl to one record per ID, preserving the latest successful record over later failed retries."""
|
|
1457
|
+
by_id: dict[str, dict[str, Any]] = {}
|
|
1458
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
1459
|
+
if not line.strip():
|
|
1460
|
+
continue
|
|
1461
|
+
rec = json.loads(line)
|
|
1462
|
+
vid = rec.get("id")
|
|
1463
|
+
if not vid:
|
|
1464
|
+
continue
|
|
1465
|
+
prev = by_id.get(vid)
|
|
1466
|
+
if prev is None or rec.get("state") == "ok" or prev.get("state") != "ok":
|
|
1467
|
+
by_id[vid] = rec
|
|
1468
|
+
return by_id
|
|
1469
|
+
|
|
1470
|
+
|
|
1471
|
+
def parse_iso_date(rec: dict[str, Any]) -> str:
|
|
1472
|
+
"""Return YYYY-MM-DD if known from ISO or YouTube human date text; otherwise empty string."""
|
|
1473
|
+
for key in ("publish_date", "published_at", "published", "upload_date"):
|
|
1474
|
+
val = rec.get(key)
|
|
1475
|
+
if isinstance(val, str) and re.match(r"^\d{4}-\d{2}-\d{2}", val):
|
|
1476
|
+
return val[:10]
|
|
1477
|
+
dt_txt = rec.get("date_text") or ""
|
|
1478
|
+
m = re.search(r"([A-Z][a-z]{2}\s+\d{1,2},\s+\d{4})", dt_txt)
|
|
1479
|
+
if m:
|
|
1480
|
+
try:
|
|
1481
|
+
return dt.datetime.strptime(m.group(1), "%b %d, %Y").strftime("%Y-%m-%d")
|
|
1482
|
+
except ValueError:
|
|
1483
|
+
pass
|
|
1484
|
+
return ""
|
|
1485
|
+
|
|
1486
|
+
|
|
1487
|
+
def slugify(text_val: str | None, max_len: int = 60) -> str:
|
|
1488
|
+
s = re.sub(r"[^a-zA-Z0-9]+", "-", (text_val or "video").lower()).strip("-")
|
|
1489
|
+
return (s[:max_len].rstrip("-")) or "video"
|
|
1490
|
+
|
|
1491
|
+
|
|
1492
|
+
def parse_views_int(rec: dict[str, Any]) -> str:
|
|
1493
|
+
if isinstance(rec.get("views"), int):
|
|
1494
|
+
return str(rec["views"])
|
|
1495
|
+
vt = rec.get("views_text") or ""
|
|
1496
|
+
digits = re.sub(r"[^\d]", "", vt)
|
|
1497
|
+
return digits if digits else ""
|
|
1498
|
+
|
|
1499
|
+
|
|
1500
|
+
def format_mmss(seconds: int | float | None) -> str:
|
|
1501
|
+
if seconds is None:
|
|
1502
|
+
return ""
|
|
1503
|
+
s = int(seconds)
|
|
1504
|
+
h, rem = divmod(s, 3600)
|
|
1505
|
+
m, sec = divmod(rem, 60)
|
|
1506
|
+
return f"{h}:{m:02d}:{sec:02d}" if h else f"{m}:{sec:02d}"
|
|
1507
|
+
|
|
1508
|
+
|
|
1509
|
+
def load_transcript_items(transcripts_dir: Path | None, vid: str) -> list[dict[str, Any]]:
|
|
1510
|
+
if not transcripts_dir:
|
|
1511
|
+
return []
|
|
1512
|
+
p = transcripts_dir / f"{vid}.json"
|
|
1513
|
+
if not p.exists():
|
|
1514
|
+
return []
|
|
1515
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
1516
|
+
if isinstance(data, dict) and isinstance(data.get("items"), list):
|
|
1517
|
+
return data["items"]
|
|
1518
|
+
if isinstance(data, dict) and isinstance(data.get("segments"), list):
|
|
1519
|
+
return [{"t": format_mmss(seg.get("start")), "x": seg.get("text", "")} for seg in data["segments"]]
|
|
1520
|
+
return []
|
|
1521
|
+
|
|
1522
|
+
|
|
1523
|
+
def cmd_render(args: argparse.Namespace) -> dict[str, Any]:
|
|
1524
|
+
items_path = Path(args.items)
|
|
1525
|
+
if items_path.suffix.lower() == ".jsonl":
|
|
1526
|
+
records_map = reduce_items_jsonl(items_path)
|
|
1527
|
+
else:
|
|
1528
|
+
raw = json.loads(items_path.read_text(encoding="utf-8"))
|
|
1529
|
+
if isinstance(raw, dict) and raw.get("id"):
|
|
1530
|
+
records_map = {raw["id"]: raw}
|
|
1531
|
+
elif isinstance(raw, dict) and isinstance(raw.get("items"), list):
|
|
1532
|
+
records_map = {it["id"]: it for it in raw["items"] if isinstance(it, dict) and it.get("id")}
|
|
1533
|
+
elif isinstance(raw, dict) and isinstance(raw.get("entries"), list):
|
|
1534
|
+
records_map = {it["id"]: dict(it, state="ok") for it in raw["entries"] if isinstance(it, dict) and it.get("id")}
|
|
1535
|
+
else:
|
|
1536
|
+
raise ValueError(f"Unsupported items format in {items_path}")
|
|
1537
|
+
|
|
1538
|
+
out_dir = Path(args.out_dir)
|
|
1539
|
+
videos_dir = out_dir / "videos"
|
|
1540
|
+
videos_dir.mkdir(parents=True, exist_ok=True)
|
|
1541
|
+
transcripts_dir = Path(args.transcripts_dir) if args.transcripts_dir else None
|
|
1542
|
+
diagrams_dir = Path(args.diagrams_dir) if args.diagrams_dir else None
|
|
1543
|
+
|
|
1544
|
+
rows: list[dict[str, str]] = []
|
|
1545
|
+
sorted_recs = sorted(
|
|
1546
|
+
records_map.values(),
|
|
1547
|
+
key=lambda r: (parse_iso_date(r) or "0000-00-00", r.get("id", "")),
|
|
1548
|
+
reverse=True,
|
|
1549
|
+
)
|
|
1550
|
+
|
|
1551
|
+
for rec in sorted_recs:
|
|
1552
|
+
vid = rec["id"]
|
|
1553
|
+
url = rec.get("url") or f"https://www.youtube.com/watch?v={vid}"
|
|
1554
|
+
title = rec.get("title") or vid
|
|
1555
|
+
iso_date = parse_iso_date(rec)
|
|
1556
|
+
fname = f"{iso_date or 'undated'}_{vid}_{slugify(title)}.md"
|
|
1557
|
+
rel_file = f"videos/{fname}"
|
|
1558
|
+
|
|
1559
|
+
chapters = rec.get("chapters") or []
|
|
1560
|
+
peaks = rec.get("heatmap_peaks") or []
|
|
1561
|
+
links = rec.get("companion_links") or {}
|
|
1562
|
+
comments = rec.get("top_comments") or []
|
|
1563
|
+
transcript = load_transcript_items(transcripts_dir, vid)
|
|
1564
|
+
|
|
1565
|
+
thumb_manifest_path = (diagrams_dir / vid / "thumbs_manifest.json") if diagrams_dir else None
|
|
1566
|
+
thumb_count = 0
|
|
1567
|
+
thumb_files: list[dict[str, Any]] = []
|
|
1568
|
+
if thumb_manifest_path and thumb_manifest_path.exists():
|
|
1569
|
+
tm = json.loads(thumb_manifest_path.read_text(encoding="utf-8"))
|
|
1570
|
+
thumb_files = tm.get("files", [])
|
|
1571
|
+
thumb_count = len(thumb_files)
|
|
1572
|
+
|
|
1573
|
+
md_lines = [
|
|
1574
|
+
f"# {title}",
|
|
1575
|
+
"",
|
|
1576
|
+
f"- **Video ID:** `{vid}`",
|
|
1577
|
+
f"- **URL:** {url}",
|
|
1578
|
+
f"- **Channel:** {rec.get('channel_name') or rec.get('channel_title') or rec.get('author') or ''}",
|
|
1579
|
+
f"- **Published:** {iso_date or rec.get('date_text') or 'unknown'}",
|
|
1580
|
+
f"- **Fetched (UTC):** {rec.get('observed_utc') or ''}",
|
|
1581
|
+
f"- **State:** `{rec.get('state') or 'unknown'}` ({rec.get('source_tier') or ''})",
|
|
1582
|
+
f"- **Views / Likes:** {rec.get('views_text') or parse_views_int(rec) or 'unknown'} / {rec.get('likes') if rec.get('likes') is not None else 'unknown'}",
|
|
1583
|
+
f"- **Caption inventory:** `{rec.get('caption_tracks_status') or ('present' if rec.get('has_captions') else 'unknown')}`",
|
|
1584
|
+
"",
|
|
1585
|
+
]
|
|
1586
|
+
if chapters:
|
|
1587
|
+
md_lines.append("## Chapters")
|
|
1588
|
+
md_lines.append("")
|
|
1589
|
+
for ch in chapters:
|
|
1590
|
+
st = ch.get("start_seconds")
|
|
1591
|
+
deep = f"{url}&t={st}s" if isinstance(st, int) else url
|
|
1592
|
+
md_lines.append(f"- [{ch.get('time') or format_mmss(st)}]({deep}) — {ch.get('title') or ''}")
|
|
1593
|
+
md_lines.append("")
|
|
1594
|
+
if peaks:
|
|
1595
|
+
md_lines.append("## Most Replayed Heatmap Peaks")
|
|
1596
|
+
md_lines.append("")
|
|
1597
|
+
for pk in peaks:
|
|
1598
|
+
st = int(pk["start_seconds"])
|
|
1599
|
+
md_lines.append(f"- [{format_mmss(st)}]({url}&t={st}s) — intensity `{pk['intensity']}` ({pk['duration_seconds']}s)")
|
|
1600
|
+
md_lines.append("")
|
|
1601
|
+
if links:
|
|
1602
|
+
md_lines.append("## Companion Links")
|
|
1603
|
+
md_lines.append("")
|
|
1604
|
+
for bucket, urls in links.items():
|
|
1605
|
+
md_lines.append(f"### {bucket}")
|
|
1606
|
+
for u in urls:
|
|
1607
|
+
md_lines.append(f"- {u}")
|
|
1608
|
+
md_lines.append("")
|
|
1609
|
+
if thumb_files:
|
|
1610
|
+
md_lines.append("## Downloaded Static Stills")
|
|
1611
|
+
md_lines.append("")
|
|
1612
|
+
for tf in thumb_files:
|
|
1613
|
+
label = tf.get("title") or tf.get("kind")
|
|
1614
|
+
ts_part = f" ({tf['time']})" if tf.get("time") else ""
|
|
1615
|
+
md_lines.append(f"- `{tf['file']}` — {label}{ts_part}")
|
|
1616
|
+
md_lines.append("")
|
|
1617
|
+
if rec.get("description"):
|
|
1618
|
+
md_lines.extend(["## Description", "", rec["description"], ""])
|
|
1619
|
+
if comments:
|
|
1620
|
+
md_lines.append("## Top / Pinned Comments")
|
|
1621
|
+
md_lines.append("")
|
|
1622
|
+
for cm in comments:
|
|
1623
|
+
badge = " **(Channel Owner)**" if cm.get("is_channel_owner") else ""
|
|
1624
|
+
md_lines.append(f"- **{cm.get('author') or 'unknown'}**{badge} ({cm.get('likes') or 0} likes): {cm.get('text', '').strip()}")
|
|
1625
|
+
md_lines.append("")
|
|
1626
|
+
if transcript:
|
|
1627
|
+
md_lines.append("## Transcript")
|
|
1628
|
+
md_lines.append("")
|
|
1629
|
+
for item in transcript:
|
|
1630
|
+
if "chapter" in item:
|
|
1631
|
+
md_lines.append(f"\n### {item['chapter']}\n")
|
|
1632
|
+
else:
|
|
1633
|
+
t_str = item.get("t") or ""
|
|
1634
|
+
st = parse_timestamp_seconds(t_str) if t_str else None
|
|
1635
|
+
prefix = f"[{t_str}]({url}&t={st}s)" if st is not None else (f"`{t_str}`" if t_str else "")
|
|
1636
|
+
md_lines.append(f"- {prefix} {item.get('x', '').strip()}")
|
|
1637
|
+
md_lines.append("")
|
|
1638
|
+
|
|
1639
|
+
(videos_dir / fname).write_text("\n".join(md_lines), encoding="utf-8")
|
|
1640
|
+
|
|
1641
|
+
rows.append(
|
|
1642
|
+
{
|
|
1643
|
+
"date": iso_date,
|
|
1644
|
+
"id": vid,
|
|
1645
|
+
"title": title,
|
|
1646
|
+
"channel": str(rec.get("channel_name") or rec.get("channel_title") or rec.get("author") or ""),
|
|
1647
|
+
"length_s": str(rec["length_seconds"]) if rec.get("length_seconds") is not None else "",
|
|
1648
|
+
"views": parse_views_int(rec),
|
|
1649
|
+
"likes": str(rec["likes"]) if rec.get("likes") is not None else "",
|
|
1650
|
+
"metadata_state": str(rec.get("state") or ""),
|
|
1651
|
+
"caption_status": str(rec.get("caption_tracks_status") or ("present" if rec.get("has_captions") else "")),
|
|
1652
|
+
"chapters": str(len(chapters)) if chapters else "",
|
|
1653
|
+
"heatmap_peaks": str(len(peaks)) if peaks else "",
|
|
1654
|
+
"comments": str(len(comments)) if comments else "",
|
|
1655
|
+
"companion_links": str(sum(len(v) for v in links.values())) if links else "",
|
|
1656
|
+
"thumbs": str(thumb_count) if thumb_count else "",
|
|
1657
|
+
"transcript_segments": str(len(transcript)) if transcript else "",
|
|
1658
|
+
"review_state": "unread",
|
|
1659
|
+
"fetched_at": str(rec.get("observed_utc") or ""),
|
|
1660
|
+
"url": url,
|
|
1661
|
+
"file": rel_file,
|
|
1662
|
+
}
|
|
1663
|
+
)
|
|
1664
|
+
|
|
1665
|
+
# Write index.csv with csv.DictWriter and reopen to validate row widths
|
|
1666
|
+
fieldnames = [
|
|
1667
|
+
"date", "id", "title", "channel", "length_s", "views", "likes",
|
|
1668
|
+
"metadata_state", "caption_status", "chapters", "heatmap_peaks",
|
|
1669
|
+
"comments", "companion_links", "thumbs", "transcript_segments",
|
|
1670
|
+
"review_state", "fetched_at", "url", "file",
|
|
1671
|
+
]
|
|
1672
|
+
csv_path = out_dir / "index.csv"
|
|
1673
|
+
with csv_path.open("w", encoding="utf-8", newline="") as cf:
|
|
1674
|
+
writer = csv.DictWriter(cf, fieldnames=fieldnames)
|
|
1675
|
+
writer.writeheader()
|
|
1676
|
+
writer.writerows(rows)
|
|
1677
|
+
|
|
1678
|
+
with csv_path.open("r", encoding="utf-8", newline="") as cf:
|
|
1679
|
+
csv_rows = list(csv.reader(cf))
|
|
1680
|
+
if not csv_rows or len(csv_rows[0]) != len(fieldnames):
|
|
1681
|
+
raise RuntimeError("index.csv header validation failed.")
|
|
1682
|
+
for line_no, r in enumerate(csv_rows[1:], 2):
|
|
1683
|
+
if len(r) != len(fieldnames):
|
|
1684
|
+
raise RuntimeError(f"index.csv row {line_no} field count mismatch: {len(r)} != {len(fieldnames)}")
|
|
1685
|
+
|
|
1686
|
+
# Write index.md
|
|
1687
|
+
idx_lines = [
|
|
1688
|
+
"# Video Index",
|
|
1689
|
+
"",
|
|
1690
|
+
f"Rendered {len(rows)} items from `{items_path.name}` at `{dt.datetime.now(dt.timezone.utc).isoformat()}`.",
|
|
1691
|
+
"",
|
|
1692
|
+
"| Date | ID | Title | Metadata | Chapters | Peaks | Links | Thumbs | Transcript | Review |",
|
|
1693
|
+
"|---|---|---|---|---|---|---|---|---|---|",
|
|
1694
|
+
]
|
|
1695
|
+
for r in rows:
|
|
1696
|
+
safe_title = r["title"].replace("|", "\\|")
|
|
1697
|
+
idx_lines.append(
|
|
1698
|
+
f"| {r['date'] or 'unknown'} | `{r['id']}` | [{safe_title}]({r['file']}) | "
|
|
1699
|
+
f"`{r['metadata_state']}` | {r['chapters'] or '—'} | {r['heatmap_peaks'] or '—'} | "
|
|
1700
|
+
f"{r['companion_links'] or '—'} | {r['thumbs'] or '—'} | {r['transcript_segments'] or '—'} | `{r['review_state']}` |"
|
|
1701
|
+
)
|
|
1702
|
+
idx_path = out_dir / "index.md"
|
|
1703
|
+
idx_path.write_text("\n".join(idx_lines) + "\n", encoding="utf-8")
|
|
1704
|
+
|
|
1705
|
+
return {
|
|
1706
|
+
"state": "ok",
|
|
1707
|
+
"source_tier": "offline_render",
|
|
1708
|
+
"observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1709
|
+
"rendered_count": len(rows),
|
|
1710
|
+
"index_md": str(idx_path),
|
|
1711
|
+
"index_csv": str(csv_path),
|
|
1712
|
+
"csv_verified_rows": len(csv_rows) - 1,
|
|
1713
|
+
"videos_dir": str(videos_dir),
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
|
|
1717
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
1718
|
+
parser = argparse.ArgumentParser(
|
|
1719
|
+
description="Media-free YouTube scraping, enrichment, and rendering CLI (official APIs, feeds, tab-verified inventory, resumable JSONL batch, static thumbs, links, Gemini YouTube URL)."
|
|
1720
|
+
)
|
|
1721
|
+
parser.add_argument("--out", help="Optional path to write JSON output instead of stdout.")
|
|
1722
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
1723
|
+
|
|
1724
|
+
p_feed = sub.add_parser("feed", help="Tier 0: Fetch official YouTube Atom/RSS feed (latest 15 items, zero auth).")
|
|
1725
|
+
p_feed.add_argument("--channel-id", help="YouTube channel ID (UC...).")
|
|
1726
|
+
p_feed.add_argument("--playlist-id", help="YouTube playlist ID (PL... or UU...).")
|
|
1727
|
+
p_feed.set_defaults(func=cmd_feed)
|
|
1728
|
+
|
|
1729
|
+
p_oembed = sub.add_parser("oembed", help="Tier 0: Fetch official YouTube oEmbed JSON (zero auth).")
|
|
1730
|
+
p_oembed.add_argument("video", help="YouTube video URL or 11-char video ID.")
|
|
1731
|
+
p_oembed.set_defaults(func=cmd_oembed)
|
|
1732
|
+
|
|
1733
|
+
p_api_vid = sub.add_parser("api-video", help="Tier 1: Official YouTube Data API v3 videos.list (+ optional top/pinned comments).")
|
|
1734
|
+
p_api_vid.add_argument("videos", nargs="+", help="One or more YouTube URLs or video IDs (batched up to 50/call).")
|
|
1735
|
+
p_api_vid.add_argument("--comments", type=int, default=0, help="Fetch up to N top/relevant comments per video (0=skip).")
|
|
1736
|
+
p_api_vid.add_argument("--captions-meta", action="store_true", help="Also try captions.list for caption track metadata (needs OAuth; an API key alone is refused and recorded as caption_tracks_error).")
|
|
1737
|
+
p_api_vid.set_defaults(func=cmd_api_video)
|
|
1738
|
+
|
|
1739
|
+
p_api_ch = sub.add_parser("api-channel", help="Tier 1: Official YouTube Data API v3 channel uploads inventory.")
|
|
1740
|
+
p_api_ch.add_argument("--channel-id", required=True, help="YouTube channel ID (UC...).")
|
|
1741
|
+
p_api_ch.add_argument("--limit", type=int, default=50, help="Maximum videos to return (default 50).")
|
|
1742
|
+
p_api_ch.set_defaults(func=cmd_api_channel)
|
|
1743
|
+
|
|
1744
|
+
p_tabs = sub.add_parser("channel-tabs", help="Tier 2: Tab-verified public channel inventory (/videos, /shorts, /streams) from initial HTML.")
|
|
1745
|
+
p_tabs.add_argument("channel", help="Channel UC... ID, @handle, or YouTube channel URL.")
|
|
1746
|
+
p_tabs.add_argument("--tabs", default="videos,shorts,streams", help="Comma-separated tabs to probe (default: videos,shorts,streams).")
|
|
1747
|
+
p_tabs.add_argument("--delay", type=float, default=2.0, help="Seconds to wait between tab requests (default: 2.0).")
|
|
1748
|
+
p_tabs.set_defaults(func=cmd_channel_tabs)
|
|
1749
|
+
|
|
1750
|
+
p_inspect = sub.add_parser("inspect", help="Tier 2: Single anonymous watch-page GET for rich metadata, chapters+thumbs, heatmap peaks, links, caption inventory.")
|
|
1751
|
+
p_inspect.add_argument("video", help="YouTube video URL or 11-char video ID.")
|
|
1752
|
+
p_inspect.set_defaults(func=cmd_inspect)
|
|
1753
|
+
|
|
1754
|
+
p_batch = sub.add_parser("batch", help="Resumable paced JSONL collector (auto-uses Data API v3 when YOUTUBE_API_KEY is set, else sequential inspect; writes blocked.json on 403/429).")
|
|
1755
|
+
p_batch.add_argument("input_file", help="Path to JSON list, channel-tabs/feed/api-channel JSON, or newline video ID/URL file.")
|
|
1756
|
+
p_batch.add_argument("--out-dir", required=True, help="Directory to append items.jsonl (and write blocked.json if halted).")
|
|
1757
|
+
p_batch.add_argument("--mode", choices=("auto", "api", "inspect"), default="auto", help="Collection backend (default: auto).")
|
|
1758
|
+
p_batch.add_argument("--delay", type=float, default=2.5, help="Base seconds between inspect requests (default: 2.5).")
|
|
1759
|
+
p_batch.add_argument("--jitter", type=float, default=1.0, help="Random extra jitter seconds for inspect requests (default: 1.0).")
|
|
1760
|
+
p_batch.add_argument("--comments", type=int, default=0, help="In API mode, also fetch up to N top/pinned comments per video.")
|
|
1761
|
+
p_batch.add_argument("--captions-meta", action="store_true", help="In API mode, also try captions.list (needs OAuth; an API key alone is recorded as caption_tracks_error).")
|
|
1762
|
+
p_batch.add_argument("--limit", type=int, help="Optional cap on number of videos to process.")
|
|
1763
|
+
p_batch.set_defaults(func=cmd_batch)
|
|
1764
|
+
|
|
1765
|
+
p_thumbs = sub.add_parser("thumbs", help="Tier 2: Download media-free i.ytimg.com cover, keyframes (hq1-3), and chapter thumbnails with SHA-256 manifest.")
|
|
1766
|
+
p_thumbs.add_argument("target", help="Video ID/URL, inspect JSON, or items.jsonl file.")
|
|
1767
|
+
p_thumbs.add_argument("--out-dir", required=True, help="Output directory (creates <out-dir>/<video_id>/).")
|
|
1768
|
+
p_thumbs.add_argument("--delay", type=float, default=0.5, help="Seconds between image downloads (default: 0.5).")
|
|
1769
|
+
p_thumbs.set_defaults(func=cmd_thumbs)
|
|
1770
|
+
|
|
1771
|
+
p_render = sub.add_parser("render", help="Render videos/*.md, index.md, and validated index.csv from items.jsonl (+ optional transcripts & thumbs).")
|
|
1772
|
+
p_render.add_argument("--items", required=True, help="Path to items.jsonl or single video/feed JSON.")
|
|
1773
|
+
p_render.add_argument("--out-dir", required=True, help="Output directory for videos/, index.md, and index.csv.")
|
|
1774
|
+
p_render.add_argument("--transcripts-dir", help="Optional directory containing <video_id>.json transcripts.")
|
|
1775
|
+
p_render.add_argument("--diagrams-dir", help="Optional directory containing <video_id>/thumbs_manifest.json.")
|
|
1776
|
+
p_render.set_defaults(func=cmd_render)
|
|
1777
|
+
|
|
1778
|
+
p_gemini = sub.add_parser("gemini", help="Tier 4: Official Gemini API multimodal analysis of a public YouTube URL (no local download).")
|
|
1779
|
+
p_gemini.add_argument("video", help="Public YouTube video URL or 11-char video ID.")
|
|
1780
|
+
p_gemini.add_argument("--start", help="Optional start_offset in seconds, e.g. 120s.")
|
|
1781
|
+
p_gemini.add_argument("--end", help="Optional end_offset in seconds, e.g. 420s.")
|
|
1782
|
+
p_gemini.add_argument("--fps", type=float, help="Optional frame sampling rate (e.g. 0.25 for slides, 1.0 for code demos).")
|
|
1783
|
+
p_gemini.add_argument("--model", default="gemini-2.5-flash", help="Gemini model name (default: gemini-2.5-flash).")
|
|
1784
|
+
p_gemini.add_argument("--prompt", help="Custom extraction prompt.")
|
|
1785
|
+
p_gemini.add_argument("--dry-run", action="store_true", help="Print the planned request payload without calling the API.")
|
|
1786
|
+
p_gemini.set_defaults(func=cmd_gemini)
|
|
1787
|
+
|
|
1788
|
+
p_links = sub.add_parser("links", help="Tier 3: Extract and categorize companion URLs from local JSON/Markdown files.")
|
|
1789
|
+
p_links.add_argument("files", nargs="+", help="Local files to scan for companion links.")
|
|
1790
|
+
p_links.set_defaults(func=cmd_links)
|
|
1791
|
+
|
|
1792
|
+
return parser
|
|
1793
|
+
|
|
1794
|
+
|
|
1795
|
+
def emit_json(payload: dict[str, Any], out_path: str | None) -> None:
|
|
1796
|
+
rendered = json.dumps(payload, indent=2, ensure_ascii=False)
|
|
1797
|
+
if out_path:
|
|
1798
|
+
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
|
|
1799
|
+
Path(out_path).write_text(rendered + "\n", encoding="utf-8")
|
|
1800
|
+
else:
|
|
1801
|
+
print(rendered)
|
|
1802
|
+
|
|
1803
|
+
|
|
1804
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1805
|
+
parser = build_parser()
|
|
1806
|
+
args = parser.parse_args(argv)
|
|
1807
|
+
try:
|
|
1808
|
+
result = args.func(args)
|
|
1809
|
+
emit_json(result, args.out)
|
|
1810
|
+
return EXIT_OK
|
|
1811
|
+
except BlockedError as exc:
|
|
1812
|
+
emit_json(exc.payload, args.out)
|
|
1813
|
+
return EXIT_BLOCKED
|
|
1814
|
+
except Exception as exc:
|
|
1815
|
+
emit_json({"state": "error", "error": str(exc)}, args.out)
|
|
1816
|
+
return EXIT_ERR
|
|
1817
|
+
|
|
1818
|
+
|
|
1819
|
+
if __name__ == "__main__":
|
|
1820
|
+
sys.exit(main())
|