klingai-usage-analytics
Build usage analytics and reporting for Kling AI video generation. Use when tracking patterns, analyzing costs, or building dashboards. Trigger with phrases like 'klingai analytics', 'kling ai usage report', 'klingai metrics', 'video generation stats'.
What this skill does
# Kling AI Usage Analytics
## Overview
Track video generation usage with structured logging, aggregate metrics, daily reports, and cost analysis. Built on JSONL event logs that can feed into any analytics platform.
## Event Logger
```python
import json
import time
from datetime import datetime
from pathlib import Path
class KlingEventLogger:
"""Append-only JSONL event log for Kling AI operations."""
def __init__(self, log_dir: str = "logs"):
self.log_dir = Path(log_dir)
self.log_dir.mkdir(exist_ok=True)
def _write(self, event: dict):
date = datetime.utcnow().strftime("%Y-%m-%d")
filepath = self.log_dir / f"kling-{date}.jsonl"
event["timestamp"] = datetime.utcnow().isoformat()
with open(filepath, "a") as f:
f.write(json.dumps(event) + "\n")
def log_submission(self, task_id, prompt, model, duration, mode):
self._write({
"event": "task_submitted",
"task_id": task_id,
"model": model,
"duration": int(duration),
"mode": mode,
"prompt_len": len(prompt),
})
def log_completion(self, task_id, status, elapsed_sec, credits_used):
self._write({
"event": "task_completed",
"task_id": task_id,
"status": status,
"elapsed_sec": elapsed_sec,
"credits_used": credits_used,
})
def log_error(self, task_id, error_type, message):
self._write({
"event": "task_error",
"task_id": task_id,
"error_type": error_type,
"message": message[:200],
})
```
## Analytics Aggregator
```python
from collections import defaultdict
class UsageAnalytics:
"""Aggregate metrics from JSONL event logs."""
def __init__(self, log_dir: str = "logs"):
self.log_dir = Path(log_dir)
def _read_events(self, date: str = None):
pattern = f"kling-{date}.jsonl" if date else "kling-*.jsonl"
events = []
for filepath in sorted(self.log_dir.glob(pattern)):
with open(filepath) as f:
for line in f:
events.append(json.loads(line))
return events
def daily_summary(self, date: str = None) -> dict:
date = date or datetime.utcnow().strftime("%Y-%m-%d")
events = self._read_events(date)
submitted = [e for e in events if e["event"] == "task_submitted"]
completed = [e for e in events if e["event"] == "task_completed"]
errors = [e for e in events if e["event"] == "task_error"]
succeeded = [e for e in completed if e["status"] == "succeed"]
failed = [e for e in completed if e["status"] == "failed"]
total_credits = sum(e.get("credits_used", 0) for e in completed)
avg_elapsed = (sum(e["elapsed_sec"] for e in succeeded) / len(succeeded)
if succeeded else 0)
by_model = defaultdict(int)
for e in submitted:
by_model[e["model"]] += 1
return {
"date": date,
"total_submitted": len(submitted),
"succeeded": len(succeeded),
"failed": len(failed),
"errors": len(errors),
"success_rate": f"{len(succeeded) / max(len(completed), 1) * 100:.1f}%",
"total_credits": total_credits,
"avg_generation_sec": round(avg_elapsed),
"by_model": dict(by_model),
}
def print_report(self, date: str = None):
s = self.daily_summary(date)
print(f"\n=== Kling AI Usage Report: {s['date']} ===")
print(f"Submitted: {s['total_submitted']}")
print(f"Succeeded: {s['succeeded']}")
print(f"Failed: {s['failed']}")
print(f"Success rate: {s['success_rate']}")
print(f"Credits used: {s['total_credits']}")
print(f"Avg time: {s['avg_generation_sec']}s")
print(f"By model:")
for model, count in s["by_model"].items():
print(f" {model}: {count}")
```
## Cost Analysis
```python
def cost_analysis(analytics: UsageAnalytics, days: int = 7):
"""Analyze cost trends over recent days."""
from datetime import timedelta
daily_costs = []
for i in range(days):
date = (datetime.utcnow() - timedelta(days=i)).strftime("%Y-%m-%d")
summary = analytics.daily_summary(date)
daily_costs.append({
"date": date,
"credits": summary["total_credits"],
"videos": summary["total_submitted"],
"estimated_usd": summary["total_credits"] * 0.14,
})
total_credits = sum(d["credits"] for d in daily_costs)
total_videos = sum(d["videos"] for d in daily_costs)
total_cost = sum(d["estimated_usd"] for d in daily_costs)
print(f"\n=== {days}-Day Cost Summary ===")
print(f"Total credits: {total_credits}")
print(f"Total videos: {total_videos}")
print(f"Est. cost: ${total_cost:.2f}")
print(f"Avg/day: ${total_cost / days:.2f}")
for d in daily_costs:
print(f" {d['date']}: {d['credits']} credits, {d['videos']} videos, ${d['estimated_usd']:.2f}")
```
## Export to CSV
```python
import csv
def export_usage_csv(analytics: UsageAnalytics, output: str = "kling_usage.csv"):
events = analytics._read_events()
with open(output, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["timestamp", "event", "task_id",
"model", "status", "credits_used",
"elapsed_sec"])
writer.writeheader()
for e in events:
writer.writerow({k: e.get(k, "") for k in writer.fieldnames})
print(f"Exported {len(events)} events to {output}")
```
## Resources
- [Developer Portal](https://app.klingai.com/global/dev)
- [Pricing Reference](https://app.klingai.com/global/dev/document-api/productBilling/prePaidResourcePackage)
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.