ytstudio-cli 0.1.0__py3-none-any.whl

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,570 @@
1
+ import csv
2
+ import io
3
+ import json
4
+ from dataclasses import asdict, dataclass
5
+ from datetime import datetime, timedelta
6
+
7
+ import typer
8
+
9
+ from ytstudio.api import api
10
+ from ytstudio.registry import (
11
+ DIMENSION_GROUPS,
12
+ DIMENSIONS,
13
+ METRIC_GROUPS,
14
+ METRICS,
15
+ DimensionName,
16
+ MetricName,
17
+ find_closest_dimension,
18
+ validate_dimensions,
19
+ validate_metrics,
20
+ )
21
+ from ytstudio.services import get_analytics_service, get_data_service
22
+ from ytstudio.ui import console, create_kv_table, create_table, dim, format_number, set_raw_output
23
+
24
+ app = typer.Typer(help="Analytics commands")
25
+
26
+
27
+ @dataclass
28
+ class VideoAnalytics:
29
+ views: int
30
+ watch_time_minutes: int
31
+ avg_view_duration_secs: int
32
+ avg_view_percentage: float
33
+ likes: int
34
+ comments: int
35
+
36
+
37
+ def get_channel_id(service) -> str:
38
+ response = api(service.channels().list(part="id", mine=True))
39
+ if not response.get("items"):
40
+ console.print("[red]No channel found[/red]")
41
+ raise typer.Exit(1)
42
+ return response["items"][0]["id"]
43
+
44
+
45
+ def fetch_query(
46
+ data_service,
47
+ analytics_service,
48
+ *,
49
+ metric_names: list[str],
50
+ dimension_names: list[str],
51
+ start_date: str,
52
+ end_date: str,
53
+ days: int,
54
+ filters_str: str | None = None,
55
+ sort: str | None = None,
56
+ max_results: int | None = None,
57
+ currency: str | None = None,
58
+ ) -> dict:
59
+ channel_id = get_channel_id(data_service)
60
+
61
+ query_params = {
62
+ "ids": f"channel=={channel_id}",
63
+ "startDate": start_date,
64
+ "endDate": end_date,
65
+ "metrics": ",".join(metric_names),
66
+ }
67
+
68
+ if dimension_names:
69
+ query_params["dimensions"] = ",".join(dimension_names)
70
+ if filters_str:
71
+ query_params["filters"] = filters_str
72
+ if sort:
73
+ query_params["sort"] = sort
74
+ if max_results:
75
+ query_params["maxResults"] = max_results
76
+ if currency:
77
+ query_params["currency"] = currency
78
+
79
+ return api(analytics_service.reports().query(**query_params))
80
+
81
+
82
+ @app.command()
83
+ def overview(
84
+ days: int = typer.Option(28, "--days", "-d", help="Number of days to analyze"),
85
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
86
+ ):
87
+ """Get channel overview analytics"""
88
+ metric_names = [
89
+ MetricName.VIEWS,
90
+ MetricName.ESTIMATED_MINUTES_WATCHED,
91
+ MetricName.AVERAGE_VIEW_DURATION,
92
+ MetricName.SUBSCRIBERS_GAINED,
93
+ MetricName.SUBSCRIBERS_LOST,
94
+ MetricName.LIKES,
95
+ MetricName.COMMENTS,
96
+ ]
97
+
98
+ end_date = datetime.now().strftime("%Y-%m-%d")
99
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
100
+
101
+ data_service = get_data_service()
102
+ analytics_service = get_analytics_service()
103
+ response = fetch_query(
104
+ data_service,
105
+ analytics_service,
106
+ metric_names=metric_names,
107
+ dimension_names=[],
108
+ start_date=start_date,
109
+ end_date=end_date,
110
+ days=days,
111
+ )
112
+
113
+ headers = [h["name"] for h in response.get("columnHeaders", [])]
114
+ rows = response.get("rows", [])
115
+
116
+ if not rows:
117
+ console.print("[yellow]No analytics data available[/yellow]")
118
+ return
119
+
120
+ metrics = dict(zip(headers, rows[0], strict=False))
121
+
122
+ if output == "json":
123
+ print(json.dumps({"analytics": metrics, "days": days}, indent=2))
124
+ return
125
+
126
+ views = int(metrics.get("views", 0))
127
+ watch_hours = int(metrics.get("estimatedMinutesWatched", 0)) // 60
128
+ avg_secs = int(metrics.get("averageViewDuration", 0))
129
+ subs_gained = int(metrics.get("subscribersGained", 0))
130
+ subs_lost = int(metrics.get("subscribersLost", 0))
131
+ likes = int(metrics.get("likes", 0))
132
+ comments = int(metrics.get("comments", 0))
133
+
134
+ console.print(f"\n[bold]Channel Analytics[/bold] {dim(f'(last {days} days)')}\n")
135
+ table = create_kv_table()
136
+
137
+ table.add_row(dim("views"), format_number(views))
138
+ table.add_row(dim("watch time"), f"{watch_hours} hours")
139
+ table.add_row(dim("avg duration"), f"{avg_secs // 60}:{avg_secs % 60:02d}")
140
+ table.add_row(dim("subscribers gained"), f"[green]+{subs_gained}[/green]")
141
+ table.add_row(dim("subscribers lost"), f"[red]-{subs_lost}[/red]")
142
+ table.add_row(dim("likes"), format_number(likes))
143
+ table.add_row(dim("comments"), format_number(comments))
144
+
145
+ console.print(table)
146
+
147
+
148
+ def fetch_video_analytics(
149
+ data_service, analytics_service, video_id: str, days: int
150
+ ) -> VideoAnalytics | None:
151
+ channel_id = get_channel_id(data_service)
152
+ end_date = datetime.now().strftime("%Y-%m-%d")
153
+ start_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
154
+
155
+ response = api(
156
+ analytics_service.reports().query(
157
+ ids=f"channel=={channel_id}",
158
+ startDate=start_date,
159
+ endDate=end_date,
160
+ metrics=",".join(
161
+ (
162
+ MetricName.VIEWS,
163
+ MetricName.ESTIMATED_MINUTES_WATCHED,
164
+ MetricName.AVERAGE_VIEW_DURATION,
165
+ MetricName.AVERAGE_VIEW_PERCENTAGE,
166
+ MetricName.LIKES,
167
+ MetricName.COMMENTS,
168
+ )
169
+ ),
170
+ filters=f"video=={video_id}",
171
+ )
172
+ )
173
+
174
+ if not response.get("rows"):
175
+ return None
176
+
177
+ row = response["rows"][0]
178
+ metrics = {h["name"]: row[i] for i, h in enumerate(response["columnHeaders"])}
179
+
180
+ return VideoAnalytics(
181
+ views=int(metrics.get("views", 0)),
182
+ watch_time_minutes=int(metrics.get("estimatedMinutesWatched", 0)),
183
+ avg_view_duration_secs=int(metrics.get("averageViewDuration", 0)),
184
+ avg_view_percentage=float(metrics.get("averageViewPercentage", 0)),
185
+ likes=int(metrics.get("likes", 0)),
186
+ comments=int(metrics.get("comments", 0)),
187
+ )
188
+
189
+
190
+ @app.command()
191
+ def video(
192
+ video_id: str = typer.Argument(..., help="Video ID"),
193
+ days: int = typer.Option(28, "--days", "-d", help="Number of days to analyze"),
194
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
195
+ ):
196
+ """Get analytics for a specific video"""
197
+ data_service = get_data_service()
198
+ analytics_service = get_analytics_service()
199
+
200
+ video_response = api(data_service.videos().list(part="snippet,statistics", id=video_id))
201
+
202
+ if not video_response.get("items"):
203
+ console.print(f"[red]Video not found: {video_id}[/red]")
204
+ raise typer.Exit(1)
205
+
206
+ video_data = video_response["items"][0]
207
+ snippet = video_data["snippet"]
208
+ analytics = fetch_video_analytics(data_service, analytics_service, video_id, days)
209
+
210
+ if output == "json":
211
+ print(
212
+ json.dumps(
213
+ {"video": video_data, "analytics": asdict(analytics) if analytics else None},
214
+ indent=2,
215
+ )
216
+ )
217
+ return
218
+
219
+ console.print(f"\n[bold]{snippet['title']}[/bold]")
220
+ console.print(f"[cyan]https://youtu.be/{video_id}[/cyan]\n")
221
+
222
+ if analytics:
223
+ console.print(f"[bold]Analytics[/bold] {dim(f'(last {days} days)')}\n")
224
+ table = create_kv_table()
225
+
226
+ table.add_row(dim("views"), format_number(analytics.views))
227
+ table.add_row(dim("watch time"), f"{analytics.watch_time_minutes} min")
228
+ table.add_row(dim("avg duration"), f"{analytics.avg_view_duration_secs}s")
229
+ table.add_row(dim("avg % viewed"), f"{analytics.avg_view_percentage:.1f}%")
230
+ table.add_row(dim("likes"), format_number(analytics.likes))
231
+ table.add_row(dim("comments"), format_number(analytics.comments))
232
+
233
+ console.print(table)
234
+
235
+
236
+ # --- Raw query engine ---
237
+
238
+
239
+ def _parse_comma_list(value: str) -> list[str]:
240
+ """Split a comma-separated string, stripping whitespace."""
241
+ return [v.strip() for v in value.split(",") if v.strip()]
242
+
243
+
244
+ def _format_query_response(response: dict, output: str) -> None:
245
+ headers = [h["name"] for h in response.get("columnHeaders", [])]
246
+ rows = response.get("rows", [])
247
+
248
+ if output == "json":
249
+ records = [dict(zip(headers, row, strict=False)) for row in rows]
250
+ print(json.dumps(records, indent=2))
251
+ return
252
+
253
+ if output == "csv":
254
+ buf = io.StringIO()
255
+ writer = csv.writer(buf)
256
+ writer.writerow(headers)
257
+ writer.writerows(rows)
258
+ print(buf.getvalue(), end="")
259
+ return
260
+
261
+ # table output
262
+ if not rows:
263
+ console.print("[yellow]No data returned[/yellow]")
264
+ return
265
+
266
+ table = create_table()
267
+ for header in headers:
268
+ is_numeric = header in METRICS
269
+ table.add_column(
270
+ header,
271
+ justify="right" if is_numeric else "left",
272
+ style="yellow" if header in DIMENSIONS else None,
273
+ )
274
+
275
+ for row in rows:
276
+ table.add_row(*[_format_cell(headers[i], v) for i, v in enumerate(row)])
277
+
278
+ console.print(table)
279
+
280
+
281
+ def _format_cell(header: str, value) -> str:
282
+ if isinstance(value, int):
283
+ return format_number(value)
284
+ if isinstance(value, float):
285
+ if "rate" in header.lower() or "percentage" in header.lower() or "ctr" in header.lower():
286
+ return f"{value:.2f}%"
287
+ if "cpm" in header.lower():
288
+ return f"${value:.2f}"
289
+ if value == int(value):
290
+ return format_number(int(value))
291
+ return f"{value:.1f}"
292
+ return str(value)
293
+
294
+
295
+ @app.command()
296
+ def query(
297
+ metrics_str: str = typer.Option(
298
+ ..., "--metrics", "-m", help="Comma-separated metrics (e.g. views,likes,shares)"
299
+ ),
300
+ dimensions_str: str = typer.Option(
301
+ None, "--dimensions", "-d", help="Comma-separated dimensions (e.g. day,country)"
302
+ ),
303
+ filter_list: list[str] = typer.Option(
304
+ None,
305
+ "--filter",
306
+ "-f",
307
+ help="Filter in key==value format (repeatable, e.g. -f video==ID -f country==NL)",
308
+ ),
309
+ start: str = typer.Option(
310
+ None, "--start", "-s", help="Start date (YYYY-MM-DD). Defaults to --days ago"
311
+ ),
312
+ end: str = typer.Option(None, "--end", "-e", help="End date (YYYY-MM-DD). Defaults to today"),
313
+ days: int = typer.Option(28, "--days", help="Number of days (used if --start not set)"),
314
+ sort: str = typer.Option(None, "--sort", help="Sort field (prefix with - for descending)"),
315
+ limit: int = typer.Option(None, "--limit", "-n", help="Maximum number of rows"),
316
+ currency: str = typer.Option(None, "--currency", help="Currency code for revenue (e.g. EUR)"),
317
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json, csv"),
318
+ raw: bool = typer.Option(False, "--raw", help="Show raw numbers instead of human-readable"),
319
+ ):
320
+ """Run a custom analytics query with any metrics and dimensions.
321
+
322
+ Direct access to the YouTube Analytics API reports.query endpoint.
323
+ Supports all available metrics and dimensions.
324
+
325
+ Examples:
326
+
327
+ ytstudio analytics query -m views,likes --dimensions day --days 7
328
+
329
+ ytstudio analytics query -m views,shares -d country --sort -views -n 10
330
+
331
+ ytstudio analytics query -m views,estimatedMinutesWatched -d video \\
332
+ --sort -views -n 5 -o json
333
+
334
+ ytstudio analytics query -m videoThumbnailImpressions,videoThumbnailImpressionsClickRate \\
335
+ -d video --sort -videoThumbnailImpressions -n 10
336
+
337
+ ytstudio analytics query -m views -d insightTrafficSourceType \\
338
+ -f video==dMH0bHeiRNg --sort -views
339
+ """
340
+ set_raw_output(raw)
341
+
342
+ # Parse and validate
343
+ metric_names = _parse_comma_list(metrics_str)
344
+ if not metric_names:
345
+ console.print("[red]At least one metric is required[/red]")
346
+ raise typer.Exit(1)
347
+
348
+ errors = validate_metrics(metric_names)
349
+ if errors:
350
+ for err in errors:
351
+ console.print(f"[red]{err}[/red]")
352
+ console.print("\nRun [bold]ytstudio analytics metrics[/bold] to see available metrics.")
353
+ raise typer.Exit(1)
354
+
355
+ dimension_names = _parse_comma_list(dimensions_str) if dimensions_str else []
356
+ if dimension_names:
357
+ errors = validate_dimensions(dimension_names)
358
+ if errors:
359
+ for err in errors:
360
+ console.print(f"[red]{err}[/red]")
361
+ console.print(
362
+ "\nRun [bold]ytstudio analytics dimensions[/bold] to see available dimensions."
363
+ )
364
+ raise typer.Exit(1)
365
+
366
+ # Build filters string
367
+ filters_str = None
368
+ if filter_list:
369
+ for f in filter_list:
370
+ if "==" not in f:
371
+ console.print(f"[red]Invalid filter format: '{f}'. Use key==value[/red]")
372
+ raise typer.Exit(1)
373
+ filters_str = ";".join(filter_list)
374
+
375
+ # Build dates
376
+ end_date = end or datetime.now().strftime("%Y-%m-%d")
377
+ start_date = start or (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
378
+
379
+ # The video dimension requires sort + maxResults per YouTube API docs
380
+ if DimensionName.VIDEO in dimension_names and (not sort or not limit):
381
+ missing = [x for x, v in [("--sort", sort), ("--limit", limit)] if not v]
382
+ console.print(f"[red]The 'video' dimension requires {' and '.join(missing)}[/red]")
383
+ console.print(f"Example: -d video --sort -{metric_names[0]} -n 10")
384
+ raise typer.Exit(1)
385
+
386
+ # Execute query
387
+ data_service = get_data_service()
388
+ analytics_service = get_analytics_service()
389
+ response = fetch_query(
390
+ data_service,
391
+ analytics_service,
392
+ metric_names=metric_names,
393
+ dimension_names=dimension_names,
394
+ start_date=start_date,
395
+ end_date=end_date,
396
+ days=days,
397
+ filters_str=filters_str,
398
+ sort=sort,
399
+ max_results=limit,
400
+ currency=currency,
401
+ )
402
+
403
+ _format_query_response(response, output)
404
+
405
+
406
+ # --- Discovery commands ---
407
+
408
+
409
+ @app.command("metrics")
410
+ def list_metrics(
411
+ group: str = typer.Option(None, "--group", "-g", help="Filter by group"),
412
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
413
+ ):
414
+ """List available analytics metrics.
415
+
416
+ Examples:
417
+
418
+ ytstudio analytics metrics
419
+
420
+ ytstudio analytics metrics --group engagement
421
+ """
422
+ filtered = METRICS.values()
423
+ if group:
424
+ if group not in METRIC_GROUPS:
425
+ console.print(
426
+ f"[red]Unknown group '{group}'. Available: {', '.join(METRIC_GROUPS)}[/red]"
427
+ )
428
+ raise typer.Exit(1)
429
+ filtered = [m for m in filtered if m.group == group]
430
+
431
+ if output == "json":
432
+ print(
433
+ json.dumps(
434
+ [
435
+ {
436
+ "name": m.name,
437
+ "description": m.description,
438
+ "group": m.group,
439
+ "core": m.core,
440
+ "monetary": m.monetary,
441
+ }
442
+ for m in filtered
443
+ ],
444
+ indent=2,
445
+ )
446
+ )
447
+ return
448
+
449
+ title = "Available Metrics"
450
+ if group:
451
+ title += f" ({group})"
452
+ console.print(f"\n[bold]{title}[/bold]\n")
453
+
454
+ table = create_table()
455
+ table.add_column("Metric", style="bold")
456
+ table.add_column("Description")
457
+ table.add_column("Group", style="dim")
458
+ table.add_column("", justify="right") # tags
459
+
460
+ for m in filtered:
461
+ tags = []
462
+ if m.core:
463
+ tags.append("[cyan]core[/cyan]")
464
+ if m.monetary:
465
+ tags.append("[yellow]$[/yellow]")
466
+ table.add_row(m.name, m.description, m.group, " ".join(tags))
467
+
468
+ console.print(table)
469
+
470
+ if not group:
471
+ console.print(f"\n{dim(f'Groups: {", ".join(METRIC_GROUPS)}')}")
472
+ console.print(dim("Filter with --group <name>"))
473
+ console.print()
474
+
475
+
476
+ @app.command("dimensions")
477
+ def list_dimensions(
478
+ group: str = typer.Option(None, "--group", "-g", help="Filter by group"),
479
+ name: str = typer.Argument(None, help="Show details for a specific dimension"),
480
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
481
+ ):
482
+ """List available analytics dimensions.
483
+
484
+ Examples:
485
+
486
+ ytstudio analytics dimensions
487
+
488
+ ytstudio analytics dimensions --group geographic
489
+
490
+ ytstudio analytics dimensions country
491
+ """
492
+ if name:
493
+ if name not in DIMENSIONS:
494
+ console.print(f"[red]Unknown dimension '{name}'[/red]")
495
+ suggestion = find_closest_dimension(name)
496
+ if suggestion:
497
+ console.print(f"Did you mean [bold]{suggestion}[/bold]?")
498
+ raise typer.Exit(1)
499
+
500
+ d = DIMENSIONS[name]
501
+ if output == "json":
502
+ print(
503
+ json.dumps(
504
+ {
505
+ "name": d.name,
506
+ "description": d.description,
507
+ "group": d.group,
508
+ "filter_only": d.filter_only,
509
+ },
510
+ indent=2,
511
+ )
512
+ )
513
+ return
514
+
515
+ console.print(f"\n[bold]{d.name}[/bold]")
516
+ console.print(f" {d.description}")
517
+ console.print(f" group: {dim(d.group)}")
518
+ if d.filter_only:
519
+ console.print(" [yellow]filter only[/yellow] (cannot be used as a dimension)")
520
+ console.print()
521
+ return
522
+
523
+ # List dimensions
524
+ filtered = DIMENSIONS.values()
525
+ if group:
526
+ if group not in DIMENSION_GROUPS:
527
+ console.print(
528
+ f"[red]Unknown group '{group}'. Available: {', '.join(DIMENSION_GROUPS)}[/red]"
529
+ )
530
+ raise typer.Exit(1)
531
+ filtered = [d for d in filtered if d.group == group]
532
+
533
+ if output == "json":
534
+ print(
535
+ json.dumps(
536
+ [
537
+ {
538
+ "name": d.name,
539
+ "description": d.description,
540
+ "group": d.group,
541
+ "filter_only": d.filter_only,
542
+ }
543
+ for d in filtered
544
+ ],
545
+ indent=2,
546
+ )
547
+ )
548
+ return
549
+
550
+ title = "Available Dimensions"
551
+ if group:
552
+ title += f" ({group})"
553
+ console.print(f"\n[bold]{title}[/bold]\n")
554
+
555
+ table = create_table()
556
+ table.add_column("Dimension", style="bold")
557
+ table.add_column("Description")
558
+ table.add_column("Group", style="dim")
559
+ table.add_column("", justify="right")
560
+
561
+ for d in filtered:
562
+ tag = "[yellow]filter[/yellow]" if d.filter_only else ""
563
+ table.add_row(d.name, d.description, d.group, tag)
564
+
565
+ console.print(table)
566
+
567
+ if not group:
568
+ console.print(f"\n{dim(f'Groups: {", ".join(DIMENSION_GROUPS)}')}")
569
+ console.print(dim("Filter with --group <name>"))
570
+ console.print()