DenSnoychik commited on
Commit
e7b8e7e
·
verified ·
1 Parent(s): 10d8c51

Add 2D anime references and Python renderer for Arena

Browse files
Arena_Anime_Prompt.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ЗАДАНИЕ ДЛЯ ARENA CODE MODE / FULLSTACK
2
+
3
+ Моя цель — получить красивый 2D-аниме-эпизод и весь редактируемый Python-проект, которым я смогу пользоваться в дальнейшем как эталоном для своей студии.
4
+
5
+ Репозиторий Hugging Face:
6
+ https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/tree/main
7
+
8
+ Посмотреть PNG и Python-файлы прямо в репозитории:
9
+ https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/tree/main/anime-2d-reference-kit
10
+
11
+ Скачать комплект с рисунками и исходниками:
12
+ https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/resolve/main/Arena_Anime_Reference_Kit.zip?download=true
13
+
14
+ Распакуй ZIP и визуально открой все шесть PNG в references/. Там есть пять человеческих силуэтов разного возраста и телосложения, отдельный лист бабушки с поворотами и мимикой, шесть животных (кошка, собака, кролик, лиса, лошадь, птица) и три примера фона (кухня, деревня, лес). Исходный Python/Cairo-движок находится в engine/. Если среда не может скачать ZIP по ссылке, используй тот же архив из вложения. Укажи, какие файлы удалось открыть.
15
+
16
+ СВОБОДА РЕАЛИЗАЦИИ
17
+
18
+ Можешь менять, переписывать и полностью заменить движок, формат сцен, риги, наборы ассетов и рендерер. Сам выбери способ получить нужный художественный результат. Входная команда, описание демонстрационной сцены, тайминг и редактируемая логика анимации должны быть на Python, в настоящих .py. Допустимы другие форматы для рисунков, ригов, фонов и данных. Готовая демонстрация должна воспроизводиться локально по команде из README, с зависимостями и ресурсами в комплекте.
19
+
20
+ ХУДОЖЕСТВЕННОЕ ЗАДАНИЕ
21
+
22
+ Сочини свой законченный эпизод на 12–20 секунд с 2–4 планами. Бабушка и одно животное — главные герои. Добавь ещё одного заметно отличающегося по телосложению персонажа, если он помогает истории. Остальные рисунки изучи для общего визуального языка. Сам выбери сюжет, действие, место и постановку. У эпизода должны читаться цель персонажа, действие и реакция. Пусть рисунки задают уровень и характер дизайна. Создай собственные пригодные для анимации слои, позы или кадры. В готовом ролике зритель должен видеть живую игру персонажей, смену поз и взаимодействия с окружением.
23
+
24
+ Сохрани индивидуальные пропорции, возраст, формы лица, скулы, подбородок, посадку глаз, руки, волосы и складки одежды. Нарисуй формы с выразительным контуром, анатомией и объёмом. Проверь узнаваемость при смене ракурса, особенно при повороте головы. Плавность оценивай по естественности тайминга и сохранению объёма. Покажи подготовку к действию, перенос веса, постановку стоп или лап, физический контакт с предметом, реакцию лица и запаздывание волос, одежды либо хвоста. Полезный контроль для камеры — одно действие должно ясно читаться даже при её фиксации. Фон должен поддерживать перспективу, свет и силуэты в каждом плане.
25
+
26
+ КАК ПРОВЕРИТЬ
27
+
28
+ До финального рендера изолированно выведи каждый созданный для эпизода объект: каждого персонажа, животное, значимые предметы, а также прозрачные слои, у которых есть риск потерять контур. Для светлых деталей используй мягкий голубой градиент с достаточно тёмным участком. Для персонажей проверь отдельно выражение лица, силуэт в движущихся позах и доступные ракурсы. Окружение выведи отдельно и сверь с ним посадку фигур.
29
+
30
+ Сделай черновой MP4, посмотри весь ролик в движении и проверь ключевые моменты на стоп-кадрах. Для каждого найденного дефекта укажи план и таймкод, исправь его в исходниках, перерендери участок и проверь результат. Повтори цикл, пока на целевом разрешении не останется видимых проблем с формой, движением, контактом и монтажом либо пока среда реально не упрётся в свой лимит. Дай 2–3 пары «до / после» для сделанных исправлений и укажи, что осталось, если что-то осталось. Технически проверь, что финальный MP4 декодируется, динамика есть в самих персонажах, а длительность, FPS и размер кадра совпадают с заявленными.
31
+
32
+ ЧТО ВЕРНУТЬ
33
+
34
+ 1. Arena_Anime_Demo.mp4 — финальный отрендеренный эпизод, целевой формат 16:9.
35
+ 2. Arena_Anime_Demo_Source.zip — полный исходный проект, включая .py, редактируемые данные сцен и анимаций, ассеты, зависимости, README с точными командами запуска, контрольные изображения и краткий отчёт о проверке.
36
+ 3. В ответе дай рабочие ссылки или кнопки скачивания обоих файлов. Под каждой укажи точное имя:
37
+ Имя файла для поиска в Загрузках: Arena_Anime_Demo.mp4
38
+ Имя файла для поиска в Загрузках: Arena_Anime_Demo_Source.zip
39
+
40
+ Сначала проверь, что в текущей среде реально доступны Python, запуск рендера и экспорт файлов. Если рендер или загрузка ограничены, подготовь максимально полный исходный проект с воспроизводимым локальным запуском, укажи конкретное ограничение и перечисли только реально созданные артефакты. Запиши фактические команды, время выполненных проверок и параметры полученного ролика.
Arena_Anime_Reference_Kit.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e9c1f40db80ce79ec9186cfc4084dece6a8fbea7eb4991bce4aed62907f5f64f
3
+ size 14590729
Arena_Anime_Reference_Preview.jpg ADDED

Git LFS Details

  • SHA256: 72d385daabca142586bfcdb8bdb8ac6597339ffc6f9e82e793ea767244ad0418
  • Pointer size: 131 Bytes
  • Size of remote file: 328 kB
anime-2d-reference-kit/Arena_Anime_Prompt.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ЗАДАНИЕ ДЛЯ ARENA CODE MODE / FULLSTACK
2
+
3
+ Моя цель — получить красивый 2D-аниме-эпизод и весь редактируемый Python-проект, которым я смогу пользоваться в дальнейшем как эталоном для своей студии.
4
+
5
+ Репозиторий Hugging Face:
6
+ https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/tree/main
7
+
8
+ Посмотреть PNG и Python-файлы прямо в репозитории:
9
+ https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/tree/main/anime-2d-reference-kit
10
+
11
+ Скачать комплект с рисунками и исходниками:
12
+ https://huggingface.co/datasets/DenSnoychik/ArenaAISpace/resolve/main/Arena_Anime_Reference_Kit.zip?download=true
13
+
14
+ Распакуй ZIP и визуально открой все шесть PNG в references/. Там есть пять человеческих силуэтов разного возраста и телосложения, отдельный лист бабушки с поворотами и мимикой, шесть животных (кошка, собака, кролик, лиса, лошадь, птица) и три примера фона (кухня, деревня, лес). Исходный Python/Cairo-движок находится в engine/. Если среда не может скачать ZIP по ссылке, используй тот же архив из вложения. Укажи, какие файлы удалось открыть.
15
+
16
+ СВОБОДА РЕАЛИЗАЦИИ
17
+
18
+ Можешь менять, переписывать и полностью заменить движок, формат сцен, риги, наборы ассетов и рендерер. Сам выбери способ получить нужный художественный результат. Входная команда, описание демонстрационной сцены, тайминг и редактируемая логика анимации должны быть на Python, в настоящих .py. Допустимы другие форматы для рисунков, ригов, фонов и данных. Готовая демонстрация должна воспроизводиться локально по команде из README, с зависимостями и ресурсами в комплекте.
19
+
20
+ ХУДОЖЕСТВЕННОЕ ЗАДАНИЕ
21
+
22
+ Сочини свой законченный эпизод на 12–20 секунд с 2–4 планами. Бабушка и одно животное — главные герои. Добавь ещё одного заметно отличающегося по телосложению персонажа, если он помогает истории. Остальные рисунки изучи для общего визуального языка. Сам выбери сюжет, действие, место и постановку. У эпизода должны читаться цель персонажа, действие и реакция. Пусть рисунки задают уровень и характер дизайна. Создай собственные пригодные для анимации слои, позы или кадры. В готовом ролике зритель должен видеть живую игру персонажей, смену поз и взаимодействия с окружением.
23
+
24
+ Сохрани индивидуальные пропорции, возраст, формы лица, скулы, подбородок, посадку глаз, руки, волосы и складки одежды. Нарисуй формы с выразительным контуром, анатомией и объёмом. Проверь узнаваемость при смене ракурса, особенно при повороте головы. Плавность оценивай по естественности тайминга и сохранению объёма. Покажи подготовку к действию, перенос веса, постановку стоп или лап, физический контакт с предметом, реакцию лица и запаздывание волос, одежды либо хвоста. Полезный контроль для камеры — одно действие должно ясно читаться даже при её фиксации. Фон должен поддерживать перспективу, свет и силуэты в каждом плане.
25
+
26
+ КАК ПРОВЕРИТЬ
27
+
28
+ До финального рендера изолированно выведи каждый созданный для эпизода объект: каждого персонажа, животное, значимые предметы, а также прозрачные слои, у которых есть риск потерять контур. Для светлых деталей используй мягкий голубой градиент с достаточно тёмным участком. Для персонажей проверь отдельно выражение лица, силуэт в движущихся позах и доступные ракурсы. Окружение выведи отдельно и сверь с ним посадку фигур.
29
+
30
+ Сделай черновой MP4, посмотри весь ролик в движении и проверь ключевые моменты на стоп-кадрах. Для каждого найденного дефекта укажи план и таймкод, исправь его в исходниках, перерендери участок и проверь результат. Повтори цикл, пока на целевом разрешении не останется видимых проблем с формой, движением, контактом и монтажом либо пока среда реально не упрётся в свой лимит. Дай 2–3 пары «до / после» для сделанных исправлений и укажи, что осталось, если что-то осталось. Технически проверь, что финальный MP4 декодируется, динамика есть в самих персонажах, а длительность, FPS и размер кадра совпадают с заявленными.
31
+
32
+ ЧТО ВЕРНУТЬ
33
+
34
+ 1. Arena_Anime_Demo.mp4 — финальный отрендеренный эпизод, целевой формат 16:9.
35
+ 2. Arena_Anime_Demo_Source.zip — полный исходный проект, включая .py, редактируемые данные сцен и анимаций, ассеты, зависимости, README с точными командами запуска, контрольные изображения и краткий отчёт о проверке.
36
+ 3. В ответе дай рабочие ссылки или кнопки скачивания обоих файлов. Под каждой укажи точное имя:
37
+ Имя файла для поиска в Загрузках: Arena_Anime_Demo.mp4
38
+ Имя файла для поиска в Загрузках: Arena_Anime_Demo_Source.zip
39
+
40
+ Сначала проверь, что в текущей среде реально доступны Python, запуск рендера и экспорт файлов. Если рендер или загрузка ограничены, подготовь максимально полный исходный проект с воспроизводимым локальным запуском, укажи конкретное ограничение и перечисли только реально созданные артефакты. Запиши фактические команды, время выполненных проверок и параметры полученного ролика.
anime-2d-reference-kit/README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Референсы для 2D-аниме и исходники рендера
2
+
3
+ Шесть PNG в `references/` задуманы как листы дизайна и окружения. В них рисованные примеры пропорций, силуэтов, покраски, ракурсов и мимики.
4
+
5
+ | Файл | Содержимое |
6
+ | --- | --- |
7
+ | 01-human-silhouettes.png | Ребёнок, высокий худощавый мужчина, широкоплечая женщина, коренастый полный мужчина, пожилая женщина |
8
+ | 02-grandmother-turnaround.png | Бабушка в нескольких ракурсах и примеры мимики |
9
+ | 03-animal-designs.png | Кошка, собака, кролик, лиса, лошадь, птица |
10
+ | 04-interior-kitchen.png | Кухня |
11
+ | 05-exterior-village.png | Деревня |
12
+ | 06-exterior-forest.png | Лес |
13
+
14
+ `engine/` содержит Python/Cairo-исходники и проверки из [DenSnoy/PythonProject](https://github.com/DenSnoy/PythonProject/tree/34f7218734edbc4cd53a4d34eccf9c5b071844d6). Техническая сцена `scenes/motion-example.py` из локального рабочего примера показывает интерфейс движка. Её рисунок служит тесту рендера. Для художественного направления используйте PNG. Исходная ветка с Gemini использует переменные окружения. Рендер готового Python-сценария запускается через `--scene`. Используйте доверенные файлы сцен, поскольку рендерер исполняет Python-код сцены.
15
+
16
+ Старт из папки `engine/`:
17
+
18
+ ```bash
19
+ python -m pip install -r requirements.txt
20
+ python render.py --scene scenes/motion-example.py --duration 2 --fps 24 --strict-frames --out smoke
21
+ ```
22
+
23
+ Для звуковой ветки с MIDI нужны системный FluidSynth и доступный SoundFont (`SOUNDFONT_PATH`). Для видео нужен FFmpeg.
24
+
25
+ `Arena_Anime_Prompt.txt` — готовое задание для Arena Code Mode. Оно даёт свободу менять либо целиком заменить приложенный движок.
anime-2d-reference-kit/engine/config.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration read from environment variables."""
2
+ import os
3
+
4
+ API_KEY = os.getenv("GEMINI_API_KEY", "").strip()
5
+ LIVE_API_KEYS = [os.environ["GEMINI_LIVE_API_KEY"].strip()] if os.getenv("GEMINI_LIVE_API_KEY", "").strip() else []
6
+ MODEL_NAME = os.getenv("GEMINI_MODEL", "gemini-3.5-flash-lite")
7
+ LIVE_MODEL = os.getenv("GEMINI_LIVE_MODEL", "gemini-3.1-flash-live-preview")
8
+ PROXY_URL = os.getenv("GEMINI_BASE_URL", "")
9
+ LIVE_PROXY_URL = os.getenv("GEMINI_LIVE_BASE_URL") or None
10
+ SOUNDFONT_PATH = os.getenv("SOUNDFONT_PATH", "")
11
+ OUTPUT_DIR = "output"
12
+ VIDEO_DURATION = 15.0
13
+ VIDEO_FPS = 60
14
+ AUDIO_SAMPLE_RATE = 44100
anime-2d-reference-kit/engine/final_review.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Require a recorded review of the exact draft before accepting a final render."""
2
+ import json
3
+ from pathlib import Path
4
+ import re
5
+ import runpy
6
+ import subprocess
7
+
8
+
9
+ def git(*args):
10
+ return subprocess.check_output(["git", *args], text=True, encoding="utf-8").strip()
11
+
12
+
13
+ def validate_final_review(request):
14
+ path = request.get("review", "")
15
+ if not isinstance(path, str) or not re.fullmatch(r"reviews/[a-z0-9-]+\.json", path):
16
+ raise SystemExit("Final render needs a review in reviews/<id>.json.")
17
+ review_path = Path(path).resolve(strict=True)
18
+ if not review_path.is_relative_to(Path("reviews").resolve()):
19
+ raise SystemExit("Review file resolves outside reviews/.")
20
+ review = json.loads(review_path.read_text(encoding="utf-8"))
21
+ draft_sha = review.get("draft_sha", "")
22
+ if not isinstance(draft_sha, str) or not re.fullmatch(r"[0-9a-f]{40}", draft_sha):
23
+ raise SystemExit("Review must reference the reviewed draft commit.")
24
+ if subprocess.run(["git", "merge-base", "--is-ancestor", draft_sha, "HEAD"]).returncode:
25
+ raise SystemExit("Reviewed draft must be in this branch history.")
26
+ files = git("diff-tree", "--no-commit-id", "--diff-filter=A", "-r", "--name-only",
27
+ draft_sha, "--", "render-requests/").splitlines()
28
+ if len(files) != 1:
29
+ raise SystemExit("Draft commit must add one render request.")
30
+ draft = json.loads(git("show", f"{draft_sha}:{files[0]}"))
31
+ keys = ("scene", "duration", "fps", "format", "voice", "checkpoints", "motion")
32
+ defaults = {"duration": 3, "fps": 30, "format": "horizontal", "voice": False}
33
+ if draft.get("stage") != "draft" or any(
34
+ draft.get(key, defaults.get(key)) != request.get(key, defaults.get(key)) for key in keys
35
+ ):
36
+ raise SystemExit("Final scene, timing, voice and checkpoints must match the reviewed draft.")
37
+ if git("diff", "--name-only", draft_sha, "HEAD", "--", ".",
38
+ ":(exclude)render-requests/**", ":(exclude)reviews/**", ":(exclude)README.md"):
39
+ raise SystemExit("Source changed since review. Render and inspect a new draft.")
40
+
41
+ assets = review.get("assets", {})
42
+ checkpoints = review.get("checkpoints", [])
43
+ defects = review.get("defects")
44
+ if review.get("scene") != request["scene"] or not isinstance(assets, dict) or not assets:
45
+ raise SystemExit("Review must list inspected objects for the requested scene.")
46
+ registered = runpy.run_path(request["scene"]).get("REVIEW_ASSETS")
47
+ if not isinstance(registered, dict) or set(assets) != set(registered):
48
+ raise SystemExit("Review must cover every object registered by the final scene.")
49
+ if not all(re.fullmatch(r"[a-z][a-z0-9_-]{0,55}", name)
50
+ and isinstance(note, str) and note.strip() for name, note in assets.items()):
51
+ raise SystemExit("Each object needs its own visual observation.")
52
+ if (not isinstance(checkpoints, list) or len(checkpoints) != len(request["checkpoints"])
53
+ or not all(isinstance(note, str) and note.strip() for note in checkpoints)):
54
+ raise SystemExit("Review must record an observation for each motion checkpoint.")
55
+ if request.get("motion"):
56
+ notes = review.get("motion")
57
+ if not isinstance(notes, list) or len(notes) != len(request["motion"]) or not all(
58
+ isinstance(note, str) and note.strip() for note in notes
59
+ ):
60
+ raise SystemExit("Review must describe visible actor motion for every declared beat.")
61
+ if not isinstance(defects, list) or not all(
62
+ isinstance(item, dict) and item.get("status") == "verified-fixed"
63
+ and all(isinstance(item.get(key), str) and item[key].strip()
64
+ for key in ("where", "problem", "change", "verified"))
65
+ for item in defects
66
+ ):
67
+ raise SystemExit("Review has unresolved defects or lacks verified fixes.")
anime-2d-reference-kit/engine/modules/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Animation engine and Gemini clients."""
anime-2d-reference-kit/engine/modules/client.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================================
2
+ # MODULES / CLIENT.PY
3
+ # Клиент Gemini API с умной ротацией ключей и фильтрацией ошибок
4
+ # ==========================================================
5
+
6
+ import re
7
+ import requests
8
+ import config
9
+
10
+ def get_all_api_keys() -> list[str]:
11
+ raw = getattr(config, "API_KEY", [])
12
+ if isinstance(raw, list):
13
+ keys = [str(k).strip() for k in raw if str(k).strip()]
14
+ if keys:
15
+ return keys
16
+ elif isinstance(raw, str) and raw.strip():
17
+ return [raw.strip()]
18
+ raise ValueError("Задайте переменную GEMINI_API_KEY.")
19
+
20
+ def extract_code_block(text: str) -> str:
21
+ text = text.strip()
22
+ match = re.search(r"```(?:python|json)?\s*([\s\S]*?)\s*```", text, flags=re.IGNORECASE)
23
+ if match:
24
+ return match.group(1).strip()
25
+ clean = re.sub(r"^```(?:python|json)?\s*", "", text, flags=re.IGNORECASE)
26
+ clean = re.sub(r"\s*```$", "", clean).strip()
27
+ return clean
28
+
29
+ def is_google_side_error(status_code: int, response_text: str) -> bool:
30
+ """Определяет, относится ли ошибка к стороне Google/Ключа или это локальная ошибка."""
31
+ if status_code in (429, 500, 502, 503, 504, 524):
32
+ return True
33
+ if status_code == 403:
34
+ # Исчерпан лимит или ключ заблокирован
35
+ return True
36
+ if status_code == 400:
37
+ err_lower = response_text.lower()
38
+ if any(w in err_lower for w in ["api_key_invalid", "key expired", "api key not valid", "quota", "resource_exhausted"]):
39
+ return True
40
+ return False
41
+
42
+ def call_gemini(system_prompt: str, user_prompt: str, model: str = None, thinking: bool = True, images: list = None) -> str:
43
+ keys = get_all_api_keys()
44
+ selected_model = model or getattr(config, "MODEL_NAME", "gemini-3.5-flash-lite")
45
+ proxy_url = getattr(config, "PROXY_URL", "").strip()
46
+ base_url = proxy_url.rstrip("/") if proxy_url else "https://generativelanguage.googleapis.com"
47
+ proxies = getattr(config, "PROXIES", None)
48
+
49
+ parts = [{"text": f"{system_prompt}\n\nUSER REQUEST: {user_prompt}"}]
50
+
51
+ if images and isinstance(images, list):
52
+ for img in images[:10]:
53
+ if isinstance(img, dict) and "data" in img and "mime_type" in img:
54
+ parts.append({
55
+ "inline_data": {
56
+ "mime_type": img["mime_type"],
57
+ "data": img["data"]
58
+ }
59
+ })
60
+
61
+ payload = {
62
+ "contents": [{"parts": parts}],
63
+ "generationConfig": {
64
+ "temperature": 0.7,
65
+ "maxOutputTokens": 65536
66
+ }
67
+ }
68
+
69
+ if thinking:
70
+ payload["generationConfig"]["thinkingConfig"] = {"thinkingLevel": "medium"}
71
+ print(f"[+] [Gemini API] Модель: {selected_model} | 🧠 Thinking: ВКЛ")
72
+ else:
73
+ print(f"[+] [Gemini API] Модель: {selected_model} | ⚡ Thinking: ВЫКЛ")
74
+
75
+ last_google_error = ""
76
+
77
+ for index, key in enumerate(keys):
78
+ print(f"[*] Попытка запроса с ключом #{index + 1}/{len(keys)}")
79
+ url = f"{base_url}/v1beta/models/{selected_model}:generateContent"
80
+
81
+ try:
82
+ res = requests.post(
83
+ url,
84
+ json=payload,
85
+ headers={"Content-Type": "application/json; charset=utf-8", "x-goog-api-key": key},
86
+ proxies=proxies,
87
+ timeout=120
88
+ )
89
+ except requests.exceptions.Timeout:
90
+ print(f"[!] Ключ #{index + 1}: Таймаут соединения с сервером Google.")
91
+ last_google_error = "Таймаут соединения с Gemini API"
92
+ continue
93
+ except requests.exceptions.RequestException as e:
94
+ # Ошибка локального сетевого стека или DNS клиента
95
+ raise RuntimeError(f"Локальная сетевая ошибка соединения: {type(e).__name__}")
96
+
97
+ # Успешный ответ
98
+ if res.status_code == 200:
99
+ data = res.json()
100
+ candidates = data.get("candidates", [])
101
+ if not candidates:
102
+ raise RuntimeError("Gemini API вернул ответ, но список 'candidates' пуст.")
103
+
104
+ cand_parts = candidates[0].get("content", {}).get("parts", [])
105
+ text = "".join(p.get("text", "") for p in cand_parts if not p.get("thought", False))
106
+ if not text and cand_parts:
107
+ text = cand_parts[-1].get("text", "")
108
+
109
+ clean = extract_code_block(text)
110
+ if not clean:
111
+ raise RuntimeError("Не удалось извлечь код из ответа модели.")
112
+
113
+ return clean
114
+
115
+ # Проверяем причину ошибки
116
+ err_text = res.text
117
+ if is_google_side_error(res.status_code, err_text):
118
+ try:
119
+ err_msg = res.json().get("error", {}).get("message", err_text[:200])
120
+ except Exception:
121
+ err_msg = err_text[:200]
122
+ print(f"[!] Ошибка Google (код {res.status_code}): {err_msg}. Переключаемся на следующий ключ...")
123
+ last_google_error = f"Код {res.status_code}: {err_msg}"
124
+ continue
125
+ else:
126
+ # Ошибка вызвана некорректным телом запроса/клиентскими параметрами — прерываем перебор
127
+ try:
128
+ client_err = res.json().get("error", {}).get("message", res.text)
129
+ except Exception:
130
+ client_err = res.text
131
+ raise RuntimeError(f"Фатальная ошибка клиента (код {res.status_code}): {client_err}")
132
+
133
+ # Если цикл завершился и все ключи исчерпаны
134
+ raise RuntimeError(f"Все доступные API-ключи ({len(keys)} шт.) исчерпали лимит или недоступны. Последняя ошибка Google: {last_google_error}")
anime-2d-reference-kit/engine/modules/live_config.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================================
2
+ # MODULES / LIVE_CONFIG.PY
3
+ # Настройки Gemini Live API (Актерская игра и эмоции)
4
+ # ==========================================================
5
+
6
+ import config
7
+
8
+ LIVE_MODEL = "models/gemini-3.1-flash-live-preview"
9
+
10
+ # Все пресеты настроены на живое актерское исполнение эмоций
11
+ VOICE_PRESETS = {
12
+ "grandma": {
13
+ "voice": "Vindemiatrix",
14
+ "title": "Бабушка (Vindemiatrix)",
15
+ "instruction": "Ты бабушка. Говори тепло, с заботой, быстро и живо. Все эмоции отыгрывай голосом и интонацией."
16
+ },
17
+ "male_bass": {
18
+ "voice": "Algieba",
19
+ "title": "Мужской бас (Algieba)",
20
+ "instruction": "Ты харизматичный мужчина с басовым голосом. Говори четко, быстро, уверенно, энергично и эмоционально."
21
+ },
22
+ "female_leda": {
23
+ "voice": "Leda",
24
+ "title": "Женский эмоциональный (Leda)",
25
+ "instruction": "Ты живая, яркая девушка. Разговаривай задорно, эмоционально, с естественным смехом в голосе."
26
+ },
27
+ "male_proud": {
28
+ "voice": "Zubenelgenubi",
29
+ "title": "Гордый мужской (Zubenelgenubi)",
30
+ "instruction": "Ты гордый лидер. Говори звучно, твердо, быстро и эмоционально."
31
+ },
32
+ "male_fast": {
33
+ "voice": "Achird",
34
+ "title": "Быстрый мужской (Achird)",
35
+ "instruction": "Ты энергичный ведущий. Говори максимально динамично, живо и зажигательно."
36
+ },
37
+ "female_sulafat": {
38
+ "voice": "Sulafat",
39
+ "title": "Спокойный женский (Sulafat)",
40
+ "instruction": "Ты девушка с приятным мягким голосом. Говори лаконично, живо, с мягкой улыбкой в голосе."
41
+ }
42
+ }
43
+
44
+ # Жесткая директива актерской игры: НЕ читать ремарки вслух
45
+ LIVE_ACTING_PROMPT = """
46
+ [CRITICAL VOICE ACTING DIRECTIVE]:
47
+ 1. NEVER pronounce stage directions, markdown actions, or words in asterisks/brackets (e.g., *laughs*, *chuckles*, *sighs*, *усмехнулась*, [whispers]) aloud as literal words!
48
+ 2. Instead, ACT THEM OUT naturally with your vocal performance (actually chuckle, laugh, sigh, gasp, or shift your tone/pitch).
49
+ 3. Speak clearly, expressively, and with authentic emotional timing.
50
+ """
51
+
52
+ def get_live_credentials():
53
+ return config.LIVE_API_KEYS or config.API_KEY, config.LIVE_PROXY_URL, config.LIVE_MODEL or LIVE_MODEL
anime-2d-reference-kit/engine/modules/mod_video.py ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =========================================================================
2
+ # MODULES / MOD_VIDEO.PY
3
+ # Universal Motion Graphics Engine (60 FPS) + PyCairo Anti-Aliased Canvas
4
+ # + Safe-Proxy Canvas + Live Audio-Reactive Energy + FluidSynth SoundFont
5
+ # =========================================================================
6
+
7
+ import os
8
+ import base64
9
+ import io
10
+ from pathlib import Path
11
+ import sys
12
+ import re
13
+ import uuid
14
+ import math
15
+ import time
16
+ import inspect
17
+ import random
18
+ import colorsys
19
+ import wave
20
+ import shutil
21
+ import subprocess
22
+ import asyncio
23
+ import concurrent.futures
24
+ import builtins
25
+ import numpy as np
26
+ import cv2
27
+ import cairo
28
+ from modules.client import call_gemini
29
+ import config
30
+
31
+ # -------------------------------------------------------------------------
32
+ # 0. БЕЗОПАСНАЯ ОБЕРТКА ДЛЯ CAIRO.CONTEXT (ЗАЩИТА ОТ ОПЕЧАТОК И CANVAS API)
33
+ # -------------------------------------------------------------------------
34
+ class SafeCairoContext:
35
+ """Безопасный прокси над cairo.Context: переводит вызовы HTML5 Canvas в PyCairo."""
36
+ def __init__(self, raw_ctx):
37
+ self._ctx = raw_ctx
38
+
39
+ def begin_path(self):
40
+ return self._ctx.new_path()
41
+
42
+ def beginPath(self):
43
+ return self._ctx.new_path()
44
+
45
+ def close_path(self):
46
+ return self._ctx.close_path()
47
+
48
+ def closePath(self):
49
+ return self._ctx.close_path()
50
+
51
+ def circle(self, cx, cy, r):
52
+ return self._ctx.arc(cx, cy, r, 0, 2 * math.pi)
53
+
54
+ def ellipse(self, cx, cy, rx, ry):
55
+ self._ctx.save()
56
+ self._ctx.translate(cx, cy)
57
+ self._ctx.scale(rx, ry)
58
+ self._ctx.arc(0, 0, 1.0, 0, 2 * math.pi)
59
+ self._ctx.restore()
60
+
61
+ def round_rect(self, x, y, w, h, r):
62
+ r = min(r, w / 2.0, h / 2.0)
63
+ self._ctx.move_to(x + r, y)
64
+ self._ctx.line_to(x + w - r, y)
65
+ self._ctx.arc(x + w - r, y + r, r, -math.pi / 2, 0)
66
+ self._ctx.line_to(x + w, y + h - r)
67
+ self._ctx.arc(x + w - r, y + h - r, r, 0, math.pi / 2)
68
+ self._ctx.line_to(x + r, y + h)
69
+ self._ctx.arc(x + r, y + h - r, r, math.pi / 2, math.pi)
70
+ self._ctx.line_to(x, y + r)
71
+ self._ctx.arc(x + r, y + r, r, math.pi, 3 * math.pi / 2)
72
+ self._ctx.close_path()
73
+
74
+ def __getattr__(self, name):
75
+ return getattr(self._ctx, name)
76
+
77
+
78
+ # Внедрение математических функций в глобальный scope Python
79
+ builtins.math = math
80
+ builtins.sin = math.sin
81
+ builtins.cos = math.cos
82
+ builtins.tan = math.tan
83
+ builtins.atan2 = math.atan2
84
+ builtins.pi = math.pi
85
+ builtins.sqrt = math.sqrt
86
+ builtins.np = np
87
+ builtins.random = random
88
+ builtins.colorsys = colorsys
89
+
90
+ from modules.live_config import VOICE_PRESETS, LIVE_ACTING_PROMPT, get_live_credentials
91
+
92
+ def get_soundfont_path():
93
+ candidates = [config.SOUNDFONT_PATH, "GeneralUser_GS.sf2",
94
+ "/usr/share/sounds/sf2/FluidR3_GM.sf2"]
95
+ return next((path for path in candidates if path and os.path.isfile(path)), None)
96
+
97
+
98
+ def resample_audio(pcm_data: np.ndarray, orig_sr: int = 24000, target_sr: int = 44100) -> np.ndarray:
99
+ if len(pcm_data) == 0: return np.zeros(0, dtype=np.float32)
100
+ try:
101
+ from scipy.signal import resample_poly
102
+ divisor = math.gcd(orig_sr, target_sr)
103
+ return resample_poly(pcm_data, target_sr // divisor, orig_sr // divisor).astype(np.float32)
104
+ except Exception:
105
+ target_len = int(len(pcm_data) * (target_sr / float(orig_sr)))
106
+ return np.interp(
107
+ np.linspace(0, len(pcm_data), target_len, endpoint=False),
108
+ np.arange(len(pcm_data)),
109
+ pcm_data
110
+ ).astype(np.float32)
111
+
112
+
113
+ def time_stretch_preserve_pitch(signal: np.ndarray, speed: float = 1.0, sr: int = 44100) -> np.ndarray:
114
+ speed = float(speed or 1.0)
115
+ if abs(speed - 1.0) < 0.03 or len(signal) < 2048: return signal
116
+
117
+ win_size = int(sr * 0.025)
118
+ if win_size % 2 != 0: win_size += 1
119
+ hop_syn = win_size // 2
120
+ hop_ana = int(hop_syn * speed)
121
+ if hop_ana <= 0 or win_size >= len(signal): return signal
122
+
123
+ window = np.hanning(win_size).astype(np.float32)
124
+ num_frames = (len(signal) - win_size) // hop_ana
125
+ if num_frames <= 1: return signal
126
+
127
+ out_len = num_frames * hop_syn + win_size
128
+ output = np.zeros(out_len, dtype=np.float32)
129
+ norm = np.zeros(out_len, dtype=np.float32)
130
+ search_range = win_size // 4
131
+
132
+ for i in range(num_frames):
133
+ ana_pos = i * hop_ana
134
+ syn_pos = i * hop_syn
135
+ best_pos = ana_pos
136
+ if i > 0 and (ana_pos - search_range >= 0) and (ana_pos + win_size + search_range < len(signal)):
137
+ ref = output[syn_pos : syn_pos + win_size]
138
+ candidates = np.array([
139
+ signal[ana_pos + d : ana_pos + d + win_size] * window
140
+ for d in range(-search_range, search_range, 2)
141
+ ])
142
+ corrs = np.dot(candidates, ref)
143
+ best_idx = int(np.argmax(corrs))
144
+ best_pos = ana_pos + (-search_range + best_idx * 2)
145
+
146
+ if best_pos + win_size > len(signal): break
147
+ frame = signal[best_pos : best_pos + win_size] * window
148
+ output[syn_pos : syn_pos + win_size] += frame
149
+ norm[syn_pos : syn_pos + win_size] += window
150
+
151
+ valid = norm > 1e-3
152
+ output[valid] /= norm[valid]
153
+ return output
154
+
155
+
156
+ # -------------------------------------------------------------------------
157
+ # 3. СИНТЕЗАТОР ГОЛОСА GEMINI LIVE API
158
+ # -------------------------------------------------------------------------
159
+ async def _fetch_gemini_live_pcm(text_prompt: str, voice_name: str, char_instruction: str) -> np.ndarray:
160
+ from google import genai
161
+ from google.genai import types
162
+
163
+ keys, proxy_url, model = get_live_credentials()
164
+ if not keys: return np.zeros(0, dtype=np.float32)
165
+
166
+ full_instruction = f"{char_instruction}\n\n{LIVE_ACTING_PROMPT}".strip()
167
+ sys_inst = types.Content(parts=[types.Part.from_text(text=full_instruction)])
168
+
169
+ live_config = types.LiveConnectConfig(
170
+ response_modalities=["AUDIO"],
171
+ speech_config=types.SpeechConfig(
172
+ voice_config=types.VoiceConfig(
173
+ prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice_name)
174
+ )
175
+ ),
176
+ system_instruction=sys_inst
177
+ )
178
+
179
+ http_opts = {"api_version": "v1beta"}
180
+ if proxy_url: http_opts["base_url"] = proxy_url
181
+
182
+ clean_text = text_prompt.strip()
183
+ command_prompt = f"Perform and speak aloud ONLY this dialogue line. Express emotions naturally, never read stage direction words out loud: {clean_text}"
184
+
185
+ for key in keys:
186
+ try:
187
+ client = genai.Client(http_options=http_opts, api_key=key)
188
+ audio_chunks = []
189
+ async with client.aio.live.connect(model=model, config=live_config) as session:
190
+ await session.send_realtime_input(text=command_prompt)
191
+
192
+ async for response in session.receive():
193
+ if data := getattr(response, "data", None):
194
+ audio_chunks.append(data)
195
+ server_content = getattr(response, "server_content", None)
196
+ if server_content and getattr(server_content, "turn_complete", False):
197
+ break
198
+
199
+ if audio_chunks:
200
+ raw_bytes = b"".join(audio_chunks)
201
+ int16_arr = np.frombuffer(raw_bytes, dtype=np.int16)
202
+ return (int16_arr.astype(np.float32) / 32768.0)
203
+ except Exception as e:
204
+ print(f"[!] Gemini Live ({voice_name}): {type(e).__name__}")
205
+ continue
206
+
207
+ return np.zeros(0, dtype=np.float32)
208
+
209
+
210
+ def generate_live_voice_audio(text_prompt: str, voice_or_preset: str = "female_leda", custom_instruction: str = None) -> np.ndarray:
211
+ preset = VOICE_PRESETS.get(voice_or_preset, {})
212
+ voice_name = preset.get("voice", voice_or_preset)
213
+ instruction = custom_instruction or preset.get("instruction", "Speak clearly, dynamically and concisely with natural emotion.")
214
+
215
+ def _thread_runner():
216
+ new_loop = asyncio.new_event_loop()
217
+ asyncio.set_event_loop(new_loop)
218
+ try:
219
+ return new_loop.run_until_complete(asyncio.wait_for(
220
+ _fetch_gemini_live_pcm(text_prompt, voice_name, instruction), timeout=30
221
+ ))
222
+ finally:
223
+ try:
224
+ pending = asyncio.all_tasks(new_loop)
225
+ if pending:
226
+ for task in pending: task.cancel()
227
+ new_loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
228
+ new_loop.close()
229
+ except Exception: pass
230
+
231
+ try:
232
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
233
+ future = executor.submit(_thread_runner)
234
+ return future.result(timeout=35.0)
235
+ except Exception as e:
236
+ print(f"[!] Сбой синтеза речи Gemini Live: {e}")
237
+ return np.zeros(0, dtype=np.float32)
238
+
239
+
240
+ # -------------------------------------------------------------------------
241
+ # 4. ТОЧНЫЙ И НЕУБИВАЕМЫЙ ЗВУКОВОЙ ДВИЖОК FLUIDSYNTH
242
+ # -------------------------------------------------------------------------
243
+ NOTE_MAP = {
244
+ 'c': 0, 'c#': 1, 'db': 1, 'd': 2, 'd#': 3, 'eb': 3, 'e': 4,
245
+ 'f': 5, 'f#': 6, 'gb': 6, 'g': 7, 'g#': 8, 'ab': 8, 'a': 9,
246
+ 'a#': 10, 'bb': 10, 'b': 11
247
+ }
248
+
249
+ def parse_note_to_midi(val) -> int:
250
+ if isinstance(val, (int, float)):
251
+ return int(np.clip(val, 0, 127))
252
+ if isinstance(val, str):
253
+ s = val.strip().lower()
254
+ m = re.match(r'([a-g][#b]?)(-?\d+)', s)
255
+ if m:
256
+ name, oct_v = m.group(1), int(m.group(2))
257
+ return int(np.clip(12 * (oct_v + 1) + NOTE_MAP.get(name, 9), 0, 127))
258
+ try: return int(float(val))
259
+ except Exception: return 60
260
+ return 60
261
+
262
+
263
+ class SoundStudio:
264
+ """Универсальная студия: точные программы FluidSynth (0-127) + ударные + Gemini Voice."""
265
+ def __init__(self, duration: float = 15.0, sample_rate: int = 44100):
266
+ self.duration = float(duration)
267
+ self.sample_rate = int(sample_rate)
268
+ self.total_samples = int(self.duration * self.sample_rate)
269
+ self.master_buffer = np.zeros((self.total_samples, 2), dtype=np.float32)
270
+ self.midi_events = []
271
+ self.channel_programs = {}
272
+
273
+ def voice(self, *args, **kwargs):
274
+ """Синтез живой актерской речи."""
275
+ start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("time", kwargs.get("t", 0.0))))
276
+ text = str(args[1] if len(args) > 1 else kwargs.get("text", kwargs.get("prompt", kwargs.get("line", ""))))
277
+ voice = str(args[2] if len(args) > 2 else kwargs.get("voice", kwargs.get("speaker", "female_leda")))
278
+ instruction = kwargs.get("instruction", None)
279
+ speed = float(kwargs.get("speed", kwargs.get("rate", 1.15)))
280
+ vol = float(kwargs.get("vol", kwargs.get("volume", kwargs.get("gain", 1.0))))
281
+ pan = float(kwargs.get("pan", 0.0))
282
+
283
+ start_idx = int(max(0.0, start) * self.sample_rate)
284
+ if start_idx >= self.total_samples or not text.strip(): return
285
+
286
+ pcm_24k = generate_live_voice_audio(text, voice_or_preset=voice, custom_instruction=instruction)
287
+ if len(pcm_24k) == 0:
288
+ raise RuntimeError(f"Gemini Live не вернул озвучку для голоса {voice}.")
289
+
290
+ v_peak = np.max(np.abs(pcm_24k))
291
+ if v_peak > 0.001: pcm_24k = (pcm_24k / v_peak) * 0.90
292
+
293
+ resampled_voice = resample_audio(pcm_24k, orig_sr=24000, target_sr=self.sample_rate)
294
+ speed_val = max(0.6, min(2.5, speed))
295
+ resampled_voice = time_stretch_preserve_pitch(resampled_voice, speed=speed_val, sr=self.sample_rate)
296
+
297
+ abs_v = np.abs(resampled_voice)
298
+ gate_mask = np.clip((abs_v - 0.008) / 0.015, 0.0, 1.0)
299
+ smooth_k = int(self.sample_rate * 0.005)
300
+ if smooth_k > 1:
301
+ k = np.ones(smooth_k) / smooth_k
302
+ gate_mask = np.convolve(gate_mask, k, mode='same')
303
+ resampled_voice = resampled_voice * gate_mask
304
+
305
+ end_idx = min(self.total_samples, start_idx + len(resampled_voice))
306
+ actual_len = end_idx - start_idx
307
+ if actual_len <= 0: return
308
+
309
+ voice_gain = vol * 1.6
310
+ pan_val = max(-1.0, min(1.0, pan))
311
+ left_gain = math.cos((pan_val + 1.0) * math.pi / 4.0) * voice_gain
312
+ right_gain = math.sin((pan_val + 1.0) * math.pi / 4.0) * voice_gain
313
+
314
+ self.master_buffer[start_idx:end_idx, 0] += resampled_voice[:actual_len] * left_gain
315
+ self.master_buffer[start_idx:end_idx, 1] += resampled_voice[:actual_len] * right_gain
316
+
317
+ def voice_clip(self, start: float, asset: str, volume: float = 1.0):
318
+ """Place verified Gemini Live WAV data without calling any API."""
319
+ if not re.fullmatch(r"voice-clips/[a-zA-Z0-9_-]+\.wav\.b64", asset):
320
+ raise ValueError("Voice clips belong in voice-clips/ as .wav.b64 files.")
321
+ path = Path(asset).resolve(strict=True)
322
+ if not path.is_relative_to(Path("voice-clips").resolve()):
323
+ raise ValueError("Voice clip resolves outside voice-clips/.")
324
+ start = float(start)
325
+ volume = float(volume)
326
+ if not math.isfinite(start) or not 0 <= start < self.duration:
327
+ raise ValueError("Voice clip start must be inside the scene.")
328
+ if not math.isfinite(volume) or not 0 < volume <= 2:
329
+ raise ValueError("Voice clip volume must be between 0 and 2.")
330
+ encoded = path.read_bytes().strip()
331
+ if not 0 < len(encoded) <= 4_000_000:
332
+ raise ValueError("Voice clip data is empty or too large.")
333
+ with wave.open(io.BytesIO(base64.b64decode(encoded, validate=True)), "rb") as clip:
334
+ if (clip.getnchannels(), clip.getsampwidth(), clip.getframerate()) != (1, 2, 24000):
335
+ raise ValueError("Expected a 24 kHz mono 16-bit PCM WAV.")
336
+ frame_count = clip.getnframes()
337
+ pcm = np.frombuffer(clip.readframes(frame_count), dtype="<i2")
338
+ if not frame_count or len(pcm) != frame_count or not np.any(pcm):
339
+ raise ValueError("Voice clip is empty, silent or truncated.")
340
+ signal = resample_audio(pcm.astype(np.float32) / 32768.0, 24000, self.sample_rate)
341
+ begin = round(start * self.sample_rate)
342
+ end = begin + len(signal)
343
+ if end > self.total_samples:
344
+ raise ValueError("Voice clip exceeds scene duration. Extend the scene or start earlier.")
345
+ self.master_buffer[begin:end] += (signal * volume / math.sqrt(2))[:, None]
346
+
347
+ def play(self, *args, **kwargs):
348
+ """Воспроизведение нот/сэмплов по точному номеру инструмента General MIDI."""
349
+ start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("time", kwargs.get("t", 0.0))))
350
+ duration = float(args[1] if len(args) > 1 else kwargs.get("duration", kwargs.get("dur", kwargs.get("d", 0.5))))
351
+ pitch = args[2] if len(args) > 2 else kwargs.get("pitch", kwargs.get("note", kwargs.get("key", 60)))
352
+ program = int(kwargs.get("program", kwargs.get("prog", kwargs.get("instrument", 0))))
353
+ vol = int(kwargs.get("vol", kwargs.get("volume", kwargs.get("velocity", 90))))
354
+ channel = int(kwargs.get("channel", kwargs.get("ch", 0)))
355
+ bank = int(kwargs.get("bank", 0))
356
+
357
+ t_start = max(0.0, start)
358
+ dur = max(0.05, duration)
359
+ t_end = min(self.duration, t_start + dur)
360
+ ch = channel % 16
361
+ if ch == 9: ch = 0
362
+
363
+ self.channel_programs[ch] = (bank, program)
364
+ pitches = pitch if isinstance(pitch, (list, tuple)) else [pitch]
365
+ for p in pitches:
366
+ midi_p = parse_note_to_midi(p)
367
+ v = int(np.clip(vol, 1, 127))
368
+ self.midi_events.append((t_start, "on", ch, midi_p, v))
369
+ self.midi_events.append((t_end, "off", ch, midi_p, 0))
370
+
371
+ def note(self, *args, **kwargs):
372
+ self.play(*args, **kwargs)
373
+
374
+ def chord(self, *args, **kwargs):
375
+ start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("t", 0.0)))
376
+ duration = float(args[1] if len(args) > 1 else kwargs.get("duration", kwargs.get("dur", 1.5)))
377
+ pitches = kwargs.get("pitches", kwargs.get("chord", kwargs.get("notes", ["C4", "E4", "G4"])))
378
+ if "pitch" in kwargs: pitches = kwargs["pitch"]
379
+ program = int(kwargs.get("program", kwargs.get("prog", 48)))
380
+ vol = int(kwargs.get("vol", kwargs.get("volume", kwargs.get("velocity", 80))))
381
+ self.play(start=start, duration=duration, pitch=pitches, program=program, vol=vol, channel=1)
382
+
383
+ def drum(self, *args, **kwargs):
384
+ """Ударные и перкуссия (Channel 9): 36:Kick, 38:Snare, 42:HiHat, 75:Claves, 80:Triangle."""
385
+ start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("t", 0.0)))
386
+ drum_type = int(args[1] if len(args) > 1 else kwargs.get("drum_type", kwargs.get("type", kwargs.get("note", 36))))
387
+ vol = int(kwargs.get("vol", kwargs.get("volume", kwargs.get("velocity", 100))))
388
+
389
+ t_start = max(0.0, start)
390
+ t_end = min(self.duration, t_start + 0.3)
391
+ self.channel_programs[9] = (128, 0)
392
+ p = int(drum_type)
393
+ v = int(np.clip(vol, 1, 127))
394
+ self.midi_events.append((t_start, "on", 9, p, v))
395
+ self.midi_events.append((t_end, "off", 9, p, 0))
396
+
397
+ def _render_fluidsynth(self):
398
+ if not self.midi_events:
399
+ return
400
+ soundfont = get_soundfont_path()
401
+ if soundfont is None:
402
+ raise RuntimeError("Укажите SOUNDFONT_PATH для музыки FluidSynth.")
403
+ try:
404
+ import fluidsynth
405
+ fs = fluidsynth.Synth(samplerate=float(self.sample_rate), gain=0.50)
406
+ sfid = fs.sfload(soundfont)
407
+ if sfid < 0:
408
+ raise RuntimeError("FluidSynth не загрузил SoundFont.")
409
+
410
+ for ch, (b, p) in self.channel_programs.items():
411
+ fs.program_select(ch, sfid, b, p)
412
+ fs.cc(ch, 7, 75)
413
+
414
+ self.midi_events.sort(key=lambda x: (x[0], 0 if x[1] == "off" else 1))
415
+ chunks = []
416
+ cur_t = 0.0
417
+
418
+ for ev_t, ev_type, ch, p, v in self.midi_events:
419
+ if ev_t >= self.duration: break
420
+ dt = ev_t - cur_t
421
+ if dt > 0:
422
+ samples_cnt = int(dt * self.sample_rate)
423
+ if samples_cnt > 0:
424
+ chunks.append(fs.get_samples(samples_cnt))
425
+ cur_t += dt
426
+
427
+ if ev_type == "on": fs.noteon(ch, p, v)
428
+ else: fs.noteoff(ch, p)
429
+
430
+ if cur_t < self.duration:
431
+ remaining_samples = int((self.duration - cur_t) * self.sample_rate)
432
+ if remaining_samples > 0: chunks.append(fs.get_samples(remaining_samples))
433
+
434
+ fs.delete()
435
+
436
+ if chunks:
437
+ raw_audio = np.concatenate(chunks).astype(np.float32).reshape(-1, 2)
438
+ raw_audio = raw_audio / 32768.0
439
+ act_len = min(self.total_samples, len(raw_audio))
440
+ self.master_buffer[:act_len] += raw_audio[:act_len]
441
+
442
+ except Exception as e:
443
+ raise RuntimeError(f"Ошибка FluidSynth: {e}") from e
444
+
445
+ def export_wav(self, out_path: str):
446
+ self._render_fluidsynth()
447
+ peak = np.max(np.abs(self.master_buffer))
448
+ if peak > 0.001: mastered = self.master_buffer * (0.95 / max(peak, 0.95))
449
+ else: mastered = self.master_buffer
450
+
451
+ norm = (np.clip(mastered, -1.0, 1.0) * 32767.0).astype(np.int16)
452
+ with wave.open(out_path, "wb") as wf:
453
+ wf.setnchannels(2)
454
+ wf.setsampwidth(2)
455
+ wf.setframerate(self.sample_rate)
456
+ wf.writeframes(norm.tobytes())
457
+
458
+ UniversalSound = SoundStudio
459
+
460
+
461
+ # -------------------------------------------------------------------------
462
+ # 5. СИСТЕМНЫЙ ПРОМПТ
463
+ # -------------------------------------------------------------------------
464
+ def detect_video_dimensions(prompt: str) -> tuple[int, int]:
465
+ p = str(prompt).lower()
466
+ if any(w in p for w in ["shorts", "шортс", "reels", "рилс", "tiktok", "тикток", "вертикал", "vertical", "9:16", "9/16"]):
467
+ return 1080, 1920
468
+ if any(w in p for w in ["квадрат", "square", "1:1", "1/1"]):
469
+ return 1080, 1080
470
+ return 1920, 1080
471
+
472
+
473
+ SYS_PROMPT_VIDEO = """
474
+ You are an ELITE 2D Animator (PyCairo) and Sound Producer.
475
+ Write high-performance Python code creating an animated scene with synchronized audio, multi-character voice acting, and FluidSynth instruments.
476
+
477
+ ENTRYPOINTS REQUIRED IN YOUR CODE:
478
+ 1. `def draw_frame(ctx: cairo.Context, t: float, w: int, h: int, audio_level: float = 0.0) -> None:`
479
+ - `t`: current time in seconds.
480
+ - `ctx`: PyCairo drawing context (with anti-aliasing).
481
+ - `audio_level`: Dynamic audio volume energy (0.0 to 1.5+). Use it to scale visualizers, pulse steam, or add organic motion.
482
+
483
+ 2. `def build_audio(sound: SoundStudio) -> None:`
484
+ - Compose music, Foley SFX, and dialogue lines (`sound.voice`).
485
+
486
+ CRITICAL CINEMATIC FRAMING & CHARACTER GUIDELINES:
487
+ 1. PROPER CAMERA FRAMING (NO TINY MICROSCOPIC FIGURES!):
488
+ - Use Medium Shot / Close-up framing! Main characters must occupy 40% to 70% of screen height.
489
+ - Do NOT leave 90% of the screen empty. Fill the scene with cozy environment details (e.g. detailed table in foreground, steaming bowl, wallpaper/window/trees in background).
490
+
491
+ 2. EXPRESSIVE 2D STORYBOOK ANATOMY & ACTING:
492
+ - NEVER draw raw geometric stickmen or single-pixel lines!
493
+ - Draw stylized illustrated bodies with clothing & silhouette:
494
+ * Grandma: Shawl/cardigan, apron, glasses with glint, grey bun hair, arm extending with spoon animated via `sin(t)`.
495
+ * Grandson: Hoodie/t-shirt, expressive hands held up in refusal, head turning/leaning back ("I can't eat anymore!").
496
+ * Limbs: Draw arms with thick rounded strokes (`ctx.set_line_cap(cairo.LINE_CAP_ROUND)`, `line_width=16-24px`) with natural elbow bends.
497
+ * Table & Props: Large soup bowl with rising animated steam curves (`ctx.curve_to`), shiny spoon, bread/mugs.
498
+
499
+ 3. MULTI-CHARACTER VOICE ACTING:
500
+ - For dialogues, switch voices appropriately:
501
+ * `sound.voice(start=0.5, text="...", voice="grandma")`
502
+ * `sound.voice(start=5.0, text="...", voice="female_leda")` (or 'male_fast' / young voice)
503
+ * `sound.voice(start=10.0, text="...", voice="grandma")`
504
+ - NEVER put stage directions or asterisks like `*усмехнулась*` in the voice text string.
505
+ - Match 100% of spoken text and on-screen subtitles to the user's prompt language.
506
+
507
+ 4. FLUIDSYNTH INSTRUMENTS (USE EXACT NUMBERS):
508
+ - Birds / Forest: `sound.play(start=0.0, duration=4.0, pitch=60, program=123, vol=75)` (123: Bird Tweet)
509
+ - Water / Ocean: `sound.play(start=0.0, duration=5.0, pitch=60, program=122, vol=70)` (122: Seashore/Water)
510
+ - Spoon clink / Dishes: `sound.play(start=t, duration=0.2, pitch=84, program=9, vol=60)` (9: Glockenspiel) or `sound.drum(start=t, drum_type=80, vol=65)` (80: Triangle)
511
+ - Steps / Wood knock: `sound.drum(start=t, drum_type=75, vol=65)` (75: Claves)
512
+ - Acoustic Guitar: `program=24` | Flute: `program=73` | Strings: `program=48` | Accordion: `program=21`
513
+ - Synth Lead: `program=80` | Bass: `program=33` | Piano: `program=0`
514
+
515
+ PYCAIRO API RULES:
516
+ - Use `ctx.new_path()`, `ctx.close_path()`, `ctx.arc()`, `ctx.curve_to()`.
517
+
518
+ CRITICAL RULES:
519
+ - Output ONLY pure executable Python code without markdown tags.
520
+ """
521
+
522
+ def extract_code_block(text: str) -> str:
523
+ """Безопасно извлекает чистый Python-код из любого ответа модели."""
524
+ text = text.strip()
525
+ match = re.search(r"```(?:python)?\s*([\s\S]*?)\s*```", text, flags=re.IGNORECASE)
526
+ if match:
527
+ return match.group(1).strip()
528
+ clean = re.sub(r"^```(?:python)?\s*", "", text, flags=re.IGNORECASE)
529
+ clean = re.sub(r"\s*```$", "", clean).strip()
530
+ return clean
531
+
532
+ def sanitize_code(code_text: str) -> str:
533
+ clean = extract_code_block(code_text)
534
+ clean = re.sub(r'\bmath\.abs\b', 'abs', clean)
535
+ clean = re.sub(r'\bmath\.min\b', 'min', clean)
536
+ clean = re.sub(r'\bmath\.max\b', 'max', clean)
537
+ clean = re.sub(r'\bmath\.round\b', 'round', clean)
538
+ return clean
539
+
540
+ def get_ffmpeg_binary():
541
+ if shutil.which("ffmpeg"): return "ffmpeg"
542
+ try:
543
+ import imageio_ffmpeg
544
+ return imageio_ffmpeg.get_ffmpeg_exe()
545
+ except Exception: pass
546
+ return None
547
+
548
+
549
+ # -------------------------------------------------------------------------
550
+ # 6. КОНВЕЙЕР ГЕНЕРАЦИИ ВИДЕО (60 FPS + H.264 / AAC)
551
+ # -------------------------------------------------------------------------
552
+ def generate_video_scene(prompt: str, model: str = None, thinking: bool = True, images: list = None, *, scene_code: str | None = None, scene_name: str = "<scene>", strict_frames: bool = False) -> dict:
553
+ duration = float(getattr(config, "VIDEO_DURATION", 15.0))
554
+ fps = int(getattr(config, "VIDEO_FPS", 60))
555
+ sr = int(getattr(config, "AUDIO_SAMPLE_RATE", 44100))
556
+ total_frames = int(duration * fps)
557
+
558
+ target_w, target_h = detect_video_dimensions(prompt)
559
+ aspect_desc = "Vertical 9:16 (1080x1920)" if target_h > target_w else ("Square 1:1 (1080x1080)" if target_w == target_h else "Horizontal 16:9 (1920x1080)")
560
+
561
+ enriched_prompt = (
562
+ f"USER PROMPT: {prompt}\n"
563
+ f"TARGET ASPECT RATIO: {aspect_desc}\n"
564
+ f"CANVAS_WIDTH = {target_w}, CANVAS_HEIGHT = {target_h}, DURATION = {duration}s.\n"
565
+ f"CRITICAL: Keep 100% of spoken text and on-screen typography strictly in the language of the USER PROMPT. "
566
+ f"Use Medium Shot framing (characters occupy 50-70% height). Switch voices for multi-character dialogue."
567
+ )
568
+
569
+ if scene_code is None:
570
+ scene_code = call_gemini(SYS_PROMPT_VIDEO, enriched_prompt, model=model, thinking=thinking, images=images)
571
+ clean_code = sanitize_code(scene_code)
572
+
573
+ auto_imports = (
574
+ "import math\n"
575
+ "from math import sin, cos, tan, pi, sqrt, atan2, radians, degrees, floor, ceil\n"
576
+ "import numpy as np\n"
577
+ "import random\n"
578
+ "import time\n"
579
+ "import colorsys\n"
580
+ "import cairo\n\n"
581
+ )
582
+ if not clean_code.startswith("import math") and "import cairo" not in clean_code:
583
+ clean_code = auto_imports + clean_code
584
+
585
+ exec_scope = {
586
+ "cairo": cairo,
587
+ "math": math, "sin": math.sin, "cos": math.cos, "tan": math.tan,
588
+ "pi": math.pi, "sqrt": math.sqrt, "atan2": math.atan2,
589
+ "radians": math.radians, "degrees": math.degrees,
590
+ "floor": math.floor, "ceil": math.ceil,
591
+ "abs": abs, "min": min, "max": max, "round": round,
592
+ "np": np, "numpy": np, "random": random, "time": time, "colorsys": colorsys,
593
+ "SoundStudio": SoundStudio,
594
+ "UniversalSound": SoundStudio,
595
+ "SoundEngine": SoundStudio,
596
+ "CANVAS_WIDTH": target_w,
597
+ "CANVAS_HEIGHT": target_h,
598
+ "DURATION": duration
599
+ }
600
+
601
+ try:
602
+ exec(compile(clean_code, scene_name, "exec"), exec_scope)
603
+ except Exception as e:
604
+ raise ValueError(f"Ошибка компиляции видео:\n{e}\n\nКод:\n{clean_code[:400]}")
605
+
606
+ draw_frame = exec_scope.get("draw_frame")
607
+ if not draw_frame or not callable(draw_frame):
608
+ raise ValueError("В коде отсутствует функция draw_frame(ctx, t, w, h)!")
609
+ build_audio = exec_scope.get("build_audio")
610
+
611
+ w = int(exec_scope.get("CANVAS_WIDTH", target_w))
612
+ h = int(exec_scope.get("CANVAS_HEIGHT", target_h))
613
+
614
+ if not (16 <= w <= 4096 and 16 <= h <= 4096 and w % 2 == h % 2 == 0):
615
+ raise ValueError("Размер кадра должен быть чётным и от 16 до 4096 пикселей.")
616
+ if total_frames < 1:
617
+ raise ValueError("Длительность слишком мала для выбранного FPS.")
618
+ ffmpeg_bin = get_ffmpeg_binary()
619
+ if not ffmpeg_bin:
620
+ raise RuntimeError("FFmpeg не найден.")
621
+
622
+ base_out = getattr(config, "OUTPUT_DIR", getattr(config, "OUTPUT_FOLDER", "output"))
623
+ out_dir = os.path.join(base_out, "video")
624
+ os.makedirs(out_dir, exist_ok=True)
625
+ uid = uuid.uuid4().hex[:6]
626
+
627
+ temp_v = os.path.join(out_dir, f"raw_{uid}.mp4")
628
+ temp_a = os.path.join(out_dir, f"raw_{uid}.wav")
629
+ final_mp4 = os.path.join(out_dir, f"video_{uid}.mp4")
630
+
631
+ # 1. РЕНДЕРИНГ АУДИО
632
+ sound = SoundStudio(duration=duration, sample_rate=sr)
633
+ if build_audio and callable(build_audio):
634
+ build_audio(sound)
635
+
636
+ sound.export_wav(temp_a)
637
+
638
+ audio_mono = np.mean(sound.master_buffer, axis=1) if len(sound.master_buffer) > 0 else np.zeros(1, dtype=np.float32)
639
+ samples_per_frame = int(sr / fps)
640
+ frame_energies = []
641
+
642
+ for i in range(total_frames):
643
+ s_start = i * samples_per_frame
644
+ s_end = min(len(audio_mono), s_start + samples_per_frame)
645
+ if s_end > s_start:
646
+ chunk = audio_mono[s_start:s_end]
647
+ rms = float(np.sqrt(np.mean(chunk**2))) * 4.2
648
+ frame_energies.append(min(rms, 2.5))
649
+ else:
650
+ frame_energies.append(0.0)
651
+
652
+ # 2. РЕНДЕРИНГ КАДРОВ
653
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
654
+ vw = cv2.VideoWriter(temp_v, fourcc, fps, (w, h))
655
+
656
+ if not vw.isOpened():
657
+ raise RuntimeError("OpenCV не смог открыть MP4 для записи.")
658
+
659
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
660
+ raw_ctx = cairo.Context(surface)
661
+ raw_ctx.set_antialias(cairo.ANTIALIAS_BEST)
662
+ safe_ctx = SafeCairoContext(raw_ctx)
663
+
664
+ accepts_audio_param = False
665
+ try:
666
+ sig = inspect.signature(draw_frame)
667
+ accepts_audio_param = (len(sig.parameters) >= 5) or any(
668
+ p.name == "audio_level" for p in sig.parameters.values()
669
+ )
670
+ except Exception:
671
+ accepts_audio_param = True
672
+
673
+ last_valid_bgr = np.zeros((h, w, 3), dtype=np.uint8)
674
+ error_logged = 0
675
+ first_frame_error = None
676
+ valid_frames = 0
677
+
678
+ for i in range(total_frames):
679
+ t = (i / float(fps)) % duration
680
+ current_energy = frame_energies[i] if i < len(frame_energies) else 0.0
681
+
682
+ try:
683
+ raw_ctx.identity_matrix()
684
+ raw_ctx.new_path()
685
+ if accepts_audio_param:
686
+ if strict_frames:
687
+ draw_frame(safe_ctx, t, w, h, current_energy)
688
+ else:
689
+ try: draw_frame(safe_ctx, t, w, h, current_energy)
690
+ except TypeError: draw_frame(safe_ctx, t, w, h)
691
+ else:
692
+ draw_frame(safe_ctx, t, w, h)
693
+
694
+ surface.flush()
695
+ buf = surface.get_data()
696
+ frame_bgra = np.ndarray(shape=(h, w, 4), dtype=np.uint8, buffer=buf)
697
+ last_valid_bgr = frame_bgra[:, :, :3].copy()
698
+ valid_frames += 1
699
+ except Exception as e:
700
+ if strict_frames:
701
+ first_frame_error = (i, t, e)
702
+ break
703
+ if error_logged < 3:
704
+ print(f"[!] Ошибка draw_frame на t={t:.2f}s: {e}")
705
+ error_logged += 1
706
+
707
+ vw.write(last_valid_bgr)
708
+
709
+ vw.release()
710
+ surface.finish()
711
+
712
+ try:
713
+ if first_frame_error is not None:
714
+ frame, timestamp, exc = first_frame_error
715
+ raise RuntimeError(f"Frame {frame} at {timestamp:.3f}s failed: {exc}") from exc
716
+ if valid_frames == 0:
717
+ raise RuntimeError("Сцена не смогла нарисовать ни одного кадра.")
718
+ subprocess.run(
719
+ [ffmpeg_bin, "-loglevel", "error", "-y", "-i", temp_v, "-i", temp_a,
720
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
721
+ "-c:a", "aac", "-b:a", "192k", "-shortest", final_mp4],
722
+ check=True,
723
+ )
724
+ except Exception:
725
+ if os.path.isfile(final_mp4):
726
+ os.remove(final_mp4)
727
+ raise
728
+ finally:
729
+ for temporary in (temp_v, temp_a):
730
+ if os.path.isfile(temporary):
731
+ os.remove(temporary)
732
+
733
+ return {
734
+ "type": "video",
735
+ "video_path": final_mp4,
736
+ "resolution": f"{w}x{h}",
737
+ "duration": f"{duration:.1f}s",
738
+ "fps": fps
739
+ }
anime-2d-reference-kit/engine/motion_review.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inspect isolated actor animation without camera, captions or background effects."""
2
+ import json
3
+ import math
4
+ from pathlib import Path
5
+ import runpy
6
+
7
+ import cairo
8
+ import cv2
9
+ import numpy as np
10
+
11
+ WIDTH, HEIGHT = 384, 288
12
+ RATE = 12
13
+
14
+
15
+ def validate_motion(items, duration):
16
+ if not isinstance(items, list) or not 1 <= len(items) <= 24:
17
+ raise ValueError("motion requires 1–24 character beats")
18
+ for beat in items:
19
+ if not isinstance(beat, dict) or set(beat) != {"actor", "start", "end", "mode", "action"}:
20
+ raise ValueError("Motion beat must contain actor, start, end, mode and action")
21
+ if not all(isinstance(beat[key], str) and 0 < len(beat[key].strip()) <= 120 for key in ("actor", "action")):
22
+ raise ValueError("Motion needs a named actor and a concrete action")
23
+ a, b = beat["start"], beat["end"]
24
+ if (type(a) not in (int, float) or type(b) not in (int, float)
25
+ or not 0 <= a < b <= duration or not .34 <= b - a <= 10
26
+ or beat["mode"] not in ("gesture", "continuous")):
27
+ raise ValueError("Motion needs a 0.34–10 second interval and gesture or continuous mode")
28
+
29
+
30
+ def snapshot(draw, timestamp):
31
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
32
+ context = cairo.Context(surface)
33
+ draw(context, timestamp, WIDTH, HEIGHT)
34
+ surface.flush()
35
+ source = np.ndarray((HEIGHT, WIDTH, 4), dtype=np.uint8, buffer=surface.get_data(),
36
+ strides=(surface.get_stride(), 4, 1)).copy()
37
+ surface.finish()
38
+ return source
39
+
40
+
41
+ def inspect_motion(scene, items, output):
42
+ actors = runpy.run_path(scene).get("REVIEW_ACTORS", {})
43
+ if not isinstance(actors, dict):
44
+ raise ValueError("REVIEW_ACTORS must be a dictionary")
45
+ output = Path(output)
46
+ output.mkdir(parents=True, exist_ok=True)
47
+ findings = []
48
+ for idx, beat in enumerate(items, 1):
49
+ draw = actors.get(beat["actor"])
50
+ if not callable(draw):
51
+ raise ValueError(f"Missing REVIEW_ACTORS renderer for {beat['actor']}")
52
+ count = math.ceil((beat["end"] - beat["start"]) * RATE) + 1
53
+ times = np.linspace(beat["start"], beat["end"], count)
54
+ picks = set(np.linspace(0, count - 1, min(count, 6), dtype=int))
55
+ previous = None
56
+ still = longest = active = 0
57
+ strips = []
58
+ for n, t in enumerate(times):
59
+ current = snapshot(draw, float(t))
60
+ mask = current[:, :, 3] > 12
61
+ area = int(mask.sum())
62
+ if not 80 <= area <= WIDTH * HEIGHT * .82:
63
+ raise ValueError(f"{beat['actor']} must draw a readable actor on transparency, frame {n}")
64
+ if previous is not None:
65
+ union = mask | (previous[:, :, 3] > 12)
66
+ changed = np.max(cv2.absdiff(current, previous), axis=2) > 12
67
+ moving = bool((changed & union).sum() / union.sum() >= .008)
68
+ active += int(moving)
69
+ still = 0 if moving else still + 1
70
+ longest = max(longest, still)
71
+ if n in picks:
72
+ alpha = current[:, :, 3:4].astype(np.float32) / 255
73
+ preview = np.clip(current[:, :, :3] + (1-alpha) * np.array([76, 53, 32]), 0, 255).astype(np.uint8)
74
+ cv2.putText(preview, f"{t:.2f}s", (10, HEIGHT-12), cv2.FONT_HERSHEY_SIMPLEX,
75
+ .55, (255,255,255), 1, cv2.LINE_AA)
76
+ strips.append(preview)
77
+ previous = current
78
+ fraction = active / (count-1)
79
+ hold = float(longest * (times[1]-times[0]))
80
+ passed = active >= 2 if beat["mode"] == "gesture" else fraction >= .35 and hold <= .64
81
+ filename = f"actor-{idx:02d}.jpg"
82
+ if not cv2.imwrite(str(output / filename), np.hstack(strips)):
83
+ raise RuntimeError(f"Cannot write {filename}")
84
+ findings.append({**beat, "active_fraction": round(fraction, 3),
85
+ "longest_hold_seconds": round(float(hold), 3), "strip": filename, "passed": passed})
86
+ return {"passed": all(item["passed"] for item in findings), "beats": findings}
87
+
88
+
anime-2d-reference-kit/engine/render.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render a reviewed Cairo scene or generate one via the original Gemini flow."""
2
+ import argparse
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+
7
+ import config
8
+
9
+
10
+ def main():
11
+ parser = argparse.ArgumentParser(description=__doc__)
12
+ source = parser.add_mutually_exclusive_group(required=True)
13
+ source.add_argument("--scene", type=Path, help="Trusted Python scene file")
14
+ source.add_argument("--prompt", help="Generate scene code via Gemini first")
15
+ parser.add_argument("--duration", type=float, default=config.VIDEO_DURATION)
16
+ parser.add_argument("--fps", type=int, default=config.VIDEO_FPS)
17
+ parser.add_argument("--format", choices=("horizontal", "vertical", "square"), default="horizontal")
18
+ parser.add_argument("--out", type=Path, default=Path(config.OUTPUT_DIR))
19
+ parser.add_argument("--no-thinking", action="store_true")
20
+ parser.add_argument("--strict-frames", action="store_true")
21
+ args = parser.parse_args()
22
+ if not math.isfinite(args.duration) or not (0 < args.duration <= 300):
23
+ parser.error("--duration must be greater than zero and at most 300 seconds")
24
+ if not 1 <= args.fps <= 120:
25
+ parser.error("--fps must be between 1 and 120")
26
+
27
+ config.VIDEO_DURATION = args.duration
28
+ config.VIDEO_FPS = args.fps
29
+ config.OUTPUT_DIR = str(args.out)
30
+ from modules.mod_video import generate_video_scene
31
+
32
+ result = generate_video_scene(
33
+ args.prompt or args.format,
34
+ thinking=not args.no_thinking,
35
+ scene_code=args.scene.read_text(encoding="utf-8-sig") if args.scene else None,
36
+ scene_name=str(args.scene) if args.scene else "<gemini-scene>",
37
+ strict_frames=args.strict_frames,
38
+ )
39
+ print(json.dumps(result, ensure_ascii=False))
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()
anime-2d-reference-kit/engine/render_request.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate a render request and expose its settings to GitHub Actions."""
2
+ import json
3
+ import math
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import subprocess
8
+
9
+ from final_review import validate_final_review
10
+
11
+
12
+ def read_request():
13
+ if os.environ["EVENT"] == "workflow_dispatch":
14
+ return json.loads(os.environ["INPUTS"])
15
+ added = subprocess.check_output(
16
+ ["git", "diff-tree", "--root", "--no-commit-id", "--diff-filter=A", "-r",
17
+ "--name-only", "HEAD", "--", "render-requests/"],
18
+ text=True,
19
+ ).splitlines()
20
+ requests = [p for p in added if re.fullmatch(r"render-requests/[a-z0-9-]+\.json", p)]
21
+ if len(requests) != 1:
22
+ raise SystemExit("Add exactly one new render-requests/<id>.json per launch commit.")
23
+ return json.loads(Path(requests[0]).read_text(encoding="utf-8"))
24
+
25
+
26
+ def main():
27
+ request = read_request()
28
+ root = Path("scenes").resolve(strict=True)
29
+ raw_scene = request["scene"]
30
+ if not re.fullmatch(r"scenes/(?:[a-zA-Z0-9_-]+/)*[a-zA-Z0-9_-]+\.py", raw_scene):
31
+ raise SystemExit("Choose a Python file under scenes/.")
32
+ scene = Path(raw_scene).resolve(strict=True)
33
+ if not scene.is_relative_to(root) or not scene.is_file():
34
+ raise SystemExit("Scene must be a file under scenes/.")
35
+ duration = float(request.get("duration", 3))
36
+ fps_value = str(request.get("fps", 30))
37
+ video_format = request.get("format", "horizontal")
38
+ voice = request.get("voice", False)
39
+ if not math.isfinite(duration) or not 0 < duration <= 300:
40
+ raise SystemExit("Duration must be greater than zero and at most 300 seconds.")
41
+ if not re.fullmatch(r"[0-9]{1,3}", fps_value) or not 1 <= int(fps_value) <= 120:
42
+ raise SystemExit("FPS must be between 1 and 120.")
43
+ if video_format not in ("horizontal", "vertical", "square") or not isinstance(voice, bool):
44
+ raise SystemExit("Invalid video format or voice option.")
45
+ stage = request.get("stage", "standard")
46
+ if stage not in ("standard", "assets", "draft", "final"):
47
+ raise SystemExit("Invalid render stage.")
48
+ checks = request.get("checkpoints", [])
49
+ if not isinstance(checks, list) or len(checks) > 20:
50
+ raise SystemExit("Supply at most 20 checkpoints.")
51
+ if stage in ("draft", "final") and not checks:
52
+ raise SystemExit("Draft and final requests require checkpoints.")
53
+ for check in checks:
54
+ if (not isinstance(check, dict) or set(check) != {"time", "label"}
55
+ or type(check["time"]) not in (int, float) or not 0 <= check["time"] < duration
56
+ or not isinstance(check["label"], str) or not 0 < len(check["label"].strip()) <= 100):
57
+ raise SystemExit("Checkpoint requires an in-range time and a short label.")
58
+ motion = request.get("motion")
59
+ if motion is not None:
60
+ from motion_review import validate_motion
61
+ validate_motion(motion, duration)
62
+ print("motion=" + json.dumps(motion or [], ensure_ascii=True, separators=(",", ":")))
63
+ if stage == "final":
64
+ validate_final_review(request)
65
+ print(f"stage={stage}")
66
+ print("checkpoints=" + json.dumps(checks, ensure_ascii=True, separators=(",", ":")))
67
+ print(f"scene={raw_scene}")
68
+ print(f"duration={duration}")
69
+ print(f"fps={int(fps_value)}")
70
+ print(f"format={video_format}")
71
+ print(f"voice={str(voice).lower()}")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
anime-2d-reference-kit/engine/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ google-genai
2
+ imageio-ffmpeg
3
+ numpy
4
+ opencv-python-headless
5
+ pycairo
6
+ pyfluidsynth
7
+ requests
8
+ scipy
anime-2d-reference-kit/engine/review_assets.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render isolated Cairo assets for visual review before assembling the film."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ import runpy
7
+
8
+ import cairo
9
+ import numpy as np
10
+
11
+
12
+ WIDTH, HEIGHT = 768, 512
13
+
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser(description=__doc__)
17
+ parser.add_argument("scene", type=Path)
18
+ parser.add_argument("--out", type=Path, default=Path("output/assets"))
19
+ args = parser.parse_args()
20
+ root = Path("scenes").resolve(strict=True)
21
+ scene = args.scene.resolve(strict=True)
22
+ if not scene.is_relative_to(root) or scene.suffix != ".py":
23
+ raise SystemExit("Choose a trusted Python scene under scenes/.")
24
+ assets = runpy.run_path(str(scene)).get("REVIEW_ASSETS")
25
+ if not isinstance(assets, dict) or not 1 <= len(assets) <= 300:
26
+ raise SystemExit("REVIEW_ASSETS must contain 1–300 named object or pose renderers.")
27
+ args.out.mkdir(parents=True, exist_ok=True)
28
+ report = {}
29
+ for name, draw in assets.items():
30
+ if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,55}", name) or not callable(draw):
31
+ raise SystemExit(f"Invalid asset name or renderer: {name!r}")
32
+ object_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
33
+ object_ctx = cairo.Context(object_surface)
34
+ object_ctx.set_antialias(cairo.ANTIALIAS_BEST)
35
+ draw(object_ctx, WIDTH, HEIGHT)
36
+ object_surface.flush()
37
+ pixels = np.ndarray((HEIGHT, WIDTH), dtype=np.uint32,
38
+ buffer=object_surface.get_data(),
39
+ strides=(object_surface.get_stride(), 4))
40
+ y, x = np.nonzero((pixels >> 24) >= 4)
41
+ if not x.size:
42
+ raise RuntimeError(f"{name} drew no visible pixels.")
43
+
44
+ contact_sheet = cairo.ImageSurface(cairo.FORMAT_RGB24, 2 * WIDTH + 16, HEIGHT)
45
+ ctx = cairo.Context(contact_sheet)
46
+ ctx.set_source_rgb(.11, .19, .29)
47
+ ctx.paint()
48
+ palettes = (((.65, .82, .96), (.36, .60, .80)),
49
+ ((.20, .37, .55), (.06, .13, .24)))
50
+ for index, (top, bottom) in enumerate(palettes):
51
+ ctx.save()
52
+ ctx.translate(index * (WIDTH + 16), 0)
53
+ ctx.rectangle(0, 0, WIDTH, HEIGHT)
54
+ ctx.clip()
55
+ gradient = cairo.LinearGradient(0, 0, WIDTH * .65, HEIGHT)
56
+ gradient.add_color_stop_rgb(0, *top)
57
+ gradient.add_color_stop_rgb(1, *bottom)
58
+ ctx.set_source(gradient)
59
+ ctx.paint()
60
+ ctx.set_source_surface(object_surface, 0, 0)
61
+ ctx.paint()
62
+ ctx.restore()
63
+
64
+ filename = name + ".png"
65
+ contact_sheet.write_to_png(str(args.out / filename))
66
+ contact_sheet.finish()
67
+ bounds = [int(x.min()), int(y.min()), int(x.max()), int(y.max())]
68
+ if bounds == [0, 0, WIDTH - 1, HEIGHT - 1] and np.all((pixels >> 24) == 255):
69
+ print(f"WARNING {name}: isolated renderer paints the entire canvas. "
70
+ "Remove its background unless this is the background artwork itself.")
71
+ report[name] = filename
72
+ del pixels
73
+ object_surface.finish()
74
+ (args.out / "assets.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
75
+ print(f"Rendered {len(report)} isolated asset views.")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
anime-2d-reference-kit/engine/review_video.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify the exported MP4 and extract frame strips around action checkpoints."""
2
+ import argparse
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ import shutil
7
+ import subprocess
8
+
9
+ import cv2
10
+ import numpy as np
11
+
12
+
13
+ def run(*args):
14
+ return subprocess.check_output(args, stderr=subprocess.STDOUT)
15
+
16
+
17
+ def label(image, line, time):
18
+ font = cv2.FONT_HERSHEY_SIMPLEX
19
+ cv2.rectangle(image, (0, image.shape[0] - 31), (image.shape[1], image.shape[0]), (24, 24, 24), -1)
20
+ cv2.putText(image, f"{line} {time:.3f}s", (8, image.shape[0] - 10), font, .52, (255, 255, 255), 1, cv2.LINE_AA)
21
+ return image
22
+
23
+
24
+ def main():
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("video", type=Path)
27
+ parser.add_argument("--duration", type=float, required=True)
28
+ parser.add_argument("--fps", type=int, required=True)
29
+ parser.add_argument("--checkpoints", type=json.loads, default=[])
30
+ parser.add_argument("--out", type=Path, default=Path("output/review"))
31
+ parser.add_argument("--motion", type=json.loads, default=[])
32
+ parser.add_argument("--scene")
33
+ args = parser.parse_args()
34
+ if args.motion and not args.scene:
35
+ parser.error("--scene is required when motion beats are supplied")
36
+
37
+ ffprobe, ffmpeg = shutil.which("ffprobe"), shutil.which("ffmpeg")
38
+ if not ffprobe or not ffmpeg:
39
+ raise SystemExit("Review requires ffprobe and ffmpeg.")
40
+ probe = json.loads(run(ffprobe, "-v", "error", "-count_frames", "-show_streams",
41
+ "-show_format", "-of", "json", str(args.video)))
42
+ stream = next((s for s in probe["streams"] if s["codec_type"] == "video"), {})
43
+ audio = next((s for s in probe["streams"] if s["codec_type"] == "audio"), {})
44
+ count = int(args.duration * args.fps)
45
+ fps_ratio = stream.get("avg_frame_rate", "0/1").split("/")
46
+ duration = float(probe["format"]["duration"])
47
+ if (stream.get("codec_name") != "h264" or audio.get("codec_name") != "aac"
48
+ or int(stream.get("nb_read_frames", -1)) != count
49
+ or not int(fps_ratio[1]) or not math.isclose(int(fps_ratio[0]) / int(fps_ratio[1]), args.fps)
50
+ or abs(duration - args.duration) > 1 / args.fps + .05):
51
+ raise SystemExit("MP4 streams, frame count, FPS or duration do not match the render request.")
52
+ pcm = np.frombuffer(run(ffmpeg, "-v", "error", "-xerror", "-i", str(args.video),
53
+ "-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"), dtype="<f4")
54
+ if not pcm.size or not np.isfinite(pcm).all():
55
+ raise SystemExit("The audio track could not be decoded.")
56
+ peak = float(np.max(np.abs(pcm)))
57
+ rms = math.sqrt(float(np.mean(np.square(pcm))))
58
+ args.out.mkdir(parents=True, exist_ok=True)
59
+ video = cv2.VideoCapture(str(args.video))
60
+ atlas = []
61
+ try:
62
+ for number, check in enumerate(args.checkpoints, 1):
63
+ center = int(round(check["time"] * args.fps))
64
+ delta = max(1, round(args.fps * .065))
65
+ indices = sorted({max(0, min(count - 1, center + step * delta)) for step in (-2, -1, 0, 1, 2)})
66
+ tiles = []
67
+ for index in indices:
68
+ video.set(cv2.CAP_PROP_POS_FRAMES, index)
69
+ ok, frame = video.read()
70
+ if not ok:
71
+ raise RuntimeError(f"Cannot read checkpoint {number}, frame {index}.")
72
+ w = min(frame.shape[1], 480)
73
+ h = max(40, round(frame.shape[0] * w / frame.shape[1]))
74
+ tile = cv2.resize(frame, (w, h), interpolation=cv2.INTER_AREA)
75
+ tiles.append(label(tile, f"{number:02d}", index / args.fps))
76
+ name = f"checkpoint-{number:02d}.jpg"
77
+ if not cv2.imwrite(str(args.out / name), np.hstack(tiles)):
78
+ raise RuntimeError(f"Cannot save {name}.")
79
+ atlas.append({**check, "strip": name, "frames": indices,
80
+ "seconds": [round(index / args.fps, 4) for index in indices]})
81
+ finally:
82
+ video.release()
83
+
84
+ report = {"duration_seconds": duration, "frame_count": count, "fps": args.fps,
85
+ "resolution": [stream["width"], stream["height"]], "video_codec": "h264",
86
+ "audio_codec": "aac", "audio_peak": peak, "audio_rms": rms,
87
+ "audio_appears_silent": peak < 0.0001, "checkpoints": atlas}
88
+ if args.motion:
89
+ from motion_review import inspect_motion, validate_motion
90
+ validate_motion(args.motion, args.duration)
91
+ report["actor_motion"] = inspect_motion(args.scene, args.motion, args.out)
92
+ (args.out / "review.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
93
+ print(f"Verified {count} frames at {args.fps} fps; audio peak {peak:.4f}; {len(atlas)} checkpoint strips.")
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
anime-2d-reference-kit/engine/scenes/motion-example.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example of sharing actual actor motion between the shot and the review."""
2
+ import math
3
+
4
+
5
+ def segment(ctx, points, color, width):
6
+ ctx.set_source_rgb(*color)
7
+ ctx.set_line_width(width)
8
+ ctx.set_line_cap(1)
9
+ ctx.move_to(*points[0])
10
+ for point in points[1:]:
11
+ ctx.line_to(*point)
12
+ ctx.stroke()
13
+
14
+
15
+ def circle(ctx, x, y, radius, color):
16
+ ctx.set_source_rgb(*color)
17
+ ctx.arc(x, y, radius, 0, math.tau)
18
+ ctx.fill()
19
+
20
+
21
+ def pose(t):
22
+ anticipation = math.exp(-((t-.55)/.23)**2)
23
+ lift = max(0., min(1., (t-.55)/.9))
24
+ lift = lift*lift*(3-2*lift)
25
+ settle = max(0., 1-abs(t-1.64)*2.6)
26
+ return anticipation, lift, settle
27
+
28
+
29
+ def actor(ctx, t, width, height):
30
+ ctx.save()
31
+ ctx.translate(width/2, height*.51)
32
+ ctx.scale(height/288, height/288)
33
+ anticipate, lift, settle = pose(t)
34
+ lean = -6*anticipate+10*lift
35
+ cloth = (.13,.27,.43)
36
+ skin = (.85,.62,.46)
37
+ segment(ctx, [(0,23),(lean,72),(lean-3,115)], cloth, 71)
38
+ segment(ctx, [(lean-23,46),(lean-45,79),(lean-31,113)], cloth, 19)
39
+ shoulder=(lean+24,43)
40
+ angle=.86-1.55*lift
41
+ elbow=(shoulder[0]+39*math.cos(angle),shoulder[1]+39*math.sin(angle))
42
+ wrist=(elbow[0]+32*math.cos(angle-1.05*lift),elbow[1]+32*math.sin(angle-1.05*lift))
43
+ segment(ctx,[shoulder,elbow],cloth,19)
44
+ segment(ctx,[elbow,wrist],skin,13)
45
+ circle(ctx,*wrist,8,skin)
46
+ ctx.save()
47
+ ctx.translate(lean,-13-2*settle)
48
+ ctx.rotate(.12*anticipate-.10*lift)
49
+ circle(ctx,0,-5,36,(.12,.14,.18))
50
+ circle(ctx,4,4,29,skin)
51
+ for x in (-5,14):
52
+ blink = math.exp(-((t-1.8)/.08)**2)
53
+ segment(ctx,[(x-4,1),(x+4,1)],(.15,.21,.26),max(1,6*(1-blink)))
54
+ mouth = 2+3*abs(math.sin(t*19))*settle
55
+ circle(ctx,11,17,mouth,(.28,.15,.16))
56
+ ctx.restore()
57
+ ctx.restore()
58
+
59
+
60
+ def draw_frame(ctx, t, width, height, audio_level=0):
61
+ ctx.set_source_rgb(.08,.13,.24)
62
+ ctx.paint()
63
+ actor(ctx,t,width,height)
64
+
65
+
66
+ REVIEW_ACTORS = {"envoy": actor}
67
+ REVIEW_ASSETS = {"envoy": lambda ctx,w,h: actor(ctx,1.25,w,h)}
68
+ CANVAS_WIDTH, CANVAS_HEIGHT = 640, 360
anime-2d-reference-kit/image-prompts.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 01-human-silhouettes
2
+
3
+ Wide horizontal polished original hand-drawn 2D anime character model sheet, high-end animated-film preproduction, five distinct full body people spaced far apart head-to-toe in one clean row, soft desaturated pale blue studio backdrop and faint grounding lines. Left to right: lively 9-year-old girl in yellow raincoat and boots (short compact proportions); tall slender young adult man with long teal overcoat and reserved posture; strong broad-shouldered middle-aged woman in practical work jacket rolled sleeves and utility boots; short plus-size young adult man in moss green cardigan with round face and gentle smile; elderly grandmother with short silver hair in a bun, fine smile lines, slight stoop and a knitted burgundy cardigan, warm and capable, holding a walking cane. Each figure has a clearly recognizable face and body construction, accurate hand anatomy, beautiful weighted organic ink contours, sophisticated cel shading and restrained palette, expressive natural postures, distinctly different heads and silhouettes. All designs original, no text or logos, no grid, no borders. Reference sheet with no overlap or clipped figures. No geometrical primitive or faceted low-poly look, no 3D render. All figures sharp and readable.
4
+
5
+ 02-grandmother-turnaround
6
+
7
+ Landscape original 2D anime animation model sheet, same elderly grandmother across the sheet: softly stooped, silver low bun, small warm amber eyes and smile lines, burgundy knitted cardigan, cream blouse, dark sage long skirt, practical brown shoes. Upper row three clearly separated complete full-body views front, three-quarter and true side profile, aligned proportions, neutral natural hands and slightly bent knees, no walking cane so silhouette is legible. Lower row four independent face closeups: gentle smile, concern, speaking, and amused eyes. High-end hand-drawn anime, fine organic ink contours, designed skull, jaw and anatomy, precise eyes, clean cel shading, very light blue background. Identical hair, face, garment and body design across all views. Clean breathing room, no cut-off feet, no props, no written labels, no letters or logos.
8
+
9
+ 03-animal-designs
10
+
11
+ Wide landscape studio-production model sheet with six animal character designs in a tidy 3 by 2 array with generous spacing and pale blue matte background, original gorgeous hand-drawn anime movie art. Upper row ginger domestic cat (playful walking), tricolor shepherd dog (friendly standing), white-and-grey rabbit (crouched ears raised). Lower row red fox (alert walking), dark brown horse (standing at three-quarter side), small blue songbird (perched and alert). Show complete bodies and feet/tails. Natural species-specific anatomy, beautiful organic confident lines with subtle line weight, art director quality simplified fur masses and careful cel shadows, each species recognizably different, silhouettes are easy to stage and animate. Consistent lighting, no text, no letters, no borders, no captions, no overlapping animals, no low-poly or 3D aesthetic.
12
+
13
+ 04-interior-kitchen
14
+
15
+ One cinematic landscape anime background painting, detailed lived-in rural kitchen at late afternoon, entirely empty of characters and animals, eye-level medium wide view with a clear foreground staging area near a wood table, warm stove nook with copper kettle at the back, muted teal cupboard, lavender curtains, window with soft afternoon sunlight, houseplants and antique utensils. Organic hand-painted textures treated with Japanese 2D animation background sensibility, beautiful perspective, layered depth from foreground to distant trees visible through window, masterfully controlled value hierarchy, cozy burnt umber, ivory and teal palette. Set up so drawn human characters can be composited on top. No text, no logos, no panel borders.
16
+
17
+ 05-exterior-village
18
+
19
+ One cinematic landscape Japanese 2D animated movie environment design, picturesque small village square with an old bookshop and bakery facades in the middle distance, cobbled path with room for a character to walk across the foreground, autumn sunlight, flower boxes, warm brick and wooden shutters, distant hilly horizon. Eye-level three-quarter perspective, purposeful depth layers, refined brushwork, rich blue shadows and warm amber light, visually clean staging. Entirely empty of people and animals. No text, no signs with letters, no logos, no panel borders.
20
+
21
+ 06-exterior-forest
22
+
23
+ One cinematic landscape environment reference for an original 2D anime film, lush temperate woodland edge with mossy stones and ferns beside a gently angled footpath, layered trees and a glint of stream in midground, blue-green fog and warm shaft of sun. Spacious simple near section suitable for staging an actor and an animal. Carefully designed foreground, middle ground and background, high-end hand-painted organic 2D anime background, deep atmospheric perspective, deliberate tonal hierarchy. Empty of people and animals. No text or logos, no panel borders.
anime-2d-reference-kit/references/01-human-silhouettes.png ADDED

Git LFS Details

  • SHA256: a6a84da05493064c9272ced59b70a91d0a4a58a50bdbfcaaa4ec74c9e5128a0d
  • Pointer size: 132 Bytes
  • Size of remote file: 2.2 MB
anime-2d-reference-kit/references/02-grandmother-turnaround.png ADDED

Git LFS Details

  • SHA256: a18cb9b18fdba2c0ad57fd0fae9eee6085672f0073f1df53fcc3853bacacbd33
  • Pointer size: 132 Bytes
  • Size of remote file: 2.08 MB
anime-2d-reference-kit/references/03-animal-designs.png ADDED

Git LFS Details

  • SHA256: a7cd8878a63938eee7a34750ed87282b51b29c5e2df6105cc04ee5de08ae57f0
  • Pointer size: 132 Bytes
  • Size of remote file: 1.98 MB
anime-2d-reference-kit/references/04-interior-kitchen.png ADDED

Git LFS Details

  • SHA256: 7eb5689156bdb9e2d3d89d072899ef13fa735da7659e25b74e52511be32cf3a9
  • Pointer size: 132 Bytes
  • Size of remote file: 2.8 MB
anime-2d-reference-kit/references/05-exterior-village.png ADDED

Git LFS Details

  • SHA256: 0836699aa37801e0371def22b9eb9ad795b988241ffc2c7dc1aeae24b8470322
  • Pointer size: 132 Bytes
  • Size of remote file: 3.31 MB
anime-2d-reference-kit/references/06-exterior-forest.png ADDED

Git LFS Details

  • SHA256: fb89c1b46f4bcf058ae69af071568a1ea56acdf0ee3c06ee3b7f7a0dd23c656c
  • Pointer size: 132 Bytes
  • Size of remote file: 2.65 MB