cinecode
Makes a short film, animation, ad or music video entirely with code, together with the user. Two first questions - the mode (Quick - one HTML file with Web Audio sound, a few questions, a low-res draft, two revisions on drafts, then the final, up to about 3 minutes; Film - six gated steps with a style frame, animatic, three.js render and layered sound) and the purpose (cinematic film, or ad & product). Also: a film on the user's own song, a film like a reference video with changes, the user's own footage cut. Ends in an MP4 with a -14 LUFS master. Use when the user says "kısa film", "kodla film", "animasyon", "reklam filmi", "reklam", "ürün videosu", "tanıtım videosu", "müzik videosu", "klip", "şarkıma video", "bunun gibi bir video", "aynı formatta", "hızlı mod", "film modu", "make a short film", "animated short", "product video", "promo video", "music video", "explainer video", "cinecode", or asks what it can make, or when the folder has a STATE.md made by this kit and no FILM-BIBLE.md.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/sarpstar/cinecode with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/sarpstar/cinecode'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/sarpstar--cinecode)HTML
<a href="/listings/sarpstar--cinecode"><img src="/api/listings/sarpstar--cinecode/badge.svg" alt="findsafeskills safety rating" /></a>Install
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 167 lines
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- ---
- name: cinecode
- description: >-
- Makes a short film, animation, ad or music video entirely with code, together with the user. Two first questions - the mode (Quick - one HTML file with Web Audio sound, a few questions, a low-res draft, two revisions on drafts, then the final, up to about 3 minutes; Film - six gated steps with a style frame, animatic, three.js render and layered sound) and the purpose (cinematic film, or ad & product). Also: a film on the user's own song, a film like a reference video with changes, the user's own footage cut. Ends in an MP4 with a -14 LUFS master. Use when the user says "kısa film", "kodla film", "animasyon", "reklam filmi", "reklam", "ürün videosu", "tanıtım videosu", "müzik videosu", "klip", "şarkıma video", "bunun gibi bir video", "aynı formatta", "hızlı mod", "film modu", "make a short film", "animated short", "product video", "promo video", "music video", "explainer video", "cinecode", or asks what it can make, or when the folder has a STATE.md made by this kit and no FILM-BIBLE.md.
- hooks:
- UserPromptSubmit:
- - hooks:
- - type: command
- command: node
- args:
- - -e
- - "const f=require('fs'),p=require('path'),e=process.env,u=p.join(require('os').homedir(),'.claude','skills'),w=p.join(e.CLAUDE_PROJECT_DIR||process.cwd(),'.claude','skills');let d=[e.CLAUDE_SKILL_DIR,p.join(u,'cinecode'),p.join(w,'cinecode')];for(const s of [u,w]){try{d=d.concat(f.readdirSync(s).map(n=>p.join(s,n)))}catch(x){}}const r=d.find(x=>x&&f.existsSync(p.join(x,'scripts','hook.cjs'))&&f.existsSync(p.join(x,'scripts','guard.py')));if(r)require(p.join(r,'scripts','hook.cjs'))(process.argv[1])"
- - prompt
- onFailure: continue
- Stop:
- - hooks:
- - type: command
- command: node
- args:
- - -e
- - "const f=require('fs'),p=require('path'),e=process.env,u=p.join(require('os').homedir(),'.claude','skills'),w=p.join(e.CLAUDE_PROJECT_DIR||process.cwd(),'.claude','skills');let d=[e.CLAUDE_SKILL_DIR,p.join(u,'cinecode'),p.join(w,'cinecode')];for(const s of [u,w]){try{d=d.concat(f.readdirSync(s).map(n=>p.join(s,n)))}catch(x){}}const r=d.find(x=>x&&f.existsSync(p.join(x,'scripts','hook.cjs'))&&f.existsSync(p.join(x,'scripts','guard.py')));if(r)require(p.join(r,'scripts','hook.cjs'))(process.argv[1])"
- - stop
- onFailure: continue
- PreToolUse:
- - matcher: "*"
- hooks:
- - type: command
- command: node
- args:
- - -e
- - "const f=require('fs'),p=require('path'),e=process.env,u=p.join(require('os').homedir(),'.claude','skills'),w=p.join(e.CLAUDE_PROJECT_DIR||process.cwd(),'.claude','skills');let d=[e.CLAUDE_SKILL_DIR,p.join(u,'cinecode'),p.join(w,'cinecode')];for(const s of [u,w]){try{d=d.concat(f.readdirSync(s).map(n=>p.join(s,n)))}catch(x){}}const r=d.find(x=>x&&f.existsSync(p.join(x,'scripts','hook.cjs'))&&f.existsSync(p.join(x,'scripts','guard.py')));if(r)require(p.join(r,'scripts','hook.cjs'))(process.argv[1])"
- - tool
- onFailure: continue
- ---
- # cinecode
- You make a short film with the user. Their taste decides; you do the rest: story, script, picture, sound, edit, checks. The aim is a film worth the wait. You work best from a short, exact plan and your own eyes: so the plan is one card with numbers, you look at stills before anything long renders, and every note becomes a number to change.
- This file is the core. Open a reference only when a step names it, and only its section. The kit's tools enforce the mechanical rules (dashes in the words, still or repeated drafts, the show-first lock, the film folder, question language, chat size): when one stops, it prints what to do; follow it rather than restating it.
- Reply in the user's language; project files stay in English unless the user prefers otherwise. Messages are short: what was made, where, one or two questions, a recommendation.
- ## Asking the user
- Use the question tool when there is one (Claude Code `AskUserQuestion`: 1–4 questions a call, 2–4 options, a header of at most 12 characters; Cursor `AskQuestion`); otherwise one numbered message.
- - **Show before you ask.** Never ask for an OK on something the user has not seen in this chat: beats and lines are in the message itself, boards, stills and drafts are shown big as below. Too long for one message: show it part by part, ask at the last.
- - One question per item; the recommended option first with "★ (önerilen)" / "★ (recommended)" and its reason; the user's own answer always allowed. More candidates than slots: number them on a board, the rest are picked by typing their number; without a board, keep the best and the rest stay reachable as the own answer.
- - A round over the tool's limit becomes consecutive calls; one-line notes (the sound line, defaults) go in a short message before the first call.
- - **The idea stays open:** without one, ask it as a plain message first; once given, its 2–3 interpretations become the options, from three sparks (`deal.py deal spark`: each led by a seed, a real thing drawn by chance from outside, with a place, a form and a medium, so no two films start from the same place), after the prediction test and the overlap check (`writing.md` §1: fresh helpers; one writes the films the first message makes anyone expect, the other marks every candidate that repeats those or one of this user's own films, and a marked one is replaced). Invent a story only on "sen öner" / "suggest".
- - A gate is one question ("OK, continue ★" · "One note" · "A swap"), the note typed in "Other".
- - **The music is always the user's:** in both modes and at any pace, the first questions ask where it comes from (★ a real open-licence recording · their own track · written in code · none), never folded into another question; a recording is picked by ear (2–3 candidates sent as files, one question), even with `Pace: through`; a long film whose acts change mood may take a piece per act or part (a 12-minute film perhaps 3–4), its candidates grouped by act in that one listening question, while a short film keeps one track; music is made in code only when the user chose it. The pick goes into `STATE.md` as `Music: <recording file / own file / code / none> (user)`; `make.py` holds a draft whose music is code-made without that line.
- - **The pace of production is the user's (Film mode):** asked with the script gate, when production starts, as a second question in the same call: **"Aşama aşama"** (style frame, type, animatic, draft, each its own gate) or **"Hepsini üret, taslakta göster"** (straight to the draft cut). ★ the second up to about 3 minutes; ★ the first above, where a long render is worth a look at the frame and the pacing first. Written in `STATE.md` as `Pace: steps` or `Pace: through`. With `through`, or on "artık sorma, bitir" at any point, the film runs to the draft without a question, except a real blocker (a missing key, money, a legal limit): every choice goes to the ★ and is written in `STATE.md`, the style frame and key stills reach the user as progress, never as questions, and the draft lists the choices made so any of them can be a note. "Dur, göster" brings the gates back.
- - **An approved gate starts the next step in the same turn:** "Tamam", "onay", a ★ pick or "devam" is the go for what comes next, never the end of the work. A turn ends only on a question to the user, a delivery, or a background job named with how long it runs.
- - **Nothing runs silently:** before a step that takes more than about 30 s with nothing to show yet (a search, a board, a render, a helper), say in one line what it is doing and how long ("Stil panosu için film kareleri arıyorum, yarım dakika").
- - **A long job reports its progress:** a render or helper running over about 2 minutes gets a progress note with done/total and the minutes left (the status file's `eta_s`), again at about half way; "bitti mi?" is answered from the status file in one line, never with a guess.
- - **In the Claude Code desktop app a turn ends with its `wrap_up` box.** A gate the turn ends on (a delivered draft, a plan waiting for its OK) is never plain text: ask it with the question tool, or, with two choices, put it in `wrap_up` as `ask` with `blocked: true` and two reply buttons (`label` 1–3 words, `message` the user's words back), the ★ first. The box shows two buttons and drops the rest, so a question with more choices goes to the question tool: the draft's Final · Notes · Jury, or any question with the new-chat offer added ("Yeni sohbette devam ★" as one more option); on that answer the new chat starts already told to continue (Small context, below). The guard stops a delivered draft's turn that ends without its question.
- - **Everything the user reads is in their language,** every part of every question box and every short progress note between steps included ("Kartı kaydettim, ilk iki sahneyi kuruyorum", never "Card saved, building…"); this file's English examples are translated, never copied.
- - **Show pictures and films big, never in a window.** In Claude Code every board, stills sheet, poster and draft goes to the user with `SendUserFile` (`display: "render"`, `status: "normal"`, a one-line caption in their language): it opens big in the app's side panel. Elsewhere its path (or the page the tool wrote beside it) goes in the message. The tools print what to show ("show the user: …"); reading an image yourself shows the user only a tiny thumbnail, never enough.
- - **An option does exactly what its label says** (never "Tamam, temizle" that also saves a format). Two decisions are two questions.
- ## Start
- **Help** ("yardım", "neler yapabilirsin", "ne yapabilirim", "help", "what can you do", or a first message that asks for nothing specific: a greeting, "ne yapabiliriz"): this menu in their language, then one question with the four likeliest items and "Other":
- > Neler yapabiliriz (hepsi kodla, sonunda bir MP4):
- > 1. **Kısa film ya da animasyon**: bir fikir, bir his ya da bir yer; istediğin süre ve biçimde
- > 2. **Reklam, ürün ya da tanıtım videosu**: markan, ürünün ya da işin için
- > 3. **Müzik videosu, kendi şarkınla**: "bu şarkıya klip yap" + şarkı dosyası
- > 4. **Bir videoya benzeyen film**: "bunun gibi yap ama renkleri sıcak olsun" + video dosyası
- > 5. **Kendi çekimini kurgulamak**: konuşan kafa ya da ekran kaydı: duraklamalar kırpılır, grafikler eklenir
- > 6. **Kayıtlı formatla yeni film**: "geçen seferki formatta yeni bir tane"
- > 7. **Görünüşlere göz atmak**: fikrine uyan sinema yönlerini ve stilleri bir panoda görmek
- > Her birinde önce mod seçilir: Hızlı (bugün biter) ya da Film (her aşamada onay).
- **Update** ("cinecode'u güncelle", "update cinecode"): `git -C KIT pull`, then one line: open a new chat so the new version loads.
- **Direct routes.** A request that names a kind of film skips the menu: first the mode and purpose (one call), then the route's own first step, then only the questions it leaves open.
- | The user says | Route |
- |---|---|
- | a story, mood, place or animation idea | First questions |
- | an ad, product, launch, promo or explainer | First questions, purpose Ad & product |
- | a music video, or sends a song | `references/music-video.md` (its beat grid first) |
- | "bunun gibi", "like this one", or sends a video | `references/reference-video.md` |
- | their own footage to cut | `references/footage-edit.md` |
- | "aynı formatta", "same format" | `formats.py list` → `init_film.py <short-name> --format <name>` (with `--quick` when the format is a Quick one, as `formats.py list` shows); `quick-mode.md` §8 |
- | "stillere bakalım", "show me styles" | `styles.py suggest "<their words>" --board research/style-board.jpg`, then the first questions |
- ## First questions: mode and purpose
- **Steer first** (`references/steering.md`, short): read the idea against what costs the most in code. When it leans on what code draws badly (realistic people or animals as the subject, an idea stretched past its length), the ★ interpretation keeps the idea and its subject and changes only how they are shown; the original stays an option with its honest cost, and if the user picks it, help fully.
- Ask both in one call; skip one already answered ("reklam filmi" names the purpose).
- - **Mod / Mode:** **Hızlı / Quick**: this chat builds the whole film in one file; questions only where the brief leaves a gap; the card, two scenes as stills, then the draft (a complete brief: the draft first); about 3 approvals, a short film's first draft in minutes. **Film**: a studio process (roadmap, script, style frame, animatic, draft), research, layered sound, helpers for the parts that run in parallel; it takes longer than Quick, so the question never quotes a time for it: it says what the user sees and approves. The ★ follows the size of the work, never its purpose: ★ Quick under about 60 s, for one shot or a few scenes, brand and client pieces included; ★ Film from about 60 s with several scenes, research or archive material, a narrator over many chapters, or when the user asks for the gated process. The question says what each asks of the user ("Hızlı: ilk taslak dakikalar içinde, 3 onay · Film: önce yol haritası ve senaryo, sonra üretimi aşama aşama ya da tek seferde"). Unknown goal → ★ Quick (it can move to Film later, keeping the beats: `init_film.py <film> --to-film`).
- **A complete brief goes straight to work,** in either mode: when the opening message settles what happens and when, the words, the length, the format and what is delivered (a client brief, a shot list, an instruction to deliver and stop), nothing it answers is asked and no gate stands before the draft. The card is saved in `STATE.md` (its idea as the user gave it, marked `(user)`) and shown in one short message, the build starts at once, and the first gate is the draft itself (for a long build, a sheet of stills from its main moments). An instruction to deliver and stop is followed as written: deliver, report, wait. Only a gap that changes the film (a look the brief does not name, a missing logo) is asked, once, before building.
- - **Amaç / Purpose:** **Sinematik / Cinematic**: a story, mood or art piece that looks filmed, not rendered. **Reklam & ürün / Ad & product**: whose it is and what to do next are clear. ★ from the idea (a product, brand, launch, app or sponsor → Ad; a story, place, feeling or art idea → Cinematic). An own answer is mapped to the nearer purpose, said in one line.
- Record `Mode` and `Purpose` in `STATE.md`, then open `references/purpose-cinematic.md` or `references/purpose-ad.md` (its defaults and checks).
- ## Quick mode
- Everything in `references/quick-mode.md`. Setup: `python3 KIT/scripts/init_film.py <short-name> --quick --films-folder Filmler` (the folder word in the user's language). In short: questions in one round (the idea, then the medium, the user's choice; then the style picked by eye inside it: for a named look, your own readings of it beside real stills; otherwise a board) · research in the background · **the production card** as text within a minute or two (beats second by second, the director card with numbers) · the look and two scenes as stills, a gate · the rest in passes · half-size draft · up to two revision rounds on drafts · the final after the OK.
- ## Film mode
- Everything in `references/film-mode.md`, with `references/context-protocol.md`. Setup: `python3 KIT/scripts/init_film.py <short-name> --films-folder Filmler`. Six gated steps: interview → roadmap → script → style frame and type → animatic → draft cut, then the final; a gate the brief already answers is skipped. This chat does the work it holds the context for and hands a helper only an independent part that runs beside it (sound designed while the picture is made, voice takes recorded, research, the independent viewer) or a chapter of a long film (`context-protocol.md` §1); notes are saved verbatim per round; a defect is diagnosed before anything is rebuilt; at each gate the user may be asked to continue in a new chat ("STATE.md'den devam et").
- ## Where things are
- **KIT** = the folder of this file: `references/`, `templates/`, `scripts/`, `starter/`, `styles/`; read only. **PROJECT** = one folder per film, made by `init_film.py`, which picks the right place (the chat's folder when it holds only films, otherwise a films folder) and stops with the question to ask when it cannot (a film at the root of a films folder, a chat started inside a film, an unclear folder). A short name comes from the title (lowercase, ASCII, hyphens), so the folder stays a shelf of films that never mix; tell the user the film's folder in one line, first in words they can follow to find it (Mac: Finder › Home › Filmler › <name>; Windows: File Explorer › <their user folder> › Filmler › <name>; Linux: Files › Home › Filmler › <name>, in their language), then the path; never a film inside a film; never step into a film folder this chat did not create unless the user names it (another chat may be working there: `init_film.py` says IN USE when its files changed in the last 15 minutes, EXISTS otherwise, and then you ask); work inside it (`cd <short-name>`); the finished `<title>.mp4` sits at its top. **`~/.cinecode/`** keeps what carries over: keys, saved formats, the taste log, caches.
- **Setup check, silently, beside the first questions:** `node -v` (≥ 22), `python3 -V` (Windows: `py -3 -V`, else `python -V`; then that command wherever these files say `python3`), `ffmpeg -version`, Chrome, free disk space (`df -h .`; Windows: `Get-PSDrive`), and the GPU: `node KIT/scripts/capture.mjs --url KIT/starter/index.html --probe` (it names the GPU, or warns on software rendering; the renderer follows it). A missing tool never stops the film: offer it in the same question round, one option per tool (★ install now, with this machine's command; "I'll do it myself"): macOS `brew install node ffmpeg`, `brew install --cask google-chrome` (no Homebrew: the one-line installer from brew.sh for the user to paste in Terminal; it asks for their password); Linux `sudo apt install nodejs ffmpeg chromium`; Windows `winget install OpenJS.NodeJS Gyan.FFmpeg Google.Chrome Python.Python.3.12` (nothing else to render: the kit needs no bash, and no Git to run; Git is used only to install and update the kit itself, §Update; when Claude Code runs commands in PowerShell, join them with `;`). An old Node (< 22) is upgraded the same way. Install after the OK in the background while the questions go on, check again, and continue where the film is. On Windows a program winget installs reaches only the apps started after it: once Node, ffmpeg or Python is installed, ask the user to close and reopen Claude Code once, then say "continue" (the guard needs `node` on its PATH). **Low disk space:** say how much is free and what the film needs, measured from a past film's folder when there is one (`du -sh`; PowerShell: `(Get-ChildItem -Recurse <folder> | Measure-Object Length -Sum).Sum`); a 30 s Quick film used 50–100 MB through its drafts, a long film with full-size finals a few GB.
- **A later session** ("STATE.md'den devam et"): with several films in the folder, list them by title and last change and ask which, unless the user named it. Load this skill (Claude Code: the Skill tool, which starts its guard; never re-read this file by hand), refresh the film's copied tools silently (`python3 KIT/scripts/init_film.py <film-folder> --update-tools`: a film begun with an older kit gets the new tools, its own files stay untouched), then read `STATE.md` first (Film mode: its "Resume here"; Quick mode: its Phase, Open notes and Next action lines); never rely on chat history.
- ## Hard rules
- What makes the film:
- - **Hook:** the first 2 seconds move from frame 1 and lead with an action; no still title, no fade from black.
- - **One action per beat, and every beat changes something** the viewer sees or hears; a camera move alone is not a beat; a beat that changes nothing is cut or given a job.
- - **Half size, never half detail:** every world is built at its full detail before the first draft (`quick-mode.md`: its real parts, materials, secondary motions, depth layers, how its light falls); a world of light, water or terrain goes on the GPU when there is one. A blockout is never shown as a draft.
- - **Motion that lives:** one lead per moment, cause before effect, nothing living moves linearly, no pops, landings on the cue (`references/motion.md`).
- - **One eye decides, the tempo drives variety:** every device (look, light, camera, transitions, effects, finishing) is chosen on the director card (Film mode: the roadmap's card) with its reason from this story, and the build uses what the card names. Camera moves, shot sizes, light and type change as often as the tempo asks; adjacent shots never repeat a move or size, and never the same designed transition twice in a row (a plain cut is the default joint and may follow a cut); something new reaches the eye or the ear every few seconds. What stays constant is the film's identity: one visual language and a signature that returns, changed. Monotony is a fault just like clutter. Libraries are vocabulary, never a checklist.
- - **No shortcuts from the templates:** example scenes, the test scene and presets are scaffolding, deleted before the first stills; every scene is built for this story (its subject, place, light and action); abstract shapes never stand in for the subject unless the user asked for an abstract film. Every preview frame is asked: could it belong to another film? If yes, it is redone first. A saved format or a reference video repeats a form, never scenes. **No AI-overused choices by habit:** the kit has no default font or palette; the colours and fonts every generated design reaches for ("yapay zekânın aşırı kullandığı") need a reason on the card (`make.py` prints a taste line while they are still there; `fonts.py` finds type by tone); the images generated films reach for by habit (a lighthouse or lanterns, neon, floating balloons) are never a default: they enter a plan when the user asked for them or when the plan says why this story needs them (`- **Habit image:** <the image>: <why>`; the guard holds a card, roadmap or script that brings one in silently).
- - **Sound from version 1:** ambience per scene, picture-locked effects, one shared space. **Narration is never the raw TTS:** each film gets its own voice treatment (`references/sound.md` §4b).
- - **Words read as written, never generated:** no dash (—, or – and -- used as one) anywhere in the film's words (`make.py` stops before rendering on one); generated-sounding tells ("X değil, Y", "adeta", "fısıldıyor", "peki ya…?", sales lines) are rewritten or kept with a reason (`references/writing.md` §6, `tools/words_check.py`).
- - **Type** reads at phone size, keeps its diacritics and has an open licence; a style rule is broken only as a named, consistent signature (`references/typography.md` §11).
- - **Counts follow the length:** shots, chapters, research and stills scale with the runtime (`references/craft.md` §0).
- - **Finishing is the user's choice:** motion blur, print tone and gate weave are off by default; Quick mode shows them as one line of the card, Film mode asks one multi-select question at the style frame (`references/purpose-cinematic.md` §2).
- How it is made:
- - **Stills before rendering:** Quick mode: the text plan, then stills, then a half-size draft; Film mode: the style frame, one still per new or changed shot, the animatic and the draft cut. No full-size moving video before the user's OK on a draft; single stills for review may be full size.
- - **Frames are pure functions of time:** time from the frame index, seeded randomness, assets loaded before `READY`.
- - **Measured, not heard:** you measure audio but cannot hear it; every delivery asks the user to listen, naming the seconds that matter.
- - **Delivery is the film:** the final sits in the project folder as `<title>.mp4` (and `<title>-altyazili.mp4` when subtitled) and its path leads the message; a film with outside material carries its credits right under the path, headed in capitals in the user's language ("PAYLAŞIRKEN BU KÜNYE VİDEONUN AÇIKLAMASINA GİRMELİ"), the lines themselves in a code block, never only the credits file's name. Versions are kept silently (`tools/snapshot.py "<step>"` at every gate and delivery: a local history of the film's text files only, nothing uploaded); never ask the user to commit, never mention git. **Versions without clutter:** after the OK on a final, two questions one at a time: "Ara dosyaları temizleyeyim mi?" (★ yes, what goes, what stays, the space it frees), then "Beğendiysen bu formatı kaydedeyim mi?" (`formats.py save`). On yes, delete drafts, picture-only and segment files, frame folders and older versions; never the delivered film, `refs/`, `assets/`, audio sources or `notes/`. Video has a bitrate ceiling (`capture.mjs --maxrate`: 10M, drafts 4M).
- - **The voice is the user's pick, by ear:** candidate takes as separate short files, one question; no agent or helper chooses a narrator's voice, and no line is generated in a voice the user has not heard and picked; the voice's treatment is picked by ear too: in Film mode from a treatment audition, in Quick mode the card's line the user approved (or an audition when they ask). A helper brief for narration says: render the takes and stop.
- - **No long detail work the user did not ask for.** A build step that would take more than about ten minutes on its own (a piece-by-piece model, a realistic character, many 3D worlds) is named on the card with its time, and the ★ is the lighter route that keeps the idea; the long one only when the user asks for it.
- - **Generated pictures only when the user asks.** When the code route struggles: ★ a style the code draws well (silhouette, cut-paper, toon, figures at a distance, objects instead of bodies), then a simpler scene, then stopping. A connected image or video generator (Higgsfield, fal or any service that spends credits) is never offered and never ★: it is used only when the user asks for it, as a last resort after the kit's own route was tried, and its output gets a `LICENSES.csv` row.
- - **No paid services, API keys, installs or large downloads without the user's OK;** no logins, no browser automation for research. **Keys once, never shown:** `tools/keys.py list` before asking; when a key is set, use it and never ask again. A new one: `keys.py open <NAME>` opens the key file in the user's text editor (no terminal), or `keys.py set <NAME>` (hidden input); keys in an older film's `.env` move with `keys.py import`. Saved once in `~/.cinecode/keys.env` for every film; never printed or copied into a film folder, `STATE.md`, a log, a commit or the chat. The guard blocks the obvious ways to open, print or search the key file, but it is a seatbelt, not a sandbox: shell code can always be written to read any file, so this is a rule the agent follows, not a wall. Reach a key only through `keys.py` and the tools that use it (`asset_search.py`, `tts.py`), which pass it to a service and never to the chat.
- - **Research is probed and boxed:** for a real person, team, event or brand, `asset_search.py supply` counts what the open archives hold before any download, and thin or empty elements go to the user at once with the routes (their licensed material, a design-led film, a mix); a search round takes at most 15 minutes, helpers included, and a deeper one is the user's call.
- - **Licences at download time:** every outside file gets a `LICENSES.csv` row; unknown licence = not used. Copyrighted films and stills are mood references only, never in a frame. Credits go in the video description (`make.py final` in Quick mode and `make.py credits` in Film mode write `<title>-credits.txt` beside the film), never on the picture and never as a list at the end, unless the user asks for one.
- - **All writes inside the project folder,** except `~/.cinecode/`. Check free disk before renders.
- ## Small context
- Every step re-reads the whole chat, so a film's cost is set by how large its chats grow, not by the model. Quick mode: the main chat builds, renders and revises itself, however large it grows (a helper starts cold and plans for minutes before its first edit); helpers only run the prediction test and the overlap check (`brief.py predict`, `brief.py overlap`), render narration takes and, in the background, watch a delivered draft as the independent viewer (`templates/quick/REVIEWER.md`); a large chat offers a new chat after a delivered draft, never by handing the work to a cold helper. Film mode: the same, with helpers for the independent parts of a longer film (one task, its model named, at most 25 tool calls, a reply of 10 lines or fewer, details in `review/`; `context-protocol.md` §1). A check a script answers (counting, validating, measuring) is the script's job, never a helper's. A long reference is read by section (the Grep tool for `^## `, then that section with the Read tool's offset and limit), never whole.
- - **One call per render step:** `python3 tools/make.py stills | draft | final`; never chain capture, master and checks by hand, never print a log into the chat (bash `> logs/x.log 2>&1`, PowerShell `2>&1 | Out-File -Encoding utf8 logs/x.log` so 5.1 does not write UTF-16, then its last lines with the Read tool).
- - **Edit, never rewrite:** read files in parts (the Grep tool, the Read tool's offset and limit) and change only what a note touches; a helper script longer than about 20 lines is saved in `logs/` and run from there, not pasted inline.
- - **Small images only:** the sheets the tools write (under a megapixel), one per gate in the main chat.
- - **Measured:** `tools/usage.py` shows each chat's tokens; in Claude Code the guard reminds at 160 K and 260 K tokens, refuses large images and stops a helper after 25 tool calls.
- - One batch of notes per round, one question per gate. What the user praised is locked: fixes and re-plans keep it (`film-mode.md`, Notes).
- At a delivered draft, when the guard reports a large chat or after about 15 user messages, update `STATE.md` and offer a new chat (`templates/HANDOFF.md`: a question; in the desktop app's `wrap_up` box only as one of two buttons at most). On yes the new chat starts by itself: in the Claude desktop app with `mcp__ccd_session__start_session` (a child session that begins working at once, never a prefilled box the user must send); elsewhere `tools/handoff.py`.
- ## References
- - Modes: `quick-mode.md` · `film-mode.md` · `context-protocol.md`. Purpose: `purpose-cinematic.md` · `purpose-ad.md`. Routes: `music-video.md` · `reference-video.md` · `footage-edit.md`.
- - Steering: `steering.md`. Jury: `jury.md` (optional, two or three minutes). Story: `writer-prompt.md` (every script, line and card) · `writing.md`.
- - Picture: `looks.md` (8 families, 58 recipes) · `characters.md` (a stylised cast) · `camera-moves.md` · `motion.md` · `motion-design.md` (devices that tell: maps, counts, cutaways, archive parallax, annotations) · `finish.md` (the quality toolbox: light, lens, air, material, geometry, motion and post devices, chosen per scene) · `craft.md` (§0 counts by length) · `typography.md`. Sound: `sound.md`. Production: `engine.md` · `assets-and-licences.md`.
- - Tools (copied into a film's `tools/` by `init_film.py`, which runs from `KIT/scripts`; Quick mode leaves out the Film-only `animatic.py` and `validate_shots.py`; each with `--help`): `make.py`, `capture.mjs`, `qc.py`, `brief.py` (a helper's brief with the kit's rules for its task), `scene_check.py`, `validate_shots.py`, `animatic.py` · `mix.py`, `master_audio.py`, `voice_treat.py`, `tts.py`, `beat_grid.py`, `lyrics_align.py`, `samples.py`, `sounds.py` · `asset_search.py`, `styles.py`, `moves.py`, `fonts.py`, `direction.py`, `ref_video.py`, `deal.py`, `dice.py` (no CLI of its own: `deal.py deal spark|seed`, `deal.py past`), `type_deal.py` (no CLI of its own: `deal.py … type`), `type_refs.py`, `type_extract.py`, `captions.py`, `words_check.py` · `formats.py`, `keys.py`, `snapshot.py`, `handoff.py`, `usage.py` · `footage_cut.py`; the decks `sparks.json` and `seeds.json`. The guard (`guard.py`, started by `hook.cjs`) stays in the kit. Starters: `templates/quick/film.html` (engine: `templates/quick/HELPERS.md`); Film `starter/`. Needs Node 22+, Python 3 (standard library), ffmpeg and Chrome, nothing else; Whisper only for the footage edit and optional word-locked captions, installed with the user's OK.
README.md · README · 350 lines
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <p align="center">
- <img src="docs/media/lockup.png" alt="cinecode" width="560">
- </p>
- <p align="center">
- <b>Kodla yazılmış filmler.</b><br>
- Kısa filmler, uzun YouTube videoları, reklamlar, açıklayıcılar ve müzik videoları. Fikri ve zevki sen getirirsin; bir yapay zekâ kodlama ajanı senaryoyu yazar, her kareyi kodla kurar, sesi tasarlar ve sana bitmiş bir MP4 verir.
- </p>
- <p align="center">
- <a href="README.en.md">English</a> ·
- <a href="README.zh-CN.md">简体中文</a> ·
- <a href="README.ja.md">日本語</a> ·
- <a href="#kurulum">Kurulum</a> ·
- <a href="#hızlı-başlangıç">Hızlı başlangıç</a> ·
- <a href="#sss">SSS</a>
- </p>
- <p align="center">
- <a href="https://github.com/sarpstar/cinecode/actions/workflows/tests.yml"><img src="https://img.shields.io/github/actions/workflow/status/sarpstar/cinecode/tests.yml?branch=main&label=tests&style=flat-square" alt="tests"></a>
- <img src="https://img.shields.io/badge/license-MIT-C37232?style=flat-square" alt="license: MIT">
- <img src="https://img.shields.io/badge/agents-Claude%20Code%20%C2%B7%20Cursor-1a1a1a?style=flat-square" alt="agents: Claude Code, Cursor">
- <img src="https://img.shields.io/badge/render-three.js%20%C2%B7%20ffmpeg-1a1a1a?style=flat-square" alt="render: three.js, ffmpeg">
- </p>
- <p align="center">
- <img src="docs/media/reel.gif" alt="cinecode ile yapılmış filmlerden 30 saniye: gün doğumunda taş kemerler, karda linol baskı bir posta treni, oyulmuş bir saat mekanizması, çölde 3B bir tavşan, yağan kodun altında minyatür bir şehir, su altında pop-art bir balina, turuncu kapılardan geçen bir yol, üç dikey açıklayıcı, buğday tarlasında raylı bir film kamerası, altın ışık sütunları altında köpekler, bir kibrit, bir fırın ve bir caz afişi, fenerli bir çocuğun orman masalı, gece ufukta bir gemi" width="100%">
- </p>
- <p align="center"><sub>cinecode ile yapılmış filmlerden 30 saniye. Her kare başsız Chrome'da koddan üretildi.</sub></p>
- Kendi bilgisayarında, **Claude Code** (masaüstü uygulaması, VS Code eklentisi, terminal) ya da **Cursor** içinde çalışır. Ücretli bir servis gerekmez; dış ses, yalnızca istersen, kendi Gemini anahtarını (ücretsiz kotası var), ElevenLabs'i ya da ücretsiz bir Türkçe sesi kullanır.
- ## Neler yapabilirsin
- ### Kodla yapılmış kısa filmler
- Aklındakini tek cümleyle yaz; gerisini birlikte kurarsınız.
- - **Sıradan fikirde kalmaz.** Ajan fikrini, dünyadan rastgele çekilen gerçek bir şeyle buluşturur: bir müze eseri, bir hayvan, uzaydan bir fotoğraf, eski bir icat, tarihî bir yer, bir zanaat. Böylece sana herkesin aklına ilk gelen filmi değil, fikrinin senin bile düşünmediğin yorumlarını getirir.
- - **Kendini tekrar etmez.** Her öneri senin daha önce yaptığın filmlerle karşılaştırılır; aynı filmi sana ikinci kez önermez.
- - **Son söz hep senin.** Filmin neyden yapılacağını sen seçersin: gerçek ışıklı 3B, 2B animasyon, boya, mürekkep, kâğıt, kil, hareketli grafik ya da piksel. Görünümü gerçek filmlerden karelerle kurulmuş bir panodan seçersin; film bütünüyle kurulmadan önce ilk iki sahneyi görüp onaylarsın.
- ### Uzun YouTube videoları
- On dakikayı aşan belgeseller, açıklayıcılar ve video denemeleri; Film modunda perdeler ve bölümler hâlinde kurulur:
- - gerçek bir kişi ya da olay hakkındaki her iddianın kaynağıyla yazıldığı, araştırılmış bir metin;
- - ilk dakikada kurulan açık bir soru ve izleyiciyi sona kadar tutan bir merak haritası;
- - senin dilinde bir anlatıcı (Türkçe ve İngilizce sesler, ücretsiz Türkçe sesler dahil), çiğ motor sesiyle değil, filme ait bir ses işlemesiyle;
- - açık arşivlerden fotoğraflar, haritalar, belgeler ve görüntüler; resmi olmayan yerde kod: kendini çizen haritalar, sayaçlar, şemalar, yeniden kurulan mekânlar;
- - biçim isterse bölüm kartları, her perde için kulakla seçilen müzik, −14 LUFS mastering ve video açıklaman için bir künye dosyası.
- ### Reklam ve ürün filmleri
- Ürünün, renklerin, fontların, logon ve çağrı cümlen. Ürün ayrıntısıyla kurulur ve stüdyo çekimi gibi aydınlatılır; yazılım için arayüz kahraman planları; özgüllük testi filmin başka bir markaya uymasını önler; 9:16, 1:1 ve 16:9 sürümleri güvenli alanlarıyla gelir.
- ### Sosyal medya için açıklayıcılar
- 30–60 saniyelik dikey filmler: ilk saniyede bir soru, açık lisanslı ve Türkçesi denenmiş bir font eşleşmesiyle kinetik yazı, çizgi çizgi kurulan şemalar, telefonda okunan sözcükler.
- ### Müzik videoları
- Şarkını getir: vuruş ızgarası ölçülür, kesmeler ölçülere, vurgular vuruşlara oturur, her söz satırına bir görüntü.
- ### Ve dahası
- - **Sevdiğin bir video gibi ama farklı:** biçimi ölçülür (kesmeler, tempo, ışık, renk), film o biçimle yeniden yapılır, onun karelerinden asla.
- - **Kendi çekimlerinin kurgusu:** konuşan kafa ya da ekran kaydı, kelime zamanlı bir dökümden kesilir; duraklamalar kırpılır, grafikler sözcüklere oturur.
- - **Tek formatta seri:** bir filmin formatını kaydedip sonraki bölümü o formatta yaparsın.
- 15 saniyelik bir klipten on dakikayı aşan filmlere kadar. Hızlı mod yaklaşık 3 dakikaya kadar bir filmi tek oturumda yapar; Film modu daha uzun filmleri onaylı adımlarla götürür. Film uzadıkça daha çok zaman ve kullanım ister.
- ## cinecode ile yapılanlar
- <table>
- <tr>
- <td width="33%"><img src="docs/media/stills/motor.jpg" alt="Motor: gün batımında kırılırken donmuş bir dalga"><br><sub><b>Motor</b> · donmuş anlar · 90 sn</sub></td>
- <td width="33%"><img src="docs/media/stills/tren.jpg" alt="The Mail Train: linol baskı bir kar manzarasında kırmızı posta vagonu"><br><sub><b>The Mail Train</b> · linol baskı bir yolculuk · 25 sn</sub></td>
- <td width="33%"><img src="docs/media/stills/ilktik.jpg" alt="İlk Tik: altın bir saat mekanizmasına oyulmuş şehir silueti"><br><sub><b>İlk Tik</b> · bir saat reklamı · 50 sn</sub></td>
- </tr>
- <tr>
- <td><img src="docs/media/stills/atlama.jpg" alt="Atlama Programı: yağan yeşil kodun altında kâğıttan bir şehir"><br><sub><b>Atlama Programı</b> · minyatür bir saygı duruşu · 50 sn</sub></td>
- <td><img src="docs/media/stills/koltuk.jpg" alt="Boş Koltuk: boş bir tarlada raylı film kamerası"><br><sub><b>Boş Koltuk</b> · kendini kuran bir film seti · 80 sn</sub></td>
- <td><img src="docs/media/stills/kopek.jpg" alt="Yüz Köpek: ışık sütunları altında nokta nokta köpekler"><br><sub><b>Yüz Köpek</b> · bir veri belgeseli · 90 sn</sub></td>
- </tr>
- <tr>
- <td><img src="docs/media/stills/titanik.jpg" alt="Titanik, Son Saatler: karanlık denizde batan gemi"><br><sub><b>Titanik, Son Saatler</b> · bir belgesel · 5 dk</sub></td>
- <td><img src="docs/media/stills/cinecode.jpg" alt="cinecode: renkli pencerelerden pop-art bir kule"><br><sub><b>cinecode</b> · pop-art bir tanıtım · 60 sn</sub></td>
- <td><img src="docs/media/stills/fener.jpg" alt="Fener: ay ışığında bir kız ve bir ağaç ruhu"><br><sub><b>Fener</b> · animasyon bir masal · 60 sn</sub></td>
- </tr>
- <tr>
- <td><img src="docs/media/stills/gokyuzu.jpg" alt="Gökyüzü neden mavi?: ışığı ayıran bir prizma ve büyük sarı yazı"><br><sub><b>Gökyüzü neden mavi?</b> · bir açıklayıcı · 45 sn, 9:16</sub></td>
- <td><img src="docs/media/stills/firin.jpg" alt="Kuzguncuk Fırın: lambanın altında fırından yeni çıkmış simitler"><br><sub><b>Kuzguncuk Fırın</b> · bir fırın reklamı · 15 sn, 9:16</sub></td>
- <td><img src="docs/media/stills/kibrit.jpg" alt="Tek Kibrit: bakır renginde parlayan oyma bir şehir"><br><sub><b>Tek Kibrit</b> · grafik bir kısa film · 63 sn, 9:16</sub></td>
- </tr>
- </table>
- ## Nasıl çalışır
- 1. **Fikri söylersin.** Bir cümle yeter; eksiksiz bir brief doğrudan işe koyulur.
- 2. **Birkaç soru sorar** (fikrin okumaları, filmin neyden yapılacağı, süre ve format, görünüm, ses ve müzik); her birinde önerilen cevap ★ ile işaretli.
- 3. **Planı gösterir:** saniye saniye vuruşlar ve satır satır değiştirebileceğin bir yönetmen kartı. Sonra gerisi kurulmadan önce iki sahne, kare olarak.
- 4. **Taslağı render eder,** denetler (ilk kareden hareket, ses yüksekliği, okunurluk, tekrarlar), sana gösterir; bağımsız bir izleyici de onu soğuk gözle izler. Notların yalnızca dokundukları yeri değiştirir.
- 5. **Final:** tam boyut, −14 LUFS mastering ve video açıklaman için künye.
- ## İki mod
- Ajan önce bunu sorar ve hedefine göre birini önerir.
- | | **Hızlı mod** | **Film modu** |
- |---|---|---|
- | Tek satırda | tek dosyada tüm film, birkaç soru, düşük çözünürlüklü taslak, 1–2 revizyon | önce yol haritası ve senaryonun tamamı onaylanır; üretim ya aşama aşama senin onayınla ya da tek seferde taslağa kadar; araştırma, katmanlı ses |
- | En uygun | bir dakikanın altındaki her iş, marka ve müşteri işleri dahil; sosyal medya klipleri, anlatım videoları, reklamlar, yaklaşık 3 dakikaya kadar işler; kısa bir filmin ilk taslağı dakikalar içinde, yaklaşık 3 onay | birden çok sahneli, araştırmalı ya da arşiv malzemeli uzun filmler: belgeseller, dış sesli işler, festival kısaları; aşama aşama yaklaşık 6–8 onay, tek seferde yaklaşık 3 onay |
- | Nasıl | birkaç soru (biçim, dış ses, müzik ve referanslar dahil) → isteğe bağlı araştırma (filmine benzeyen filmlerden kareler, konu gerçekse gerçek şekiller) → plan metin olarak (vuruşlar, yönetmen kartı, referans panosu) → iki sahne kare olarak senin onayına gelir, sonra gerisi → düşük çözünürlüklü taslak → taslak üzerinde en fazla 2 revizyon turu → final render | 6 soru → yol haritası → senaryo → stil karesi → animatik → render; aşama aşama her biri senin onayınla ya da senaryodan sonra doğrudan taslak |
- | Görüntü | tek, kendi kendine yeten `film.html`: zamanın fonksiyonu olarak sahneler, Canvas 2D ya da three.js / WebGL, ekran yazısı | sekiz görünüm ön ayarlı three.js sahneleri, plan plan render |
- | Ses | ilk sürümden itibaren tasarlanmış, aynı dosyada (Web Audio, çevrimdışı render): her sahneye bir ortam sesi, görüntünün işaret tablosuna kilitli efektler, ortak bir yankı, düzenleme tablosundan müzik | tasarlanmış ses kimliği: katmanlı fonlar, efekt, doruk anları, anlatıcı ve müzik |
- | Ajanlar | tek ana sohbet kurar, render alır ve revize eder (hızlı); araştırma arka planda, yardımcılar yalnızca tahmin testi, tekrar kontrolü, dış ses denemeleri ve her taslağın bağımsız izleyicisi için | ana sohbet bağlamına sahip olduğu işi kendisi kurar; yardımcılar bağımsız parçaları paralel alır (ses, dış ses, araştırma, denetim) ve uzun filmin bölümlerini |
- Hızlı modda başlayıp bir filmi sonra Film moduna taşıyabilirsin: vuruşlar yol haritası olur.
- ## İki amaç
- Modla birlikte sorulur: mod işin ne kadar derin gideceğini, amaç nasıl bir film olacağını belirler. Sonrasındaki her şey (soruların önerileri, referanslar, onay noktaları, kontroller) amaca göre ilerler.
- | | **Sinematik film** | **Reklam & ürün** (marka, lansman, tanıtım, explainer) |
- |---|---|---|
- | Hedef | çekilmiş gibi görünen, render gibi durmayan bir hikâye, his ya da sanat işi | tek bir özneye ait, kimin olduğunu ve sonra ne yapılacağını net söyleyen bir film |
- | Görüntü | sinematik geçiş: sığ alan derinliği ve lens karakteri, gren, operatör ataleti; istersen (varsayılan kapalı) hızlı hareketlerde 180° hareket bulanıklığı, kitin kendi baskı eğrisiyle film tonu ve gate weave; her plan için seçilen kamera hareketleri | özgüllük ve rakip testi, ekranda isim etiketleri (alt üçte bir), yazılım için arayüz kahraman planları, markanın renkleri ve yazı tipleri (açık yazı tipleri Fontsource'tan; kendi marka yazı tipin yerelde kalır), harekete çağrılı kapanış kartı |
- | Ses | ortam sesi önde, bir imza ses, müzik senin seçimin | varsayılan: dış ses + müzik |
- | Teslim | seçtiğin format | güvenli alanlarıyla 9:16, 1:1 ve 16:9 sürümler |
- | Ek | — | isteğe bağlı: kendi çekimin ya da ekran kayıtların, kelime saatli dökümden kurgulanır (Whisper gerekir): duraklama kırpma, senin onayladığın kekeleme ve tekrar işaretleri, kelimelere bağlı grafikler |
- Ayrıntılar: `references/purpose-cinematic.md`, `references/purpose-ad.md`, `references/footage-edit.md`. Hareket, kamera dili, yazı tipleri, ses senkronu, kanca, plan başına tek eylem ve kontroller ikisinde ortaktır.
- ## Neler var
- - **Zekice, kısa, nokta atışı senaryolar için yazım sistemi** (iki modda da): önce çoğalt sonra seç, hikâyenin bir dönüşü varsa net bir dönüş, sonu önce yaz, anlatma göster, kelime bütçesi, İngilizce ve Türkçe yasaklı klişe listesi, sesli okuma ve %30 kısaltma turu, ilk kez izleyen gözüyle kontrol.
- - **Adlandırılmış kamera ve geçiş sözlüğü** (`references/camera-moves.md`): kamera hareketleri, odak hareketleri ve geçişler (dolly in, orbit, dolly zoom, FPV, omuz kamerası, hız rampası, odak kaydırma, eşleşme kesmesi, whip pan, J-cut…); her birinin izleyicide uyandırdığı his, varsayılan süre, hız ve yumuşatma. Her planın kamerası tek satırdır: *"dolly in, 3 s, slow ease-in-out, toward the figure"*. İki motor da bunları zamanın saf fonksiyonları olarak uygular (`film.html` 2.5B kamera, three.js için `starter/camera.mjs`).
- - **Hızlı mod başlangıç dosyası:** deterministik zaman çizelgesi, derinlik katmanlı 2.5B kamera, geçişler, görüntü ve ses için ortak işaret tablosu, tohumlu rastgelelik (tohumlu veriler için tembel önbellek), yazı yardımcıları ve aksanlı harflere pay bırakan isim etiketleri, küçük Web Audio sesleri (pad, kick, tick, hit, riser, whoosh, pluck, yumuşak lead, efekt, ortam sesleri, üretilmiş ortak yankı) ve her renderdan önce denetlenen bir düzenleme tablosu içeren `film.html`. Tarayıcıda tıklayınca görüntü ve ses birlikte oynar.
- - **Film modu görüşmesi** (üç kısa turda altı soru, aralarında yön panosu) ve **sekiz görünüm ön ayarı** (sinematik gerçekçi, anime/cel, pastel masal kitabı, claymation, kâğıt kesik/kolaj, retro/synthwave/VHS, parlak reklam, el yapımı mürekkep); ayrıca kendi referans görsellerinden özel görünüm çıkarma yolu. Aynı sekiz aile Hızlı modda da çalışır (renk düzeltmesi, doku, çizgi film gölgelemesi, saniyede 12 çizim).
- - **Filme ait bir ses:** dış ses asla çiğ motor sesiyle çıkmaz. Her film sesinin neyin içinden geldiğini (yakın, bant kaydı, radyo, koro, su altı, makine…) ve nerede durduğunu (oda, salon, taş bir mekân, açık hava) kendisi seçer; ses filmin imza sesini içinde taşıyabilir; her satır aynı konuşma seviyesine iner.
- - **Bunun gibi ama …:** beğendiğin bir videoyu `refs/` içine bırak ve neyi değiştirmek istediğini söyle. Biçimi ölçülür (kesmeler ve plan süreleri, tempo, palet ve ışık, BPM, kesmelerin vuruşa oturması), istediğini değiştirirsin, film o biçim üzerine yeniden yapılır; karelerinden ya da müziğinden hiçbir şey alınmaz.
- - **Kendi şarkın:** bir şarkı ya da parça getir, film onun vuruş ızgarasına oturur: tempo şarkının tamamından ölçülür, klip ölçü başından kesilir, kesmeler ve vurgular ölçü ve vuruşlara düşer, her söz satırına bir görsel; müzik dış sesin altında kendiliğinden kısılır.
- - **Yön panosu (Film modu):** fikrini söyleyince üç görsel yön tek görselde gösterilir; her biri bir stil ve o havayı taşıyan iki üç gerçek filmden kareler (FilmGrab, yalnızca ruh hali referansı) ve ölçülmüş paletinden oluşur; seçtiğin yön ölçülüp filmin ışığına ve rengine aktarılır, stil karesi de ona göre kontrol edilir.
- - **Her fikre bulunan görünüş:** gerçek sinemadan yönler (filmlerden, görüntü yönetmenlerinden ve fotoğrafçılardan kareler, yalnızca ilham için) ve söz dağarcığı olarak bir stil tarifleri rafı (ağaç baskı, ukiyo-e, gölge oyunu, risograf, sessiz film ve dahası; çoğu LemoLab'in, bkz. Emeği geçenler); yalnızca seçilen okunur.
- - **Tasarımcı düzeyinde tipografi** (`references/typography.md`): bağımsız açık dökümhanelerden ve Fontsource'tan lisansı temiz, Türkçesi doğrulanmış fontlar ve eşleşmeler; her film için üç eşleşme filmin kendi görünümünde örnek kartlarla sunulur; Fonts In Use, Art of the Title, Typewolf, Are.na ve `refs/type/` klasörüne bıraktığın kendi ekran görüntülerinden (Instagram kaydettiklerin dahil) tipografi referansları ölçülüp yöne dönüşür; seçimlerini filmden filme öğrenen bir zevk günlüğü; telefon boyutunda okunurluk, kontrast ve aksan kontrolleri; isteğe bağlı, kelimeye kilitli konuşan-kafa altyazıları.
- - **Ses tasarımının temelleri:** her film için hafif bir ses kimliği, katmanlı fon sesleri, test edilmiş ffmpeg tarifleri, −14 LUFS mastering.
- - **Küçük, bağımlılıksız araçlar:** kare yakalama (doğrudan MP4'e ve sayfanın film sesini WAV'a da), animatik, miks, mastering, kalite kontrolleri (ölçülen kanca kontrolü, kamera hareketi çıkarıldıktan sonra sahne başına özne eylemi, sahne başına ses yüksekliği ve sertlik dahil), lisans kaydı tutan açık lisanslı varlık arama.
- ## Gereksinimler
- - Bilgisayarında araç çalıştırabilen bir yapay zekâ kodlama ajanı: **Claude Code** (masaüstü uygulaması, VS Code eklentisi ya da terminal) ya da **Cursor**. claude.ai'deki normal sohbet bilgisayarında araç çalıştıramaz; Claude Code çalıştırır (ffmpeg, Chrome, betikler).
- - Node.js 22+, Python 3.9+, ffmpeg ve Google Chrome (ya da Chromium / Edge); eksik olanı ajan senin onayınla kurar. Başka bir şey gerekmez, Windows'ta da: kit Claude Code'un kendi PowerShell'inde çalışır, bash istemez; Git yalnızca kiti kurmak ve güncellemek için kullanılır, film üretiminde değil. Kitin bekçisi bir Claude Code oturumunda çalışmıyorsa filmin kurulumu GUARD OFF der (testler her gönderimde Windows ve Linux'ta, her değişiklikten önce macOS'ta çalışır; Windows'ta baştan sona bir film henüz denenmedi). Kancalar güncel bir Claude Code ister (exec biçimli kancalar ve `onFailure`, 2.1.295 ve sonrası); daha eski bir sürümde bekçi devreye girmeyebilir, film yine çalışır.
- - Chrome'un kullanabildiği bir GPU (güncel her Mac ya da sürücüsü çalışan bir PC).
- - Disk alanı: Hızlı mod kareleri doğrudan MP4'e aktardığı için birkaç yüz MB yeterli; Film modu render sırasında film başına birkaç GB ister.
- Biri eksik mi? Yine de başla: ajan önce bilgisayarı kontrol eder ve eksik olanı kurmayı önerir (bir şey kurmadan önce sorar). Başka hiçbir şey kurulmaz: betikler yalnızca yerleşik modülleri kullanır, three.js sabitlenmiş kütüphane sürümlerini CDN'den yükler.
- **İstersen bedava Türkçe sesler** (kit hiçbirini kurmaz; anlatım aksi halde senin anahtarınla Gemini TTS'ten, yoksa geçici olarak sistem sesinden gelir):
- - Canberk Aslan'ın [EMA Lightning](https://huggingface.co/canberkkkkkk/ema-lightning) modeli (Apache 2.0): tek, net bir ses, internetsiz ve işlemcide çalışır, PyTorch ile yaklaşık 800 MB. Kurulduktan sonra kit kullanabilir: `python3 tools/tts.py --install ema`, ardından `--engine ema`.
- - [VoxCPM2 Türkçe ses tasarımı](https://github.com/alexturkey/voxcpm2-turkce-ses-tasarimi) (Apache 2.0): sesi tarif ederek tasarlarsın, yedi hazır anlatıcı var (belgesel sesi, derin anlatıcı, haber spikeri); Apple Silicon ya da NVIDIA ekran kartı, yaklaşık 3,7 GB.
- - Özgür Güler'in [Ahenk](https://github.com/ozguradmin/ahenk-turkish-tts) projesi: soru tonlaması, duygular ve gülme (büyük model, NVIDIA ekran kartı) ve Ahenk Cep (küçük, işlemcide); ağırlıklar CC BY 4.0 olduğu için onları kullanan film Ahenk'e kredi verir.
- ## Kurulum
- Claude Code'u aç (masaüstü uygulamasında **Code** sekmesi, VS Code eklentisi ya da terminal) ve şunu yaz:
- > cinecode skill'ini https://github.com/sarpstar/cinecode adresinden kur
- Kiti GitHub'dan git ile `~/.claude/skills/cinecode` klasörüne çeker (Windows: `%USERPROFILE%\.claude\skills\cinecode`); git'i olmayan bir Windows bilgisayarda önce senin onayınla git'i kurar (`winget install --id Git.Git -e`). Sonra yeni bir sohbet aç. Daha sonra **"cinecode'u güncelle"** demen en yeni sürümü getirir. Yalnızca tek bir yere kur; ajan iki kopya görmesin.
- Elle, tek satırda aynısı:
- ```bash
- git clone https://github.com/sarpstar/cinecode.git ~/.claude/skills/cinecode
- ```
- Beceri gündelik film, animasyon ve reklam cümleleriyle başlar ("kısa film", "animasyon", "reklam filmi", "ürün videosu", "tanıtım videosu", "make a short film", "product video", "ad").
- ### 1. Claude masaüstü uygulaması (Code)
- Claude masaüstü uygulamasını aç, **Code**'a geç, filmin için boş bir klasör seç ve **"Kısa film yapmak istiyorum"** yaz (İngilizcesi: **"I want to make a short film"**).
- ### 2. VS Code eklentisi (Claude Code)
- Claude Code eklentisini kur, boş bir klasör aç, Claude Code panelini aç ve aynı cümleyi yaz.
- ### 3. Terminal
- ```bash
- mkdir filmim && cd filmim && claude
- ```
- Sonra aynı cümleyi yaz.
- ### 4. Cursor
- Cursor'ın Agent sohbetinde aynı kurulumu `~/.cursor/skills/cinecode` klasörüne iste, ya da:
- ```bash
- git clone https://github.com/sarpstar/cinecode.git ~/.cursor/skills/cinecode
- ```
- Cursor'da boş bir klasör aç, Agent sohbetini aç ve aynı cümleyi yaz. Kitin kendi kontrolleri (`make.py`, `qc.py`) aynı çalışır; bazı hataları anında durduran bekçi kancaları (gösterilmeden sorulan senaryo, gösterilmeyen taslak, onaydan hemen sonra durma) yalnızca Claude Code'da çalışır.
- ## Hızlı başlangıç
- 1. Ajanında boş bir klasör aç (bkz. Kurulum).
- 2. Fikrini yaz. Tek zorunlu şey fikir; gerisini bilmiyorsan boş bırak, ajan sorar:
- ```text
- cinecode ile bir film yapalım: <ne anlatsın, bir iki cümle>.
- (İstersen ekle, bilmiyorsan boş bırak; kit eksik olanı sorar:)
- Süre: <15 sn / 1 dk / 5 dk…>
- Nerede gösterilecek: <Instagram dikey / YouTube yatay…>
- Ses: <dış ses olsun / olmasın / kendi şarkım: dosya>
- Görünüş: <aklındaki bir film, fotoğraf, ressam ya da "sen öner">
- ```
- Modu yazma: ajan işin büyüklüğüne göre önerir. Ne kadar az yazarsan o kadar çok sorar; her şeyi eksiksiz yazarsan (vuruşlar, metin, süre, biçim) soru sormadan taslağa geçer.
- 3. Modu ve amacı seç (sinematik film ya da reklam & ürün), soruları bir iki kısa turda yanıtla (önerilen seçenek ★ ile işaretlidir).
- 4. Her kontrol noktasında onayla ya da değiştir. Bitmiş film, film klasörünün en üstüne `<başlık>.mp4` olarak gelir.
- ## Hızlı mod, adım adım
- | # | Adım | Sen ne yaparsın |
- |---|---|---|
- | 1 | **Birkaç soru:** fikrin, biçim (filmin neyden yapılacağı), süre ve format, stil ve his, ses (dış ses + müzik, yalnızca müzik ve efekt ya da ekran yazısı + müzik; dış seste ses tipi ve dil de sorulur), müzik ayrı bir soru olarak (kulağınla seçtiğin gerçek bir kayıt, kendi parçan, kodla yazılmış ya da müziksiz), referanslar (ara, sadece benimkiler ya da atla); ses kimliği tek satırla önerilir | yanıtla ya da "tamam" |
- | 1b | **Hafif araştırma, seçtiysen:** konunun ana öğeleri için açık lisanslı referanslar; film uzadıkça artar (15–30 sn için 2–3, 60 sn için 3–5, sonrasında bölüm başına 2; artı senin `refs/` klasörün) | — |
- | 2 | **Plan (tek metin kapısı):** tek cümlelik özet, dönüş, kamera satırlarıyla saniye saniye vuruş tablosu (uzun filmlerde tek akış, iç bölümlere göre gruplu), yazılar ya da replikler; araştırma yapıldıysa referans panosu; satır satır değiştirebileceğin kısa bir yönetmen kartı (stil, kamera, hareket, tempo, geçişler, font, ses, bitiş) | tamam, referans değiştir, tek not ya da daha fazla referans iste |
- | 3 | **Önce iki sahne:** görünüm ve iki sahne (açılış ve ona en az benzeyen) kare olarak, gerisi kurulmadan önce | devam ya da tek not |
- | 4 | **Yapım ve taslak:** görüntü ve sesiyle tek `film.html`, yarım boyutta, bitiş efektleri kapalı bir taslak, −14 LUFS mastering, kanca kontrolü | izle, sonra onay ya da not |
- | 5 | **Taslak üzerinde revizyonlar:** en fazla iki tur hedefli düzeltme, her biri yeni bir taslak olarak | notlarını tek seferde gönder |
- | 6 | **Final render:** tam boyut, açtığın bitiş efektleriyle (hareket bulanıklığı, baskı rengi, film titremesi; hepsi varsayılan olarak kapalı), kontroller yeniden | izle |
- ## Film modu, altı adım
- | # | Adım | Sen ne yaparsın |
- |---|---|---|
- | 1 | **Görüşme:** üç kısa turda altı soru, aralarında yön panosu | yanıtla ya da ★ seçenekleri seç |
- | 2 | **Yol haritası:** konsept, süreleriyle planlar (süre ne kadar gerektiriyorsa: 30 sn için 4–8, uzun filmlerde bölüm ve perdelere gruplu), görünüm, ses kimliği, kanca, riskler | onayla ya da satır değiştir |
- | 3 | **Senaryo ve metin:** açı, dönüş, replikler (ya da sözsüz), ekran yazıları; senaryonun tamamı tek seferde gösterilir | onayla ya da değiştir; üretimin nasıl ilerleyeceğini seç: aşama aşama ya da hepsi birden taslağa kadar |
- | 4 | **Stil karesi:** son kalitede tek bir kare; sonraki her karenin çıtası | onayla ya da not ver |
- | 5 | **Animatik:** düşük çözünürlüklü, zamanlanmış, geçici sesli video | tempo doğru mu? |
- | 6 | **Render, ses, final:** önce miksajlı yarım boy bir taslak kurgu, sonra tam boy görüntü, mastering, kontroller, teslim | izle, notlarını tek seferde gönder |
- Notlar yalnızca dokundukları planlara, repliklere ya da ses katmanlarına uygulanır; her tur yeni bir sürümdür. Finali onaylayınca ajan taslakların ve ara dosyaların temizlenip temizlenmeyeceğini sorar; teslim edilen film, referansların, varlıkların, ses kaynakların ve notların her zaman kalır.
- **Yerleşik kurallar (iki modda da):** ilk 2 saniye ilk kareden itibaren hareketlidir (ölçülür); her kare zamanın saf bir fonksiyonudur (yeniden render birebir aynıdır); dışarıdan gelen her dosya indirildiği anda lisans satırı alır; uzun renderlar durum dosyasıyla arka planda çalışır; ajan tam boy kareler yerine küçük temas sayfalarına bakar, bu da maliyeti düşük tutar.
- **İşi kim yapar (Film modu):** ana sohbet, bağlamı elinde olan işi kendisi kurar; proje dosyalarından brif alan ve modeli belirtilen yeni bir yardımcı ajan, paralel yürüyebilen bağımsız bir parçayı (ses, dış ses denemeleri, araştırma, bağımsız izleyici) ya da uzun bir filmin bir bölümünü üstlenir; notların `notes/round-N.md` dosyasına aynen kaydedilir ve yalnızca dokundukları planlar ele alınır; bir hata, bir şey yeniden yapılmadan önce birkaç test karesiyle teşhis edilir. Kontrol noktalarında ajan yeni bir sohbet önerebilir: Claude masaüstü uygulamasında senin onayınla kendiliğinden açılır; başka yerlerde yeni bir sohbet açıp tek satır yapıştırırsın: **"STATE.md'den devam et"** (İngilizce: **"Continue from STATE.md"**). Ayrıntılar: `references/context-protocol.md`. Sohbetteki her adım bütün sohbeti yeniden okur; bir filmi ucuz tutan şey kısa sohbettir: her yardımcı işinin gerektirdiği modelde başlar (zevk ve yargı gerektiren iş senin sohbetinin modelinde, dosya işleri ve kaynak arama daha hafif modellerde), renderlar dört satırla cevap verir (`tools/make.py`), görseller küçük kalır. Claude Code'da skill bunu kitin bekçisini başlatan üç kancayla uygular; denetimlerinden bazıları: sohbet büyüyünce hatırlatma, sohbete büyük görsel girmemesi, yardımcı başına 25 adım sınırı, kullanıcının görmediği bir şeyin sorulmaması, anahtar dosyasının kapalı kalması.
- ## İçinde ne var
- ```text
- cinecode/
- ├── SKILL.md beceri: akış, sorular ve kesin kurallar; her film sohbeti bununla başlar
- ├── AGENTS.md AGENTS.md okuyan ajanlar için giriş
- ├── references/ zanaat rehberleri
- │ ├── quick-mode.md Hızlı mod, adım adım
- │ ├── film-mode.md Film modu: altı onaylı adım
- │ ├── writing.md senaryo, kanca, tahmin testi, çakışma kontrolü
- │ ├── looks.md görünüm, ışık, doku; craft.md ve finish.md ile
- │ ├── camera-moves.md kamera dili; motion.md ve motion-design.md ile hareket
- │ ├── typography.md yazı; sound.md ses, music-video.md kendi şarkın
- │ └── purpose-*.md sinematik film ya da reklam ve ürün
- ├── scripts/ araçlar (Python standart kütüphanesi ve Node)
- │ ├── init_film.py film klasörünü kurar
- │ ├── make.py kareler, taslak ve final tek komutla
- │ ├── capture.mjs başsız Chrome'da kare kare render
- │ ├── deal.py, dice.py kıvılcımlar ve dış zar
- │ ├── direction.py stil panosu; styles.py, asset_search.py, fonts.py ile
- │ ├── mix.py miks; master_audio.py (−14 LUFS), tts.py (anlatıcı), beat_grid.py
- │ ├── qc.py kalite kontrolleri; scene_check.py, words_check.py ile
- │ └── guard.py bekçi: kuralları anında uygular (hook.cjs ile, Claude Code)
- ├── templates/ yeni bir filmin dosyaları ve Hızlı mod başlangıç sayfası
- ├── starter/ three.js sahnesi: sekiz görünüm, adlandırılmış kamera hareketleri, yazı katmanı
- ├── styles/ 58 stil tarifi (51'i lemo-opuscar, MIT; 7'si kitin kendi)
- ├── docs/ README görselleri ve font kütüphanesi
- └── tests/ her gönderimde Windows ve Linux'ta çalışan test takımı
- ```
- Kitin kurduğu bir film klasörü:
- ```text
- filmim/
- ├── <başlık>.mp4 bitmiş film
- ├── STATE.md filmin durumu; her yeni sohbet buradan devam eder
- ├── film.html Hızlı mod: filmin kendisi, tek sayfa kod
- ├── ROADMAP.md, SCRIPT.md Film modu: yol haritası ve senaryo; sahneler engine/ içinde
- ├── refs/, research/ referansların ve araştırma
- ├── audio/, assets/ ses ve indirilen malzeme; lisansları LICENSES.csv'de
- ├── review/, renders/ kontrol kareleri ve taslaklar
- └── tools/ kitin araçlarının bu filme ait kopyası
- ```
- **Dosyalar nerede durur:** her film kendi klasörüdür (bitmiş film en üstte `<başlık>.mp4` olarak durur). Filmden filme taşınanlar `~/.cinecode/` içindedir: API anahtarların (`keys.env`, bir kez girilir), kayıtlı formatlar, zevk günlüğü ve indirme önbellekleri. Kitin kendi klasörüne hiçbir şey yazılmaz.
- ## SSS
- **Yalnızca kod mu, hibrit mi?** Esas olan kod: görüntüler kodla üretilir, model maliyeti yoktur. Film uzadıkça ve gerçek olaylara dayandıkça, kodun gösteremediği yerlere gerçek malzeme girer: ajanın açık arşivlerde (Wikimedia Commons, Internet Archive, NASA, müzeler) kendi bulduğu görüntüler ve fotoğraflar, Pixabay'den stok fotoğraf ve videolar (ücretsiz anahtarın, bir kez sorulur); her biri lisansıyla kaydedilir ve kredisi yazılır. Ses için kit kayıt bir müzik ve hazır ses efektleri önerir (ücretsiz CC0 kütüphaneler); tamamen kodla üretilmiş ses de seçebileceğin bir tercih. Kendi çekimlerini, fotoğraflarını ve kayıtlarını ekleyebilirsin. Bir görsel ya da video üreticiyi (Higgsfield, fal ya da başka biri) kendin bağlarsan, ajan onu yalnızca sen istediğinde, son çare olarak kullanır; hiçbir zaman önermez. Yakın planda yüzler en iyi stilize ya da siluet olarak çalışır.
- **API anahtarımı her film için girmem mi gerekiyor?** Hayır. Dış ses ilk kez gerektiğinde bir kez girersin: ajan anahtar dosyasını metin düzenleyicinde boş bir `GEMINI_API_KEY=` satırıyla açar; anahtarı `=` işaretinden sonra yapıştırıp kaydedersin (ya da terminalde `python3 tools/keys.py set GEMINI_API_KEY`, yazarken görünmez). Sonraki bütün filmler onu kullanır. Eski bir filmin `.env` dosyasına koyduğun anahtarlar `keys.py import` ile oraya taşınır. Anahtarlar asla bir film klasörüne ya da repoya girmez.
- **Neler yapabildiğini nasıl öğrenirim?** Sor: "neler yapabilirsin?". Kısa bir menü gelir: kısa film, reklam ya da ürün videosu, kendi şarkına müzik videosu, bir videoya benzeyen film, kendi çekiminin kurgusu, kayıtlı formatla yeni film, stillere göz atmak. Ya da doğrudan ne istediğini söyle ("bu şarkıya klip yap"); ajan doğru yoldan ilerler.
- **Hangi modu seçmeliyim?** Bugün bitmiş bir film istiyorsan ya da sık paylaşıyorsan Hızlı mod; tek bir iş olabildiğince iyi olmalıysa Film modu. Ajan hedefine göre birini önerir.
- **Bir film ne kadar sürer?** Hızlı modda 30 saniyelik bir film kısa bir oturumdur: birkaç soru, bir plan, bakılacak iki sahne, hızlı bir taslak, sonra final render (her biri saniyelerle dakikalar arası). Film modunda 30 saniyelik bir film genellikle birkaç oturumdur: görüşme ve yol haritası dakikalar sürer, senaryo ve stil karesi bir oturum, 30 saniyelik filmin renderı güncel bir GPU'da dakikalar alır. Zamanın çoğu senin notlarına gider; amaç da bu.
- **Güçlü bir GPU gerekir mi?** Güncel her Mac (Apple silicon) ya da sürücüsü çalışan bir PC yeterli. Ajan bunu başta kontrol eder (`capture.mjs --probe`). Başsız Chrome'da GPU yoksa render CPU'ya düşer: test için yeterli, tüm film için yavaş.
- **Kendi referanslarımı kullanabilir miyim?** Evet: görselleri `refs/` içine, linkleri ya da film adı + dakikayı `refs/links.txt` içine bırak. Telif hakkı olan referanslar yalnızca hava/ton için kullanılır, karelere asla girmez.
- **Filmlerimi ticari olarak kullanabilir miyim (reklam, müşteri işi, para kazanan kanal)?** Kit açısından evet. Kitin dağıttığı ya da bulduğu her font, ticari kullanıma izin veren ve ekranda ya da açıklamada hiçbir atıf istemeyen bir lisansla gelir (SIL OFL, Apache, MIT, Ubuntu Font Licence, CC0); font görüntüde kullanılır, dosya olarak satılmaz ya da paylaşılmaz. Seçilmiş fontlardan dördü Fontshare'den gelir (ITF Free Font License): ticari iş için de ücretsizdir, ama dosyalarını kendin indirirsin ve başkasına vermezsin; kit bütün font dosyalarını git'in dışında tutar. Ajanın bulduğu referanslar yalnızca his ve biçim içindir; bir görsel ya da ses filme yalnızca izin veren bir lisansla girer ve `LICENSES.csv`'ye yazılır. Kendi logoların, marka fontların, çekimlerin ve şarkıların senin sorumluluğundadır. Açık müzik ve görseller: kit yalnızca kamu malı, CC0 ve CC BY malzeme, görsellerde CC BY-SA da alır (müzikte önce CC0), her lisansı kaydeder ve her finalin yanına video açıklaması için krediyi yazar; yayınlamadan önce bir eserin kaynak sayfasına bak ve kredi dosyasını filmle sakla (CC BY bir parçaya gelen YouTube Content ID talebine cevabı odur). Filmi yayınlayan, lisanslarından sorumludur; kit olduğu gibi sunulur (MIT lisansı). Bu bir hukuki tavsiye değildir.
- **Kredileri nereye yazarım?** Videonun açıklamasına (YouTube) ya da gönderi metnine (Instagram, TikTok, X); görüntünün üstüne hiçbir yere değil. Her final filmin yanına `<film adı>-credits.txt` bırakır: olduğu gibi yapıştır. Kamu malı ve CC0 malzeme satır gerektirmez (dosya yine de kısaca yazar); CC BY ve CC BY-SA malzemenin satırı gerekir, dosya lisans linkiyle birlikte yazar. Bir platform bir parçaya ya da görsele itiraz ederse cevabın da bu dosyadır.
- **Filmlerim nereye gidiyor?** Ajanı başlattığın klasöre: o klasör boşsa ya da yalnızca filmlerden oluşuyorsa her film orada kendi alt klasörünü alır; değilse (ev klasörün, masaüstü, bir kod projesi) ajan orada bir kez `Filmler` klasörü açar ve bütün filmleri onda toplar. Ajan sana yolu söyler. Bir dahakine ajanı aynı yerde başlat; "devam et" dediğinde filmlerin adlarıyla listelenir. Klasör seçmeden başlarsan (Claude uygulamasında klasörsüz bir sohbet), filmler ev klasöründeki `Filmler` klasörüne gider ve ajan sohbeti o filmin klasörüne taşır; böylece kareler, müzik ve taslak sohbette görünür.
- **Filmim nerede? Git bilmem gerekir mi?** Bitmiş film, film klasörüne `<başlık>.mp4` olarak kopyalanır ve ajan sana o yolu verir; ihtiyacın olan tek dosya odur. Git'e hiç dokunman gerekmez: kuruluysa ajan filmin metin dosyalarının yerel bir geçmişini tutar (kötü bir düzeltme geri alınabilsin diye). Hiçbir yere yüklenmez, videolar da bu geçmişe girmez.
- **Bir filmi beğendim, sonraki aynı formatta olabilir mi?** Evet. Finalden sonra "formatı kaydet" de; sonraki seferde "aynı formatta" de. Görünüm, font, ses, kamera dili ve ritim korunur, yalnızca fikir sorulur; sahneler ve sözler yeni fikre göre baştan yapılır. Formatlar senin bilgisayarında kalır (`~/.cinecode/formats`).
- **Ne kadar token harcar, nasıl görürüm?** Bir film, ajanın kod yazıp render edip kontrol ettiği uzun bir sohbettir: Hızlı modda 30–60 saniyelik bir film genellikle 100–250 adım sürer. Her adım bütün sohbeti yeniden okur; bunun çoğu önbellekten gelir ve ucuzdur, ama sohbet uzadıkça her adım büyür. Bu yüzden kit, bir aşama bitip sohbet büyüdüğünde yeni bir sohbette devam etmeyi önerir; film dosyalarında yaşadığı için hiçbir şey kaybolmaz. Film klasöründe `python3 tools/usage.py` her sohbetin token dökümünü gösterir (Claude Code). Her sohbet ayrıca kurulu her skill'in kısa açıklamasıyla ve bağlı her eklenti ile bağlayıcının araç tanımlarıyla başlar (bir skill'in tam talimatları yalnızca kullanıldığında yüklenir); filmin ihtiyaç duymadıklarını kapatmak her adımı ucuzlatır.
- **Hangi diller?** Ajan senin dilinde yanıt verir. Altyazı sen istemezsen kapalıdır (en fazla iki dil, alt alta).
- **Çevrimdışı?** Render, miks ve kontroller çevrimdışı çalışır; Hızlı mod başlangıç dosyası da öyle (Canvas 2D, Web Audio). Aramalar ağ ister (referanslar, müzik, ilk font ve stil indirmeleri; sonra önbellekte kalır). three.js sahnesi kütüphaneleri için bir kez ağa ihtiyaç duyar (ya da yerel bir kopya, bkz. `references/looks.md` §6); `starter/index.html` hiçbir şeye ihtiyaç duymaz.
- ## Testler
- Kit klasöründe `python3 -m unittest discover -s tests` çalıştır; gerçek Chrome ve ffmpeg testleri için başına `CINECODE_BROWSER_TESTS=1` ekle. Test takımı her gönderimde Windows'ta (Git ve bash ile de, onlarsız da) ve Ubuntu'da da çalışır. Bir sorun görürsen GitHub'da bildir.
- ## Emeği geçenler
- Sarp Yıldız ([@sarpstar](https://github.com/sarpstar)) tarafından, Claude ile birlikte Claude Code ve Cursor içinde yapıldı. MIT lisansı, bkz. [LICENSE](LICENSE).
- [three.js](https://github.com/mrdoob/three.js) (MIT) ve [pmndrs/postprocessing](https://github.com/pmndrs/postprocessing) (Zlib) üzerine kuruludur; render sırasında yüklenir, pakete dahil edilmez.
- Bazı fikirler [Leonxlnx/taste-skill](https://github.com/Leonxlnx/taste-skill) (MIT) projesinden ilham aldı.
- Karakter kiti (`references/characters.md`) John Heibel'in [ClaudeAnimationBase](https://github.com/JohnHeibel/ClaudeAnimationBase) projesinden, klişe ve renk kontrolleri [yihui-dev/awesome-opus5-5-videos](https://github.com/yihui-dev/awesome-opus5-5-videos) koleksiyonundaki filmlerin incelenmesinden ilham aldı. Yalnızca fikir: ikisinden de kod, prompt ya da kare alınmadı.
- Vuruş ızgarası yöntemi ve müzik videosu, geçiş sesleri ve kinetik tipografi dersleri [tuzhechen2005/opus-video-skills](https://github.com/tuzhechen2005/opus-video-skills) (MIT) projesinden alınıp bu kit için yeniden yazıldı.
- Stil kütüphanesi (`styles/`), LemoLab'in [lemomo-ai/lemo-opuscar](https://github.com/lemomo-ai/lemo-opuscar) projesindeki stil tarifleridir (MIT, `styles/LICENSE-lemo-opuscar`) ve tek bir commit'e sabitlenmiştir; demo filmleri ve motoru bağlantı olarak verilir, pakete dahil değildir.
- `vox-explainer` tarifi kitin kendisinindir; plan tipleri ve inceleme dersleri [charlie947/motion-graphics-skills](https://github.com/charlie947/motion-graphics-skills) (MIT) projesini izler.
- Bu kit için yeniden yazılanlar da (hepsi MIT): ürün filmi plan kataloğu [AbubakrChan/product-launch-motion](https://github.com/AbubakrChan/product-launch-motion); vuruş tipleri ve kesme gerekçeleri [cth9191/animate](https://github.com/cth9191/animate); kesme dikişi kuralları, tek kare parlama ve döngü kontrolleri, yalnızca hareket eden yerde bulanıklık, sessiz tek cümle testi ve sosyal medya kapak karesi [howseen-ai/claude-motion-design](https://github.com/howseen-ai/claude-motion-design); ışık ve lens sözlüğü [showheyohtaki/motion-prompt](https://github.com/showheyohtaki/motion-prompt).
- Hareket ilkeleri (`references/motion.md`) [LottieFiles/motion-design-skill](https://github.com/LottieFiles/motion-design-skill) (MIT) ve [whaleyxbt/claude-motion](https://github.com/whaleyxbt/claude-motion) (MIT) fikirlerinden; arayüz kahraman planı dili (`references/craft.md` §8) [1weiho/cinematic-shot](https://github.com/1weiho/cinematic-shot) (MIT) fikirlerinden; kareye tam oturan tempolar [cth9191/animate](https://github.com/cth9191/animate) (MIT) fikrinden; ham kayıt kurgusu (`references/footage-edit.md`) duraklama ve tekrar eşikleri ile kelimeye bağlı vuruşlarda [nateherkai/herk-edit-kit](https://github.com/nateherkai/herk-edit-kit) (MIT), konuşmaya bağlı grafik yoğunluğunda [Barty-Bart/motion-graphics](https://github.com/Barty-Bart/motion-graphics) (MIT) fikirlerinden yararlanır. Kayıtlı enstrümanlar (`scripts/samples.py`), [Vincentwei1021/mg-styles-15](https://github.com/Vincentwei1021/mg-styles-15) (MIT) tarafından paketlenmiş CC0 [Versilian Community Sample Library](https://github.com/sgossner/VCSL) örnekleridir; gerektiğinde indirilir, pakete dahil değildir. `line-boil`, `liquid-motion`, `shape-morph`, `sticker-explainer` ve `variety-captions` tarifleri ile jüri kontrolü, aynı reponun stil notlarını ve değerlendirme döngüsünü bu kit için yeniden yazar. Filmin kelimelerine yapılan kontroller (`scripts/words_check.py`) [blader/humanizer](https://github.com/blader/humanizer) (MIT) ve Wikipedia'nın [Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing) sayfasındaki kalıp ailelerini Türkçe karşılıklarıyla izler. lemo-opuscar tarifleri dışında (MIT lisanslarıyla birlikte dahil edildi) hepsi kendi cümlelerimizle yazıldı; kod ya da metin kopyalanmadı. İsteğe bağlı yazı tipleri [Fontsource](https://fontsource.org)'tan gelir (kod MIT; her yazı tipi kendi lisansındadır, çoğu SIL OFL 1.1) ve render sırasında yüklenir. `fonts.py` çalışırken [Fontsource API](https://fontsource.org/docs/api)'sini ve [google/fonts](https://github.com/google/fonts)'un herkese açık etiket listesini okur; ikisi de pakete dahil değildir.
- Kayıtlı enstrümanlar CC0'dır: [Versilian Community Sample Library](https://github.com/sgossner/VCSL) ve [Versilian Studios Chamber Orchestra 2 Community Edition](https://github.com/sgossner/VSCO-2-CE); yalnızca bir film kullandığında küçük parçalar halinde indirilir.
- Hazır ses efektleri [Kenney](https://kenney.nl)'nin ses paketleridir (CC0); bir film ilk ihtiyaç duyduğunda bir kez indirilir.
- Gereksinimler bölümünde önerilen bedava Türkçe sesler: EMA Lightning (Canberk Aslan), VoxCPM2 Türkçe ses tasarımı (alexturkey) ve Ahenk (Özgür Güler); yapanlarına teşekkürler.
- Depo: [github.com/sarpstar/cinecode](https://github.com/sarpstar/cinecode)
scripts/asset_search.py · Bundled script · 1,010 lines · 1 finding marked
- #!/usr/bin/env python3
- """Search open collections, and Pixabay with the user's free key, then fetch picks with a LICENSES.csv row (Python 3
- stdlib; ffmpeg optional).
- python3 tools/asset_search.py search --q "<a sound>" --type sound --out research/<sound>
- python3 tools/asset_search.py search --q "<what and where>" --type video --out research/<clip> # stock footage
- python3 tools/asset_search.py search --q "<genre and players>" --type music --out research/music # CC music
- python3 tools/asset_search.py search --q "<subject>" --sources met,cleveland --out research/<subject>
- python3 tools/asset_search.py search --q "<a sky or a room>" --type hdri --out research/hdri
- python3 tools/asset_search.py search --q "format:film-video" --type typography --out research/type-refs
- python3 tools/asset_search.py supply --q "<element>" --q "<element>" # what the archives hold, nothing downloaded
- python3 tools/asset_search.py fetch --results research/<sound>/results.json --pick 2,5 --dest assets/sound
- python3 tools/asset_search.py board --dirs research/<element-a> research/<element-b> --per 3 --refs refs \
- --out research/board-v1 # Quick mode: one sheet for the whole gate
- Sources (official APIs only, no browser; only Pixabay needs a key):
- pixabay Pixabay: stock photos (--type image) and videos (--type video) under the Pixabay Content License
- (free for commercial use, no credit owed); needs the user's free key once: keys.py open PIXABAY_API_KEY.
- Real-world material only: a hit whose tags miss the query's words, or that is AI-generated, a cartoon or
- a 3D render, is dropped; videos come in the largest size up to 1920 px wide.
- wikimedia Wikimedia Commons: images (--type image), sounds (--type sound) and videos (--type video); licence
- per file
- archive Internet Archive: music (--type music: released tracks from its Jamendo and netlabel collections),
- recordings (--type sound) and films (--type video); public domain, CC0 and CC BY only
- aic Art Institute of Chicago: public-domain artworks (CC0 images, up to 3000 px)
- cleveland Cleveland Museum of Art Open Access: CC0 artworks and objects (images up to 3400 px)
- met The Metropolitan Museum of Art Open Access: public-domain objects (CC0 images), opt-in
- rijks Rijksmuseum: public-domain artworks, prints and photographs (images up to 3400 px); its search matches
- titles; opt-in
- openverse Openverse (api.openverse.org): openly licensed images and audio gathered from many sites, filtered to
- CC0, PDM, CC BY, CC BY-SA; licence URL and attribution kept per item; check the item's source page.
- In the default sound and music searches: sounds (mostly Freesound), --type music = its music category
- (Jamendo tracks; CC BY-SA left out unless --licence names it, since share-alike music can carry its
- licence over to the whole film). Images opt-in. Its audio search can take 10-25 s, and it is often
- down: a search that it does not answer leaves it out of this film's searches for 30 minutes.
- polyhaven Poly Haven: HDRIs and textures (--type hdri | texture), all CC0
- nasa NASA Image and Video Library: images (NASA media guidelines: credit NASA, no endorsement)
- filmgrab FilmGrab (film-grab.com, its WordPress REST API; robots.txt allows it): film stills, MOOD ONLY:
- small thumbnails for the boards (direction.py), never fetched into the film. --q is a film title
- (--n stills spread across that one film) or "cat:<name>" for a cinematographer, director or genre
- page (one still from each of --n films).
- --type typography: real-world typography references through type_refs.py (Fonts In Use by format/topic/typeface,
- Art of the Title, Typewolf, Are.na; Typographic Posters link only): mood-only links and thumbnails for
- the type reference board, never fetched into the film. KIT/references/typography.md §9.
- Licences kept: cc0, pd, cc-by, cc-by-sa (default), nasa and pixabay; anything else (NC, ND, unknown) is dropped. FilmGrab
- records are kept as "mood-only"; fetch refuses them.
- --licence cc0,pd keeps only those.
- search writes <out>/results.json (numbered records) and, when ffmpeg is present, <out>/sheet.jpg: one small
- contact sheet of the thumbnails (look at it instead of single images: cheaper). It prints one line per result.
- fetch downloads the picked numbers into --dest and appends a row per file to LICENSES.csv at once (no row, no use).
- Music candidates: fetch --preview 30 first (the first 30 s of each, a few hundred KB, no row); the user listens and
- picks; then fetch only that one in full.
- board merges the first --per results of several searches (and the user's images in --refs) into one renumbered
- <out>/results.json (fetch works on it) and one <out>/sheet.jpg. It prints one line per reference and a measured palette (hex).
- Polite: a clear User-Agent, a pause between requests, results cached in research/.cache/.
- """
- import argparse
- import concurrent.futures
- import csv
- import datetime
- import hashlib
- import html
- import json
- import os
- import re
- import shutil
- import socket
- import subprocess
- import sys
- import time
- import urllib.error
- import urllib.parse
- import urllib.request
- UA = "cinecode-asset-search/1.0 (open-licence film research; low volume)"
- CACHE = os.path.join("research", ".cache")
- OPEN = {"cc0", "pd", "cc-by", "cc-by-sa", "nasa", "pixabay"}
- LIC_URL = {"cc0": "https://creativecommons.org/publicdomain/zero/1.0/",
- "pd": "https://creativecommons.org/publicdomain/mark/1.0/",
- "cc-by": "https://creativecommons.org/licenses/by/4.0/",
- "cc-by-sa": "https://creativecommons.org/licenses/by-sa/4.0/",
- "nasa": "https://www.nasa.gov/nasa-brand-center/images-and-media/",
- "pixabay": "https://pixabay.com/service/license-summary/"}
- SOURCE_NAME = {"wikimedia": "Wikimedia Commons", "archive": "Internet Archive", "aic": "Art Institute of Chicago", "polyhaven": "Poly Haven",
- "nasa": "NASA", "met": "The Metropolitan Museum of Art", "openverse": "Openverse", "pixabay": "Pixabay",
- "cleveland": "Cleveland Museum of Art", "rijks": "Rijksmuseum"}
- FIELDS = ["file", "title", "author", "source_url", "licence", "licence_url", "attribution_text", "modifications",
- "downloaded_at", "used_in", "notes"]
- _last = {} # host -> when its last request started: sources asked side by side never wait on each other
- HOST_DELAY = {"film-grab.com": 2.0} # seconds between requests; other hosts 0.5
- MAX_WAIT = [None] # --max-wait: a short wait and no second try, for a board the user waits on
- HOST_TIMEOUT = {"api.openverse.org": 60} # its audio search can take 10-25 s on an uncached query; others 25
- SHARED_PACE = {"film-grab.com": 1.0} # a board starts its searches at once: their API calls queue across processes
- def shared_pace(url):
- """Searches started side by side share one queue per rate-limited host, so six at once never meet a 429."""
- host = urllib.parse.urlparse(url).hostname or ""
- if host not in SHARED_PACE or "/wp-json/" not in url:
- return
- try:
- import fcntl
- except ImportError: # Windows: each process keeps its own pace
- return
- os.makedirs(CACHE, exist_ok=True)
- with open(os.path.join(CACHE, f".pace-{host}"), "a+") as f:
- fcntl.flock(f, fcntl.LOCK_EX)
- f.seek(0)
- try:
- last = float(f.read().strip() or 0)
- except ValueError:
- last = 0.0
- wait = last + SHARED_PACE[host] - time.time()
- if wait > 0:
- time.sleep(wait)
- f.seek(0)
- f.truncate()
- f.write(str(time.time()))
- import threading
- BUDGET = threading.local() # one deadline (and search: one wait) per source job, set in its thread
- PACE = threading.Lock()
- def wait_cap():
- """This thread's wait on one source (a search asks its sources side by side), else the run's --max-wait."""
- return getattr(BUDGET, "max_wait", None) or MAX_WAIT[0]
- DOWN_FOR = 1800 # a source that did not answer sits out this film's searches this long
- def down_until():
- try:
- with open(os.path.join(CACHE, "down.json")) as fh:
- return json.load(fh)
- except (OSError, ValueError):
- return {}
- def mark_down(name):
- d = down_until()
- d[name] = time.time() + DOWN_FOR
- os.makedirs(CACHE, exist_ok=True)
- with open(os.path.join(CACHE, "down.json"), "w") as fh:
- json.dump(d, fh)
- def get(url, as_json=True):
- key = hashlib.sha1(url.encode()).hexdigest()
- path = os.path.join(CACHE, key)
- if os.path.exists(path):
- with open(path, "rb") as fh:
- data = fh.read()
- else:
- host = urllib.parse.urlparse(url).hostname or ""
- with PACE:
- wait = _last.get(host, 0.0) + HOST_DELAY.get(host, 0.5) - time.time()
- _last[host] = time.time() + max(0.0, wait)
- if wait > 0:
- time.sleep(wait)
- req = urllib.request.Request(url, headers={"User-Agent": UA, "AIC-User-Agent": UA})
- timeout = wait_cap() or HOST_TIMEOUT.get(host, 25)
- deadline = getattr(BUDGET, "deadline", None)
- if deadline is not None:
- left = deadline - time.time()
- if left <= 0:
- raise TimeoutError("over its time")
- timeout = min(timeout, left)
- for attempt in ((0,) if deadline is not None else (0, 1)): # a budgeted probe never sleeps on a retry
- shared_pace(url)
- _last[host] = time.time()
- try:
- with urllib.request.urlopen(req, timeout=timeout) as r:
- data = r.read()
- break
- except urllib.error.HTTPError as e:
- if e.code != 429 or attempt or deadline is not None:
- raise
- after = int(e.headers.get("Retry-After") or 15) if str(e.headers.get("Retry-After") or 15).isdigit() else 15 # rate limited: wait once, then retry
- time.sleep(min(4, after) if wait_cap() else min(30, after))
- except (TimeoutError, socket.timeout, urllib.error.URLError) as e:
- timed_out = isinstance(e, (TimeoutError, socket.timeout)) or isinstance(getattr(e, "reason", None), (TimeoutError, socket.timeout))
- if not timed_out:
- raise # a real connection error (refused, DNS, SSL): not a timeout
- if attempt or wait_cap():
- raise TimeoutError("over its time") from e # normalise a stall to TimeoutError so callers keep the hits already collected
- # else: a slow search with no budget gets one more try (the loop continues)
- os.makedirs(CACHE, exist_ok=True)
- with open(path, "wb") as fh:
- fh.write(data)
- return json.loads(data) if as_json else data
- def clean(s, n=80):
- s = re.sub(r"<[^>]+>", "", str(s or ""))
- return re.sub(r"\s+", " ", s).strip()[:n]
- def norm_licence(text):
- t = (text or "").lower()
- if "cc0" in t or "zero" in t:
- return "cc0"
- if "public domain" in t or t.startswith("pd"):
- return "pd"
- if "nc" in t.replace("-", " ").split() or "nd" in t.replace("-", " ").split():
- return None
- if "by-sa" in t or "by sa" in t:
- return "cc-by-sa"
- if "cc by" in t or "cc-by" in t:
- return "cc-by"
- return None
- def rec(source, sid, title, creator, licence, page, file_url, thumb, kind):
- return {"source": source, "id": str(sid), "title": clean(title), "creator": clean(creator, 60) or "unknown",
- "licence": licence, "page": page, "file": file_url, "thumb": thumb, "type": kind}
- def src_wikimedia(q, n, kind):
- ft = "audio" if kind in ("sound", "music") else "video" if kind == "video" else "bitmap"
- p = {"action": "query", "format": "json", "generator": "search", "gsrsearch": f"{q} filetype:{ft}",
- "gsrnamespace": "6", "gsrlimit": n * 3, "prop": "imageinfo", "iiprop": "url|extmetadata",
- "iiurlwidth": "480", "iiextmetadatafilter": "LicenseShortName|LicenseUrl|Artist"}
- s = get("https://commons.wikimedia.org/w/api.php?" + urllib.parse.urlencode(p))
- out = []
- for page in sorted((s.get("query") or {}).get("pages", {}).values(), key=lambda x: x.get("index", 0)):
- ii = (page.get("imageinfo") or [{}])[0]
- md = ii.get("extmetadata") or {}
- short = (md.get("LicenseShortName") or {}).get("value") or ""
- lic = norm_licence(short)
- if lic:
- r = rec("wikimedia", page.get("pageid"), page.get("title", "").replace("File:", ""),
- (md.get("Artist") or {}).get("value"), lic, ii.get("descriptionurl"), ii.get("url"),
- ii.get("thumburl") if kind not in ("sound", "music") else None, kind)
- url = ((md.get("LicenseUrl") or {}).get("value") or "").strip()
- ver = re.search(r"(\d\.\d)", short) # keep the file's own licence version (CC BY 2.0 is not 4.0)
- if url.startswith("http"):
- r["licence_url"] = url
- elif ver and lic in ("cc-by", "cc-by-sa"):
- r["licence_url"] = f"https://creativecommons.org/licenses/{lic[3:]}/{ver.group(1)}/"
- if short:
- r["licence_name"] = short
- out.append(r)
- return out[:n]
- def src_aic(q, n, kind):
- s = get("https://api.artic.edu/api/v1/artworks/search?" + urllib.parse.urlencode(
- {"q": q, "query[term][is_public_domain]": "true", "limit": n,
- "fields": "id,title,artist_display,image_id,is_public_domain,thumbnail"}))
- base = (s.get("config") or {}).get("iiif_url", "https://www.artic.edu/iiif/2")
- def size(d): # the original's own width up to 3000 px; its IIIF server honours only a width ("max" and boxes are not)
- w = (d.get("thumbnail") or {}).get("width")
- return f"{min(3000, w)}," if isinstance(w, int) and w > 0 else "843,"
- return [rec("aic", d["id"], d.get("title"), (d.get("artist_display") or "").split("\n")[0], "cc0",
- f"https://www.artic.edu/artworks/{d['id']}", f"{base}/{d['image_id']}/full/{size(d)}/0/default.jpg",
- f"{base}/{d['image_id']}/full/200,/0/default.jpg", "image")
- for d in s.get("data", []) if d.get("image_id") and d.get("is_public_domain")]
- def src_polyhaven(q, n, kind):
- t = {"hdri": "hdris", "texture": "textures"}.get(kind, "all")
- s = get(f"https://api.polyhaven.com/assets?type={t}")
- words = [w.lower() for w in q.split()]
- scored = []
- for aid, a in s.items():
- hay = " ".join([aid, a.get("name", "")] + a.get("tags", []) + a.get("categories", [])).lower()
- score = sum(w in hay for w in words)
- if score:
- scored.append((-score, -a.get("download_count", 0), aid, a))
- return [rec("polyhaven", aid, a.get("name"), ", ".join(a.get("authors", {}).keys()), "cc0",
- f"https://polyhaven.com/a/{aid}", f"https://api.polyhaven.com/files/{aid}",
- f"https://cdn.polyhaven.com/asset_img/thumbs/{aid}.png?width=256",
- {0: "hdri", 1: "texture", 2: "model"}.get(a.get("type"), kind))
- for _, _, aid, a in sorted(scored)[:n]]
- def src_nasa(q, n, kind):
- s = get("https://images-api.nasa.gov/search?" + urllib.parse.urlencode({"q": q, "media_type": "image", "page_size": n}))
- out = []
- for it in s.get("collection", {}).get("items", [])[:n]:
- d = (it.get("data") or [{}])[0]
- nid = urllib.parse.quote(d.get("nasa_id") or "")
- out.append(rec("nasa", d.get("nasa_id"), d.get("title"), d.get("photographer") or d.get("center") or "NASA", "nasa",
- f"https://images.nasa.gov/details/{nid}", f"https://images-api.nasa.gov/asset/{nid}",
- (it.get("links") or [{}])[0].get("href"), "image"))
- return out
- def src_met(q, n, kind):
- s = get("https://collectionapi.metmuseum.org/public/collection/v1.1/search?" + urllib.parse.urlencode(
- {"q": q, "hasImages": "true", "limit": n * 4}))
- out = []
- for oid in (s.get("objectIDs") or [])[: n * 4]:
- try:
- o = get(f"https://collectionapi.metmuseum.org/public/collection/v1/objects/{oid}")
- except urllib.error.HTTPError as e: # withdrawn object ids answer 404: skip them; a timeout or a 429 is not "none"
- if e.code == 404:
- continue
- raise
- except (TimeoutError, socket.timeout): # out of time: keep what was found, else let the caller (supply) see the timeout
- if out:
- break
- raise
- if o.get("isPublicDomain") and o.get("primaryImageSmall"):
- out.append(rec("met", oid, o.get("title"), o.get("artistDisplayName") or o.get("culture"), "cc0",
- o.get("objectURL"), o.get("primaryImage"), o.get("primaryImageSmall"), "image"))
- if len(out) >= n:
- break
- return out
- def src_cleveland(q, n, kind):
- s = get("https://openaccess-api.clevelandart.org/api/artworks/?" + urllib.parse.urlencode(
- {"q": q, "has_image": 1, "cc0": 1, "limit": n}))
- out = []
- for d in s.get("data") or []:
- im = d.get("images") or {}
- big, small = (im.get("print") or im.get("web") or {}).get("url"), (im.get("web") or {}).get("url")
- if d.get("share_license_status") == "CC0" and big and small:
- out.append(rec("cleveland", d.get("id"), d.get("title"), ((d.get("creators") or [{}])[0] or {}).get("description"),
- "cc0", d.get("url"), big, small, "image"))
- return out[:n]
- RIJKS_EN = "http://vocab.getty.edu/aat/300388277" # Linked Art's tag for English text
- RIJKS_LIC = {"publicdomain/zero": "cc0", "publicdomain/mark": "pd"}
- def rijks_record(o):
- def text(items): # the English wording when there is one
- items = [i for i in items if i.get("content")]
- pick = next((i for i in items if any(l.get("id") == RIJKS_EN for l in i.get("language") or [])), None)
- return (pick or (items[0] if items else {})).get("content")
- ids = o.get("identified_by") or []
- number = next((i.get("content") for i in ids if i.get("type") == "Identifier" and i.get("content")), None)
- for s in o.get("subject_of") or []:
- for dc in s.get("digitally_carried_by") or []:
- terms = " ".join(str(r.get("content")) for r in dc.get("referred_to_by") or [])
- lic = next((v for k, v in RIJKS_LIC.items() if k in terms), None)
- img = next((a.get("id") for a in dc.get("access_point") or []
- if str(a.get("id")).startswith("https://iiif.micr.io/")), None)
- if lic and img and number:
- base = img.split("/full/")[0]
- return rec("rijks", number, text([i for i in ids if i.get("type") == "Name"]),
- text((o.get("produced_by") or {}).get("referred_to_by") or []), lic,
- f"https://www.rijksmuseum.nl/en/collection/{urllib.parse.quote(number)}",
- f"{base}/full/!3400,3400/0/default.jpg", f"{base}/full/400,/0/default.jpg", "image")
- return None
- def src_rijks(q, n, kind):
- s = get("https://data.rijksmuseum.nl/search/collection?" + urllib.parse.urlencode({"title": q, "imageAvailable": "true"}))
- out = []
- for it in (s.get("orderedItems") or [])[: n * 3]:
- oid = str(it.get("id") or "")
- if not oid.startswith("https://id.rijksmuseum.nl/"): # follow only the museum's own object ids
- continue
- try:
- o = get(oid)
- except urllib.error.HTTPError as e:
- if e.code == 404:
- continue
- raise
- except (TimeoutError, socket.timeout): # out of time: keep what was found, else let the caller (supply) see the timeout
- if out:
- break
- raise
- r = rijks_record(o)
- if r:
- out.append(r)
- if len(out) >= n:
- break
- return out
- OV_ALLOWED = set() # set by search(): the licences this run keeps
- OV_LIC = {"cc0": "cc0", "pdm": "pd", "by": "cc-by", "by-sa": "cc-by-sa"}
- def src_openverse(q, n, kind):
- media = "audio" if kind in ("sound", "music") else "images"
- params = {"q": q, "license": ",".join(OV_LIC), "page_size": n, "mature": "false"}
- if kind == "music":
- params["category"] = "music" # Jamendo tracks; without it, audio is mostly Freesound and Wikimedia
- params["license"] = ",".join(k for k, v in OV_LIC.items() if v in OV_ALLOWED) # most music is BY-SA: ask the API
- found = get(f"https://api.openverse.org/v1/{media}/?" + urllib.parse.urlencode(params)).get("results", [])
- if not found and " " in q.strip(): # every word must match (no OR syntax): try the words one by one
- for w in sorted(set(q.split()), key=len, reverse=True)[:3]:
- try:
- found += [d for d in get(f"https://api.openverse.org/v1/{media}/?" + urllib.parse.urlencode(dict(params, q=w))).get(
- "results", []) if d.get("id") not in {x.get("id") for x in found}]
- except (TimeoutError, socket.timeout): # out of time: keep what was found, else let the caller (supply) see the timeout
- if found:
- break
- raise
- if len(found) >= n:
- break
- out = []
- for d in found:
- lic = OV_LIC.get(d.get("license"))
- if not lic:
- continue
- r = rec("openverse", d.get("id"), d.get("title"), d.get("creator"), lic, d.get("foreign_landing_url"),
- d.get("url"), d.get("thumbnail") if media == "images" else None, kind)
- r.update({"licence_url": d.get("license_url"), "attribution": d.get("attribution"),
- "provider": d.get("source") or d.get("provider")})
- if d.get("duration"):
- r["duration"] = round(d["duration"] / 1000, 1)
- out.append(r)
- return out[:n]
- def src_filmgrab(q, n, kind):
- api = "https://film-grab.com/wp-json/wp/v2"
- params = {"per_page": min(n, 10), "_fields": "id,link,title,featured_media,categories"}
- if q.startswith("cat:"):
- want = q[4:].strip().lower()
- cats = get(f"{api}/categories?" + urllib.parse.urlencode({"search": want, "per_page": 20, "_fields": "id,name,count"}))
- if not cats:
- return []
- exact = [c for c in cats if html.unescape(c["name"]).lower() == want]
- params["categories"] = (exact or [max(cats, key=lambda c: c.get("count", 0))])[0]["id"]
- else: # a film title: stills from across that one film, not one per film
- params.update(search=q, per_page=10, _fields=params["_fields"] + ",content")
- posts = get(f"{api}/posts?" + urllib.parse.urlencode(params))
- if posts and "categories" not in params: # the search matches any word on a page: keep only the film named
- norm = lambda t: re.sub(r"[^a-z0-9]+", " ", html.unescape(t).lower().replace("the ", "")).strip()
- named = [p_ for p_ in posts if norm((p_.get("title") or {}).get("rendered", "")) == norm(q)]
- if not named:
- print(f"filmgrab: no film titled \"{q}\" (the search found: " + ", ".join(
- html.unescape((p_.get("title") or {}).get("rendered", "")) for p_ in posts[:5]) + "); check the title",
- file=sys.stderr)
- return []
- post, title = named[0], html.unescape((named[0].get("title") or {}).get("rendered", ""))
- body = (post.get("content") or {}).get("rendered", "")
- stills = list(dict.fromkeys(u.split("?")[0] for u in re.findall(
- r'src="(https://film-grab\.com/wp-content/uploads/photo-gallery/thumb/[^"]+)"', body)))
- if stills:
- picks = [stills[round(i * (len(stills) - 1) / max(n - 1, 1))] for i in range(min(n, len(stills)))]
- return [dict(rec("filmgrab", f"{post['id']}-{i}", title, "", "mood-only", post.get("link"), None,
- urllib.parse.quote(u, safe=":/"), "still"), use="mood-only")
- for i, u in enumerate(dict.fromkeys(picks))]
- if not posts:
- return []
- cat_ids = sorted({c for p_ in posts for c in (p_.get("categories") or [])[:12]})
- media_ids = [p_["featured_media"] for p_ in posts if p_.get("featured_media")]
- cats = {c["id"]: html.unescape(c["name"]) for c in get(f"{api}/categories?" + urllib.parse.urlencode(
- {"include": ",".join(map(str, cat_ids)), "_fields": "id,name", "per_page": 100}))} if cat_ids else {}
- media = {m["id"]: m for m in get(f"{api}/media?" + urllib.parse.urlencode(
- {"include": ",".join(map(str, media_ids)), "_fields": "id,source_url,media_details", "per_page": 100}))} if media_ids else {}
- out = []
- for post in posts: # three requests per search in all: posts, their categories, their stills
- names = [cats[c] for c in (post.get("categories") or [])[:12] if c in cats]
- year = next((x for x in names if re.fullmatch(r"(18|19|20)\d\d", x)), "")
- people = [x for x in names if x != year and not re.search(r"\d", x)][:2]
- m = media.get(post.get("featured_media")) or {}
- sizes = (m.get("media_details") or {}).get("sizes") or {}
- thumb = next((sizes[k]["source_url"] for k in ("medium_large", "medium", "thumbnail") if k in sizes),
- m.get("source_url"))
- r = rec("filmgrab", post["id"], html.unescape((post.get("title") or {}).get("rendered", "")), ", ".join(people),
- "mood-only", post.get("link"), None, thumb, "still")
- out.append(dict(r, year=year, use="mood-only"))
- return out
- def src_pixabay(q, n, kind):
- """Pixabay's stock photos and videos (Pixabay Content License: free for commercial use, no credit owed, never sold or
- shared as files). Its search reaches far, so a hit's tags must name a word of the query; AI-generated pictures,
- cartoons and 3D renders are left out, since stock answers what the real world looks like."""
- if kind not in ("image", "video"):
- return []
- import keys
- key = keys.get("PIXABAY_API_KEY")
- if not key:
- raise RuntimeError("needs a free key: tools/keys.py open PIXABAY_API_KEY")
- base = "https://pixabay.com/api/videos/" if kind == "video" else "https://pixabay.com/api/"
- try:
- s = get(base + "?" + urllib.parse.urlencode({"key": key, "q": q[:100], "per_page": max(3, min(200, n * 3)),
- "safesearch": "true", ("video_type" if kind == "video" else "image_type"):
- "film" if kind == "video" else "photo"}))
- except Exception as e: # an error can carry the request's address, and the key in it
- raise RuntimeError(str(e).replace(key, "<key>").replace(urllib.parse.quote(key), "<key>")) from None
- words = [w for w in re.findall(r"\w+", q.lower()) if len(w) > 2]
- out = []
- for h in s.get("hits", []):
- tags = (h.get("tags") or "").lower()
- if (words and not any(w in tags for w in words)) or \
- re.search(r"\bai[- ]generated\b|\bgenerative\b|\bcartoon|\banimation\b|\b3d\b|\brender", tags):
- continue
- if kind == "video":
- sizes = [v for v in ((h.get("videos") or {}).get(k) or {} for k in ("large", "medium", "small", "tiny")) if v.get("url")]
- pick = next((v for v in sizes if (v.get("width") or 0) <= 1920), sizes[-1] if sizes else None)
- if not pick:
- continue
- r = rec("pixabay", h.get("id"), tags, h.get("user"), "pixabay", h.get("pageURL"), pick["url"],
- next((v.get("thumbnail") for v in reversed(sizes) if v.get("thumbnail")), None), "video")
- r["duration"] = h.get("duration")
- else:
- r = rec("pixabay", h.get("id"), tags, h.get("user"), "pixabay", h.get("pageURL"),
- h.get("largeImageURL") or h.get("webformatURL"), h.get("webformatURL") or h.get("previewURL"), "image")
- r["licence_url"], r["licence_name"] = LIC_URL["pixabay"], "Pixabay Content License"
- r["attribution"] = f'"{r["title"]}" by {r["creator"]} on Pixabay (Pixabay Content License)'
- out.append(r)
- if len(out) >= n:
- break
- return out
- def src_archive(q, n, kind):
- """The Internet Archive's recordings and films: public domain, CC0 and CC BY only (no NC, no ND), one playable file
- each."""
- if kind not in ("sound", "music", "video"):
- return []
- media = "movies" if kind == "video" else "audio"
- where = " AND collection:(jamendo-albums OR netlabels)" if kind == "music" else "" # music: released tracks, not radio shows
- query = f"({q}){where} AND mediatype:({media}) AND " + r"licenseurl:(*\/licenses\/by\/* OR *publicdomain*)" # usable rows only
- s = get("https://archive.org/advancedsearch.php?" + urllib.parse.urlencode(
- [("q", query), ("fl[]", "identifier"), ("fl[]", "title"), ("fl[]", "creator"), ("fl[]", "licenseurl"),
- ("rows", n * 8), ("output", "json")]))
- out = []
- for d in (s.get("response") or {}).get("docs", []):
- url = str(d.get("licenseurl") or "")
- lic = "cc0" if "zero" in url else "pd" if "publicdomain" in url else "cc-by" if "/licenses/by/" in url else None
- if not lic:
- continue
- try:
- meta = get(f"https://archive.org/metadata/{urllib.parse.quote(d['identifier'])}")
- except (TimeoutError, socket.timeout): # out of time: keep what was found, else let the caller (supply) see the timeout
- if out:
- break
- raise
- playable = ("h.264", "h.264 IA", "MPEG4", "512Kb MPEG4") if kind == "video" else ("VBR MP3", "MP3", "128Kbps MP3", "Ogg Vorbis")
- files = [f for f in meta.get("files", []) if f.get("format") in playable]
- if not files:
- continue
- creator = d.get("creator")
- r = rec("archive", d["identifier"], d.get("title"), creator[0] if isinstance(creator, list) else creator, lic,
- f"https://archive.org/details/{d['identifier']}",
- f"https://archive.org/download/{d['identifier']}/{urllib.parse.quote(files[0]['name'])}",
- f"https://archive.org/services/img/{d['identifier']}" if kind == "video" else None, kind)
- r["licence_url"] = url
- out.append(r)
- if len(out) >= n:
- break
- return out
- SOURCES = {"wikimedia": src_wikimedia, "archive": src_archive, "aic": src_aic, "met": src_met, "openverse": src_openverse,
- "polyhaven": src_polyhaven, "nasa": src_nasa, "filmgrab": src_filmgrab, "pixabay": src_pixabay,
- "cleveland": src_cleveland, "rijks": src_rijks}
- DEFAULT = {"image": "wikimedia,aic,cleveland,nasa,pixabay", "sound": "wikimedia,openverse", "music": "archive,openverse",
- "hdri": "polyhaven", "texture": "polyhaven", "video": "pixabay,wikimedia,archive"}
- def contact_sheet(results, out):
- thumbs, shown = [], []
- os.makedirs(os.path.join(out, "thumbs"), exist_ok=True)
- for r in results:
- if not r.get("thumb"):
- continue
- p = os.path.join(out, "thumbs", f"{r['n']:02d}.img")
- src = r["thumb"]
- try:
- if os.path.exists(src): # a local file (the user's refs/): read it, never download it
- data = None
- if os.path.abspath(src) != os.path.abspath(p):
- with open(src, "rb") as source:
- data = source.read()
- else: # always this result's own (cached) thumb: a reused number never shows an old image
- data = get(src, as_json=False)
- if data is not None:
- with open(p + ".part", "wb") as destination:
- destination.write(data)
- os.replace(p + ".part", p)
- thumbs.append(p)
- shown.append(r["n"])
- except Exception as e:
- print(f"thumb {r['n']}: skipped ({str(e)[:80]})")
- if not thumbs:
- return None
- try:
- cols = min(4, len(thumbs))
- rows = (len(thumbs) + cols - 1) // cols
- cmd = ["ffmpeg", "-v", "error", "-y"]
- for p in thumbs:
- cmd += ["-i", p]
- f = "".join(f"[{i}]scale=200:200:force_original_aspect_ratio=decrease,pad=200:200:(ow-iw)/2:(oh-ih)/2,setsar=1[t{i}];"
- for i in range(len(thumbs)))
- layout = "|".join(f"{(i % cols) * 200}_{(i // cols) * 200}" for i in range(len(thumbs)))
- f += "".join(f"[t{i}]" for i in range(len(thumbs))) + \
- (f"xstack=inputs={len(thumbs)}:layout={layout}:fill=black" if len(thumbs) > 1 else "null")
- sheet = os.path.join(out, "sheet.jpg")
- subprocess.run(cmd + ["-filter_complex", f, "-frames:v", "1", "-q:v", "5", sheet], check=True,
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- return sheet, cols, shown
- except Exception:
- return None
- def supply(a):
- """What the open archives hold for each key element, before any download: one metadata query per element and
- source, licences filtered, nothing fetched. A real person, team, event or brand often has almost nothing open; say
- so at once with the numbers and the routes, instead of searching for hours."""
- allowed = OPEN
- OV_ALLOWED.clear(); OV_ALLOWED.update(allowed)
- sources = (a.sources or "wikimedia,met,aic").split(",")
- print("supply (open licence only, metadata, nothing downloaded):")
- MAX_WAIT[0] = MAX_WAIT[0] or 10 # a probe answers in seconds: a slow source counts as skipped
- def ask(job):
- q, name = job
- BUDGET.deadline = time.time() + MAX_WAIT[0] # the whole source, however many requests it makes
- try:
- return job, [r for r in SOURCES[name](q, a.n, "image") if r["licence"] in allowed]
- except Exception as e:
- return job, f"skipped ({str(e)[:40]})"
- finally:
- BUDGET.deadline = None
- from concurrent.futures import ThreadPoolExecutor
- with ThreadPoolExecutor(max_workers=8) as pool:
- found = dict(pool.map(ask, [(q, name) for q in a.q for name in sources]))
- verdicts = []
- for q in a.q:
- counts, titles = {}, set()
- for name in sources:
- hits = found[(q, name)]
- if isinstance(hits, str):
- counts[name] = hits
- continue
- fresh = [r for r in hits if r["title"].lower()[:40] not in titles]
- titles.update(r["title"].lower()[:40] for r in fresh)
- counts[name] = len(fresh)
- total = len(titles)
- slow = [k for k, v in counts.items() if isinstance(v, str)]
- verdict = "enough" if total >= 8 else ("not judged yet" if slow else "thin" if total else "none")
- verdicts.append((q, verdict, slow))
- print(f" {q[:44]:44s} " + " · ".join(f"{k} {v}" for k, v in counts.items()) + f" -> {verdict} ({total})")
- late = sorted({s for _, v, slow in verdicts if v == "not judged yet" for s in slow})
- if late:
- print("Not judged yet: " + "; ".join(q for q, v, _ in verdicts if v == "not judged yet") + f" ({', '.join(late)} "
- "did not answer in time). Search them patiently in the background with --patient "
- f"(asset_search.py search --patient --sources {','.join(late)} --q …), and never tell the user anything is "
- Note: Quoted as data in code: Tells the agent to keep something from the user
- Line 650 on GitHub
- "missing before that search has answered.")
- gaps = [q for q, v, _ in verdicts if v in ("thin", "none")]
- if gaps:
- print("Tell the user now, with these numbers: the open archives are thin or empty for " + "; ".join(gaps)
- + ". Routes: their own licensed material in assets/ (an agency, a private collection, a broadcaster), a design-led film "
- "(type, numbers, maps, recreated places), or a mix. Searching longer does not find what "
- "the archives do not hold.")
- def search(a):
- if a.type == "typography": # mood references: type_refs.py (Fonts In Use, Art of the Title, Typewolf, Are.na)
- import type_refs
- type_refs.search(a.q, a.n, a.sources, a.out, a.purpose)
- return
- allowed = set(a.licence.split(",")) if a.licence else (OPEN - {"cc-by-sa"} if a.type == "music" else OPEN)
- OV_ALLOWED.clear(); OV_ALLOWED.update(allowed)
- results, seen = [], set()
- names = (a.sources or DEFAULT[a.type]).split(",")
- patient = getattr(a, "patient", False) # --patient: every source in full, for a background run; the foreground never waits unbounded
- win = lambda nm: a.max_wait or (30 if nm == "openverse" else 20) # seconds on one source; Openverse audio answers in 10-25 s
- down = {} if (a.sources or patient) else down_until() # a source named with --sources is always asked
- asked = []
- for name in names:
- if down.get(name, 0) > time.time():
- back = time.strftime("%H:%M", time.localtime(down[name]))
- print(f"{name}: skipped (it did not answer a search here lately; asked again from {back}, or now with --sources {name})")
- else:
- asked.append(name)
- def ask(name): # each source in its own thread, with its own wait
- BUDGET.deadline = None if patient else time.time() + win(name)
- BUDGET.max_wait = None if patient else win(name)
- try:
- return list(SOURCES[name](a.q, a.n, a.type)), None
- except Exception as e:
- return [], e
- finally:
- BUDGET.deadline = BUDGET.max_wait = None
- with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, len(asked))) as pool:
- answers = dict(zip(asked, pool.map(ask, asked))) # side by side: a search takes as long as its slowest source
- for name in asked:
- found, err = answers[name]
- if err is not None:
- print(f"{name}: skipped ({str(err)[:80]})")
- if isinstance(err, (TimeoutError, socket.timeout)) and not patient:
- mark_down(name)
- for r in found:
- key = (r["source"], r["id"])
- if (r["licence"] in allowed or r.get("use") == "mood-only") and key not in seen:
- seen.add(key)
- results.append(r)
- used = {}
- if a.type == "sound":
- results, used = used_lately(results)
- for i, r in enumerate(results, 1):
- r["n"] = i
- src = r["source"] + (f"/{r['provider']}" if r.get("provider") and r["provider"] != r["source"] else "")
- dur = f" · {r['duration']:.0f} s" if r.get("duration") else ""
- key = f"{r['source']}:{r['id']}"
- mark = f" · used in {used[key]}" if key in used else ""
- print(f"{i:>2}. [{src}] {r['title'][:60]} · {r['creator'][:30]} · {r['licence']}{dur}{mark}")
- os.makedirs(a.out, exist_ok=True)
- json.dump({"query": a.q, "type": a.type, "results": results}, open(os.path.join(a.out, "results.json"), "w"), indent=1)
- BUDGET.max_wait = None if patient else (a.max_wait or 20) # a stalled thumbnail gets one short try, like each source
- try:
- sheet = contact_sheet(results, a.out) if a.type not in ("sound", "music") else None
- finally:
- BUDGET.max_wait = None
- print(f"{len(results)} results -> {a.out}/results.json" +
- (f"; sheet {sheet[0]} ({sheet[1]} per row, row by row = results {','.join(map(str, sheet[2]))})" if sheet else ""))
- def tiny(path):
- """16x16 grey bytes of an image, to spot the same picture arriving twice (from two archives, or as two sizes)."""
- raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=16:16,format=gray", "-f", "rawvideo", "-"],
- capture_output=True).stdout
- return raw if len(raw) == 256 else None
- def page(img, captions=()):
- """A page beside an image that shows it at full width, with optional numbered captions above it. Its path, clicked
- in the Claude Code desktop app, opens it big in the app's own browser pane (elsewhere in the browser); the app does
- not show images inside a chat message."""
- import html as _h
- p = os.path.splitext(str(img))[0] + ".html"
- name = _h.escape(os.path.basename(str(img)))
- caps = "".join(f"<li>{_h.escape(c)}</li>" for c in captions)
- open(p, "w", encoding="utf-8").write(
- f'<!doctype html><meta charset=utf-8><title>{name}</title><style>body{{margin:0;background:#111;color:#eee;'
- f'font:18px/1.5 -apple-system,Helvetica,Arial,sans-serif}}ul{{margin:0;padding:14px 18px;list-style:none}}'
- f'img{{display:block;width:100%;height:auto}}</style>' + (f"<ul>{caps}</ul>" if caps else "") +
- f'<img src="{name}">')
- return os.path.abspath(p)
- def show(path):
- """Put a board, a sheet or a film in front of the user: Preview on macOS, the default viewer elsewhere.
- CINECODE_NO_OPEN=1 turns it off (tests, servers)."""
- if os.environ.get("CINECODE_NO_OPEN") or not os.path.exists(str(path)):
- return False
- if not os.environ.get("CINECODE_OPEN"):
- return False # nothing opens a window: paths go into the message; CINECODE_OPEN=1 opens them
- try:
- if sys.platform == "darwin":
- subprocess.Popen(["open", str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- elif sys.platform.startswith("win"):
- os.startfile(str(path))
- elif shutil.which("xdg-open") and (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
- subprocess.Popen(["xdg-open", str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- else:
- return False
- except OSError:
- return False
- return True
- def board(a):
- results, prints, dropped = [], [], []
- os.makedirs(os.path.join(a.out, "thumbs"), exist_ok=True)
- def add(r, src_thumb):
- fp = tiny(src_thumb) if src_thumb and os.path.exists(src_thumb) else None
- if fp and any(sum(abs(x - y) for x, y in zip(fp, q)) / 256 < 10 for q in prints):
- dropped.append(r.get("title", "")[:30])
- return
- if fp:
- prints.append(fp)
- r = dict(r, n=len(results) + 1)
- dst = os.path.join(a.out, "thumbs", f"{r['n']:02d}.img")
- if src_thumb and os.path.exists(src_thumb):
- shutil.copyfile(src_thumb, dst)
- results.append(r)
- drop = {}
- for item in a.drop or []: # "<folder>:1,4": leave out results 1 and 4 of that search
- folder, _, nums = item.partition(":")
- drop.setdefault(folder.rstrip("/").split("/")[-1], set()).update(int(x) for x in nums.split(",") if x.strip().isdigit())
- for d in a.dirs or []:
- found = json.load(open(os.path.join(d, "results.json")))["results"]
- gone = drop.get(os.path.basename(d.rstrip("/")), set())
- for r in [r for r in found if r.get("thumb") and r.get("n") not in gone][:a.per]:
- add(dict(r, element=os.path.basename(d.rstrip("/"))), os.path.join(d, "thumbs", f"{r['n']:02d}.img"))
- if a.refs and os.path.isdir(a.refs):
- for f in sorted(os.listdir(a.refs)):
- if f.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
- p = os.path.join(a.refs, f)
- add(dict(rec("user", f, f, "user", "user", p, p, p, "image"), element="user"), p)
- for r in results:
- print(f"{r['n']:>2}. {r['element'][:14]:<14} [{r['source']}] {r['title'][:50]} · {r['licence']}")
- if dropped:
- print(f"left out as the same picture again: {', '.join(dropped)}")
- json.dump({"query": "board", "type": "image", "results": results}, open(os.path.join(a.out, "results.json"), "w"),
- separators=(",", ":"))
- sheet = contact_sheet(results, a.out)
- if not sheet:
- sys.exit("board: no thumbnails")
- print(f"{len(results)} references -> {a.out}/results.json; sheet {sheet[0]} ({sheet[1]} per row) · show the user: {os.path.abspath(sheet[0])} (Claude Code: SendUserFile with display 'render', it opens big in the side panel; elsewhere the page {page(sheet[0])} in your message)"
- + (" · opened on the user's screen" if show(sheet[0]) else ""))
- raw = subprocess.run(["ffmpeg", "-v", "error", "-i", sheet[0], "-vf", "scale=32:32", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
- capture_output=True).stdout
- bins = {}
- for i in range(0, len(raw) - 2, 3):
- r, g, b = (raw[i] >> 5, raw[i + 1] >> 5, raw[i + 2] >> 5)
- if r + g + b > 0: # leave out the black padding
- bins[(r, g, b)] = bins.get((r, g, b), 0) + 1
- top = sorted(bins, key=bins.get, reverse=True)[:6]
- print("palette: " + " ".join("#%02x%02x%02x" % tuple(c * 32 + 16 for c in k) for k in top))
- def file_url(r, variant):
- if r["source"] == "polyhaven":
- files = get(r["file"])
- res, fmt = (variant or "2k:hdr").split(":")
- for k in ("hdri", "Diffuse", "diff"):
- node = (files.get(k) or {}).get(res)
- if isinstance(node, dict):
- pick = node.get(fmt) or next(iter(node.values()))
- if isinstance(pick, dict) and "url" in pick:
- return pick["url"]
- raise RuntimeError("no file for that variant; try --variant 1k:jpg or 2k:hdr")
- if r["source"] == "nasa":
- hrefs = [i["href"] for i in get(r["file"]).get("collection", {}).get("items", [])]
- for tag in ("~large", "~orig", "~medium"):
- for h in hrefs:
- if tag in h and h.lower().endswith((".jpg", ".jpeg", ".png")):
- return h
- return hrefs[0]
- return r["file"]
- def preview(url, path, secs):
- """The first `secs` of a track: ffmpeg reads the stream and stops, so the rest is never downloaded; without
- ffmpeg, the first bytes (about 30 s of a 320 kbps MP3 per 1.2 MB)."""
- if shutil.which("ffmpeg"):
- agent = ["-user_agent", UA] if url.startswith("http") else []
- fmt = {".mka": "matroska", ".oga": "ogg", ".m4a": "ipod"}.get(os.path.splitext(path)[1], None)
- subprocess.run(["ffmpeg", "-v", "error", "-y", *agent, "-t", str(secs), "-i", url, "-map", "0:a:0", "-c", "copy",
- *(["-f", fmt] if fmt else []), path + ".part" + os.path.splitext(path)[1]], check=True, timeout=120)
- os.replace(path + ".part" + os.path.splitext(path)[1], path)
- return
- req = urllib.request.Request(url, headers={"User-Agent": UA, "Range": f"bytes=0-{int(secs * 40000)}"})
- with urllib.request.urlopen(req, timeout=60) as resp, open(path + ".part", "wb") as f:
- f.write(resp.read())
- os.replace(path + ".part", path)
- def sound_cache(r, ext):
- """A fetched sound also lands in the cache every film shares (sounds.py), so the next film copies it instead of
- downloading it again; None for other kinds."""
- if r.get("type") != "sound":
- return None
- try:
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
- import sounds
- except ImportError:
- return None
- return sounds.CACHE / "found" / f"{r['source']}-{r['id']}{ext}".replace("/", "-")
- def used_lately(results):
- """Sounds your last films used go after the rest, marked, so the shared cache never becomes the same sounds."""
- try:
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
- import sounds
- except ImportError:
- return results, {}
- used = sounds.recent()
- return sorted(results, key=lambda r: f"{r['source']}:{r['id']}" in used), used
- def fetch(a):
- data = json.load(open(a.results, encoding="utf-8"))
- by_n = {r["n"]: r for r in data["results"]}
- os.makedirs(a.dest, exist_ok=True)
- new = not os.path.exists(a.licenses) or os.path.getsize(a.licenses) == 0
- rows = []
- picks = [int(x) for x in a.pick.split(",")]
- deadline = time.time() + max(90, 30 * len(picks)) # a loose total backstop so a batch of dead links never hangs
- fails, down = {}, set() # connection failures in a row per source; a source found down (3 in a row) is skipped
- for n in picks:
- if time.time() >= deadline:
- print(f"{n}+: not fetched (the fetch spent its time; try again or another source)")
- break
- r = by_n.get(n)
- if not r:
- print(f"{n}: not in results")
- continue
- if r["source"] in down:
- print(f"{n}: skipped ({r['source']} is unreachable right now)")
- continue
- if r.get("use") == "mood-only" or r.get("licence") == "mood-only":
- print(f"{n}: mood-only reference (link and thumbnail for study): never fetched into the film")
- continue
- try:
- url = file_url(r, a.variant)
- ext = os.path.splitext(urllib.parse.urlparse(url).path)[1][:6] or ".bin"
- slug = re.sub(r"[^a-z0-9]+", "-", r["title"].lower()).strip("-")[:40] or "asset"
- path = os.path.join(a.dest, f"{r['source']}-{r['id']}-{slug}{ext}".replace("/", "-"))
- if os.path.exists(path):
- print(f"{n}: already here: {path}")
- fails.pop(r["source"], None)
- continue
- if a.preview and r.get("type") in ("sound", "music"):
- ext = ext if ext.lower() in (".mp3", ".ogg", ".oga", ".opus", ".flac", ".wav", ".m4a", ".aac") else ".mka"
- path = os.path.splitext(path)[0] + f"-preview{ext}"
- if not os.path.exists(path):
- preview(url, path, a.preview)
- print(f"{n}: {path} · first {a.preview:g} s, for listening (no licence row; fetch the pick without --preview)")
- fails.pop(r["source"], None)
- continue
- shared = sound_cache(r, ext)
- if shared and shared.exists():
- shutil.copyfile(shared, path)
- print(f"{n}: from the shared sound cache (downloaded for an earlier film)")
- else:
- req = urllib.request.Request(url, headers={"User-Agent": UA, "AIC-User-Agent": UA}) # AIC's image server refuses a file without it
- with urllib.request.urlopen(req, timeout=90) as resp, open(path + ".part", "wb") as f:
- while chunk := resp.read(1 << 20):
- f.write(chunk)
- os.replace(path + ".part", path)
- if shared:
- shared.parent.mkdir(parents=True, exist_ok=True)
- shutil.copyfile(path, shared)
- if shared:
- import sounds
- sounds.remember(f"{r['source']}:{r['id']}")
- deadline = max(deadline, time.time() + max(90, 30 * len(picks))) # a healthy fetch refreshes the budget
- except urllib.error.HTTPError as e:
- print(f"{n}: failed (the file is gone, HTTP {e.code})") # the source answered; only this file is missing
- fails.pop(r["source"], None)
- continue
- except (urllib.error.URLError, TimeoutError, socket.timeout) as e:
- fails[r["source"]] = fails.get(r["source"], 0) + 1
- print(f"{n}: failed ({str(getattr(e, 'reason', e))[:70]})")
- if fails[r["source"]] >= 3:
- down.add(r["source"])
- print(f"{r['source']} looks unreachable (3 failures in a row) — skipping its remaining picks; other sources continue")
- continue
- except Exception as e:
- print(f"{n}: failed ({str(e)[:80]})")
- continue
- fails.pop(r["source"], None)
- lic = {"cc0": "CC0", "pd": "Public domain", "cc-by": "CC BY", "cc-by-sa": "CC BY-SA", "nasa": "Courtesy NASA",
- "pixabay": "Pixabay Content License"}[r["licence"]]
- rows.append({"file": path, "title": r["title"], "author": r["creator"], "source_url": r["page"],
- "licence": r["licence"], "licence_url": r.get("licence_url") or LIC_URL[r["licence"]],
- "attribution_text": r.get("attribution") or f'"{r["title"]}" by {r["creator"]}, {SOURCE_NAME[r["source"]]}, {lic}',
- "modifications": "", "downloaded_at": datetime.date.today().isoformat(), "used_in": "",
- "notes": f"type={r['type']}; source={r['source']}" + (f"; via {r['provider']}" if r.get("provider") else "")})
- print(f"{n}: {path} · {r['licence']}")
- if rows:
- with open(a.licenses, "a", newline="", encoding="utf-8") as f:
- w = csv.DictWriter(f, fieldnames=FIELDS)
- if new:
- w.writeheader()
- w.writerows(rows)
- print(f"logged {len(rows)} row(s) in {a.licenses}; fill 'used_in' and 'modifications' when used")
- def main():
- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- sub = ap.add_subparsers(dest="cmd", required=True)
- s = sub.add_parser("search")
- s.add_argument("--q", required=True)
- s.add_argument("--type", default="image", choices=["image", "video", "sound", "music", "hdri", "texture", "typography"])
- s.add_argument("--purpose", default="cinematic", choices=["cinematic", "ad"], help="typography: default sources")
- s.add_argument("--sources")
- s.add_argument("--licence")
- s.add_argument("--n", type=int, default=6)
- s.add_argument("--out", required=True)
- s.add_argument("--max-wait", type=float, help="seconds on one source before moving to the next (default 20; Openverse audio needs 10-25 s)")
- s.add_argument("--patient", action="store_true", help="search every source in full with no time limit — only for a background run, never the foreground")
- u = sub.add_parser("supply", help="count what the open archives hold per element, nothing downloaded")
- u.add_argument("--q", action="append", required=True, help="one key element per --q (English, the shape in words)")
- u.add_argument("--sources", help="default wikimedia,met,aic")
- u.add_argument("--n", type=int, default=20, help="results asked per source and element")
- u.add_argument("--max-wait", type=float, help="seconds per source, no second try (default 10)")
- f = sub.add_parser("fetch")
- f.add_argument("--results", required=True)
- f.add_argument("--pick", required=True)
- f.add_argument("--dest", required=True)
- f.add_argument("--variant", help="Poly Haven resolution:format, e.g. 2k:hdr, 1k:jpg")
- f.add_argument("--preview", type=float, help="sounds and music: only the first N seconds, for listening")
- f.add_argument("--licenses", default="LICENSES.csv")
- b = sub.add_parser("board")
- b.add_argument("--dirs", nargs="*", help="search output folders, one per key element")
- b.add_argument("--per", type=int, default=3)
- b.add_argument("--drop", nargs="*", help='results to leave out, per search folder: "<folder>:1,4" "<folder>:2"')
- b.add_argument("--refs", help="the user's reference folder (images)")
- b.add_argument("--out", required=True)
- a = ap.parse_args()
- MAX_WAIT[0] = getattr(a, "max_wait", None)
- {"search": search, "fetch": fetch, "board": board, "supply": supply}[a.cmd](a)
- if __name__ == "__main__":
- if os.name == "nt" and not sys.flags.utf8_mode: # Windows reads, writes and prints in a legacy code page
- import subprocess
- sys.exit(subprocess.call([sys.executable] + sys.argv, env=dict(os.environ, PYTHONUTF8="1")))
- for _s in (sys.stdin, sys.stdout, sys.stderr):
- getattr(_s, "reconfigure", lambda **k: None)(encoding="utf-8", errors="replace")
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.