catime 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ name: Hourly Cat Generator
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 * * * *' # Every hour at :00
6
+ workflow_dispatch: # Allow manual trigger
7
+
8
+ permissions:
9
+ contents: write
10
+ issues: write
11
+
12
+ concurrency:
13
+ group: hourly-cat
14
+ cancel-in-progress: false
15
+
16
+ jobs:
17
+ generate-cat:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - uses: actions/setup-python@v5
23
+ with:
24
+ python-version: '3.12'
25
+
26
+ - name: Install dependencies
27
+ run: pip install nanobanana-py
28
+
29
+ - name: Generate cat and update repo
30
+ env:
31
+ GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
32
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
33
+ CAT_ISSUE_NUMBER: '1'
34
+ NANOBANANA_MODEL: gemini-3-pro-image-preview
35
+ NANOBANANA_TIMEOUT: '180'
36
+ NANOBANANA_FALLBACK_MODELS: gemini-3-pro-image-preview,gemini-2.5-flash-image
37
+ run: python scripts/generate_cat.py
@@ -0,0 +1,29 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ id-token: write
10
+
11
+ jobs:
12
+ publish:
13
+ runs-on: ubuntu-latest
14
+ environment: pypi
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: '3.12'
21
+
22
+ - name: Install uv
23
+ run: pip install uv
24
+
25
+ - name: Build
26
+ run: uv build
27
+
28
+ - name: Publish
29
+ run: uv publish --trusted-publishing always
@@ -0,0 +1,5 @@
1
+ dist/
2
+ .venv/
3
+ __pycache__/
4
+ *.egg-info/
5
+ uv.lock
catime-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yazelin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
catime-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: catime
3
+ Version: 0.2.0
4
+ Summary: AI-generated hourly cat images - a new cat every hour!
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: httpx
9
+ Description-Content-Type: text/markdown
10
+
11
+ # catime
12
+
13
+ AI-generated hourly cat images. A new cat every hour!
14
+
15
+ ## Usage
16
+
17
+ ```bash
18
+ uvx catime # Show total cat count
19
+ uvx catime 42 # View cat #42
20
+ uvx catime today # List today's cats
21
+ uvx catime yesterday # List yesterday's cats
22
+ uvx catime 2026-01-30 # List all cats from a date
23
+ uvx catime 2026-01-30T05 # View the cat from a specific hour
24
+ uvx catime --list # List all cats
25
+ ```
catime-0.2.0/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # catime
2
+
3
+ AI-generated hourly cat images. A new cat every hour!
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ uvx catime # Show total cat count
9
+ uvx catime 42 # View cat #42
10
+ uvx catime today # List today's cats
11
+ uvx catime yesterday # List yesterday's cats
12
+ uvx catime 2026-01-30 # List all cats from a date
13
+ uvx catime 2026-01-30T05 # View the cat from a specific hour
14
+ uvx catime --list # List all cats
15
+ ```
@@ -0,0 +1,15 @@
1
+ [
2
+ {
3
+ "number": 1,
4
+ "timestamp": "2026-01-30 05:46 UTC",
5
+ "url": "https://github.com/yazelin/ccat/releases/download/cats/cat_2026-01-30_0546_UTC.png",
6
+ "model": "gemini-2.5-flash-image"
7
+ },
8
+ {
9
+ "number": 2,
10
+ "timestamp": "2026-01-30 05:56 UTC",
11
+ "url": "https://github.com/yazelin/ccat/releases/download/cats/cat_2026-01-30_0556_UTC.png",
12
+ "model": "gemini-3-pro-image-preview",
13
+ "status": "success"
14
+ }
15
+ ]
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "catime"
7
+ version = "0.2.0"
8
+ description = "AI-generated hourly cat images - a new cat every hour!"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dependencies = ["httpx"]
13
+
14
+ [project.scripts]
15
+ catime = "catime.cli:main"
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["src/catime"]
@@ -0,0 +1,189 @@
1
+ """Generate a cat image using nanobanana-py, upload as GitHub Release asset. Run by GitHub Actions hourly."""
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ REPO = os.environ.get("GITHUB_REPOSITORY", "yazelin/catime")
12
+ ISSUE_NUMBER = os.environ.get("CAT_ISSUE_NUMBER", "1")
13
+ RELEASE_TAG = "cats"
14
+
15
+
16
+ async def generate_cat_image(output_dir: str, timestamp: str) -> dict:
17
+ """Use nanobanana-py's ImageGenerator to generate a cat image."""
18
+ from nanobanana_py.image_generator import ImageGenerator
19
+ from nanobanana_py.types import ImageGenerationRequest
20
+
21
+ generator = ImageGenerator()
22
+
23
+ request = ImageGenerationRequest(
24
+ prompt=f"畫一隻可愛的貓,並在圖片中顯示現在的日期與時間: {timestamp}",
25
+ filename=f"cat_{timestamp.replace(' ', '_').replace(':', '')}",
26
+ resolution="1K",
27
+ file_format="png",
28
+ parallel=1,
29
+ output_count=1,
30
+ )
31
+
32
+ os.environ["NANOBANANA_OUTPUT_DIR"] = output_dir
33
+ response = await generator.generate_text_to_image(request)
34
+
35
+ if not response.success:
36
+ return {
37
+ "file_path": None,
38
+ "model_used": None,
39
+ "status": "failed",
40
+ "error": f"{response.message} - {response.error}",
41
+ }
42
+
43
+ model_info = response.model_used or "unknown"
44
+ if response.used_fallback:
45
+ model_info += f" (fallback from {response.primary_model}, reason: {response.fallback_reason})"
46
+
47
+ return {
48
+ "file_path": response.generated_files[0],
49
+ "model_used": model_info,
50
+ "status": "success",
51
+ }
52
+
53
+
54
+ def ensure_release_exists():
55
+ """Create the 'cats' release if it doesn't exist."""
56
+ result = subprocess.run(
57
+ ["gh", "release", "view", RELEASE_TAG, "--repo", REPO],
58
+ capture_output=True, text=True,
59
+ )
60
+ if result.returncode != 0:
61
+ subprocess.run(
62
+ [
63
+ "gh", "release", "create", RELEASE_TAG,
64
+ "--repo", REPO,
65
+ "--title", "Cat Images",
66
+ "--notes", "Auto-generated cat images, one every hour.",
67
+ ],
68
+ check=True,
69
+ )
70
+
71
+
72
+ def upload_image_as_release_asset(image_path: str) -> str:
73
+ """Upload image as a GitHub Release asset. Returns the public download URL."""
74
+ filename = Path(image_path).name
75
+
76
+ subprocess.run(
77
+ [
78
+ "gh", "release", "upload", RELEASE_TAG,
79
+ image_path,
80
+ "--repo", REPO,
81
+ "--clobber",
82
+ ],
83
+ check=True,
84
+ )
85
+
86
+ # Release asset URL format
87
+ return f"https://github.com/{REPO}/releases/download/{RELEASE_TAG}/{filename}"
88
+
89
+
90
+ def post_issue_comment(image_url: str, number: int, timestamp: str, model_used: str):
91
+ """Post a comment on the issue with the cat image."""
92
+ body = (
93
+ f"## Cat #{number}\n"
94
+ f"**Time:** {timestamp}\n"
95
+ f"**Model:** `{model_used}`\n\n"
96
+ f"![cat-{number}]({image_url})"
97
+ )
98
+ subprocess.run(
99
+ ["gh", "issue", "comment", ISSUE_NUMBER, "--repo", REPO, "--body", body],
100
+ check=True,
101
+ )
102
+
103
+
104
+ def update_catlist_and_push(entry: dict) -> int:
105
+ """Update catlist.json, commit and push (only JSON, no images)."""
106
+ catlist_path = Path("catlist.json")
107
+ cats = json.loads(catlist_path.read_text()) if catlist_path.exists() else []
108
+ cats.append(entry)
109
+ catlist_path.write_text(json.dumps(cats, indent=2, ensure_ascii=False) + "\n")
110
+
111
+ subprocess.run(["git", "config", "user.name", "github-actions[bot]"], check=True)
112
+ subprocess.run(
113
+ ["git", "config", "user.email", "github-actions[bot]@users.noreply.github.com"],
114
+ check=True,
115
+ )
116
+ subprocess.run(["git", "add", "catlist.json"], check=True)
117
+
118
+ status = entry["status"]
119
+ number = entry.get("number")
120
+ timestamp = entry["timestamp"]
121
+ msg = f"Add cat #{number} - {timestamp}" if status == "success" else f"Failed cat - {timestamp}"
122
+ subprocess.run(["git", "commit", "-m", msg], check=True)
123
+
124
+ # Retry push with rebase in case of concurrent pushes
125
+ for attempt in range(3):
126
+ result = subprocess.run(["git", "push"], capture_output=True, text=True)
127
+ if result.returncode == 0:
128
+ break
129
+ print(f"Push failed (attempt {attempt + 1}), rebasing...")
130
+ subprocess.run(["git", "pull", "--rebase"], check=True)
131
+ else:
132
+ raise RuntimeError("Failed to push after 3 attempts")
133
+ return number or 0
134
+
135
+
136
+ def main():
137
+ now = datetime.now(timezone.utc)
138
+ timestamp = now.strftime("%Y-%m-%d %H:%M UTC")
139
+
140
+ print(f"Generating cat for {timestamp}...")
141
+ result = asyncio.run(generate_cat_image("/tmp", timestamp))
142
+
143
+ # Read current count for numbering
144
+ catlist_path = Path("catlist.json")
145
+ cats = json.loads(catlist_path.read_text()) if catlist_path.exists() else []
146
+ next_number = len(cats) + 1
147
+
148
+ if result["status"] == "failed":
149
+ print(f"Generation failed: {result['error']}", file=sys.stderr)
150
+ entry = {
151
+ "number": None,
152
+ "timestamp": timestamp,
153
+ "url": None,
154
+ "model": "all failed",
155
+ "status": "failed",
156
+ "error": result["error"],
157
+ }
158
+ update_catlist_and_push(entry)
159
+ sys.exit(1)
160
+
161
+ image_path = result["file_path"]
162
+ model_used = result["model_used"]
163
+ print(f"Model used: {model_used}")
164
+
165
+ print("Ensuring release exists...")
166
+ ensure_release_exists()
167
+
168
+ print("Uploading image as release asset...")
169
+ image_url = upload_image_as_release_asset(image_path)
170
+ print(f"Image URL: {image_url}")
171
+
172
+ entry = {
173
+ "number": next_number,
174
+ "timestamp": timestamp,
175
+ "url": image_url,
176
+ "model": model_used,
177
+ "status": "success",
178
+ }
179
+ print("Updating catlist.json...")
180
+ update_catlist_and_push(entry)
181
+
182
+ print("Posting issue comment...")
183
+ post_issue_comment(image_url, next_number, timestamp, model_used)
184
+
185
+ print(f"Done! Cat #{next_number}")
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
@@ -0,0 +1,3 @@
1
+ """catime - AI-generated hourly cat images."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,127 @@
1
+ """CLI entry point for catime - view AI-generated hourly cats."""
2
+
3
+ import argparse
4
+ import json
5
+ import re
6
+ import sys
7
+ from datetime import datetime, timezone, timedelta
8
+ from pathlib import Path
9
+
10
+ import httpx
11
+
12
+ CATLIST_URL = "https://raw.githubusercontent.com/{repo}/main/catlist.json"
13
+ DEFAULT_REPO = "yazelin/catime"
14
+
15
+
16
+ def fetch_catlist(repo: str) -> list[dict]:
17
+ url = CATLIST_URL.format(repo=repo)
18
+ resp = httpx.get(url, follow_redirects=True)
19
+ resp.raise_for_status()
20
+ return resp.json()
21
+
22
+
23
+ def load_local_catlist() -> list[dict]:
24
+ p = Path(__file__).resolve().parent.parent.parent / "catlist.json"
25
+ if p.exists():
26
+ return json.loads(p.read_text())
27
+ return []
28
+
29
+
30
+ def print_cat(cat: dict, index: int | None = None):
31
+ """Print a single cat entry."""
32
+ num = cat.get("number") or index
33
+ status = cat.get("status", "success")
34
+ if status == "failed":
35
+ print(f"Cat #{num or '?':>4} [FAILED] {cat['timestamp']} error: {cat.get('error', '?')}")
36
+ else:
37
+ print(f"Cat #{num:>4} {cat['timestamp']} model: {cat.get('model', '?')}")
38
+ print(f" URL: {cat['url']}")
39
+
40
+
41
+ def filter_by_query(cats: list[dict], query: str) -> list[dict]:
42
+ """Filter cats by time query: date, date+hour, today, yesterday."""
43
+ now = datetime.now(timezone.utc)
44
+
45
+ if query == "today":
46
+ target_date = now.strftime("%Y-%m-%d")
47
+ return [c for c in cats if c["timestamp"].startswith(target_date)]
48
+
49
+ if query == "yesterday":
50
+ target_date = (now - timedelta(days=1)).strftime("%Y-%m-%d")
51
+ return [c for c in cats if c["timestamp"].startswith(target_date)]
52
+
53
+ # date+hour: 2026-01-30T05 or 2026-01-30 05
54
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})[T ](\d{1,2})$", query)
55
+ if m:
56
+ date_str, hour_str = m.group(1), m.group(2).zfill(2)
57
+ prefix = f"{date_str} {hour_str}:"
58
+ return [c for c in cats if c["timestamp"].startswith(prefix)]
59
+
60
+ # date only: 2026-01-30
61
+ if re.match(r"^\d{4}-\d{2}-\d{2}$", query):
62
+ return [c for c in cats if c["timestamp"].startswith(query)]
63
+
64
+ return []
65
+
66
+
67
+ def main():
68
+ parser = argparse.ArgumentParser(
69
+ prog="catime",
70
+ description="View AI-generated hourly cat images",
71
+ )
72
+ parser.add_argument(
73
+ "query", nargs="?",
74
+ help="Cat number (e.g. 42), date (2026-01-30), date+hour (2026-01-30T05), 'today', or 'yesterday'.",
75
+ )
76
+ parser.add_argument("--repo", default=DEFAULT_REPO, help="GitHub repo owner/name")
77
+ parser.add_argument("--local", action="store_true", help="Use local catlist.json")
78
+ parser.add_argument("--list", action="store_true", help="List all cats")
79
+ args = parser.parse_args()
80
+
81
+ try:
82
+ cats = load_local_catlist() if args.local else fetch_catlist(args.repo)
83
+ except Exception as e:
84
+ print(f"Error loading cat list: {e}", file=sys.stderr)
85
+ sys.exit(1)
86
+
87
+ if not cats:
88
+ print("No cats yet! Check back in an hour.")
89
+ return
90
+
91
+ if args.list:
92
+ for i, cat in enumerate(cats, 1):
93
+ print_cat(cat, i)
94
+ return
95
+
96
+ if args.query is None:
97
+ print(f"Total cats: {len(cats)}")
98
+ print(f"Latest: #{len(cats):04d} {cats[-1]['timestamp']}")
99
+ print()
100
+ print("Usage:")
101
+ print(" catime 42 View cat #42")
102
+ print(" catime today List today's cats")
103
+ print(" catime yesterday List yesterday's cats")
104
+ print(" catime 2026-01-30 List all cats from a date")
105
+ print(" catime 2026-01-30T05 View the cat from a specific hour")
106
+ print(" catime --list List all cats")
107
+ return
108
+
109
+ # Try as number first
110
+ if args.query.isdigit():
111
+ idx = int(args.query) - 1
112
+ if idx < 0 or idx >= len(cats):
113
+ print(f"Cat #{args.query} not found. Available: 1-{len(cats)}", file=sys.stderr)
114
+ sys.exit(1)
115
+ print_cat(cats[idx], int(args.query))
116
+ return
117
+
118
+ # Try as time query
119
+ matched = filter_by_query(cats, args.query)
120
+ if not matched:
121
+ print(f"No cats found for '{args.query}'.", file=sys.stderr)
122
+ sys.exit(1)
123
+
124
+ print(f"Found {len(matched)} cat(s) for '{args.query}':\n")
125
+ for cat in matched:
126
+ print_cat(cat)
127
+ print()