Files
lightcore-cli/lightcore_cli/media_commands.py
T

237 lines
15 KiB
Python
Raw Normal View History

import argparse
import json
from pathlib import Path
import re
from .api import format_response
from .media import folder_id, positive_int
from .media_schema import CASES, DESCRIPTIONS, enum_for, example_body, request_schema
from .transport import ClientError, compact, reject_constant
SOCIAL = "/content/social"
SCRIPT = "/content/script"
DOCUMENT = "/content/document"
PAGINATION = "pageNo pageSize"
SCRIPT_DELETE = "requestId id expectedUpdatedAt"
# Each entry declares the existing backend path and the input shown in --help.
GROUPS = {
"auth": ("个人资料与会话", "/auth", [
("info", "info", "查看当前管理员身份", ""),
("update-profile", "updateProfile", "修改当前管理员显示名", "displayName*"),
("change-password", "changePassword", "修改当前管理员密码", "oldPassword newPassword", "private"),
]),
"admin-accounts": ("Media 后台管理员", "/account", [
("list", "getList", "查询后台管理员", f"{PAGINATION} keyword role status"),
("create", "create", "创建后台管理员", "username password displayName", "private"),
("update-status", "updateStatus", "设置管理员状态为 enabled 或 disabled", "id* status*"),
("reset-password", "resetPassword", "重置管理员密码", "id password", "private"),
("delete", "delete", "删除后台管理员", "id*"),
]),
"accounts": ("社媒账号", SOCIAL, [
("list", "getAccountList", "查询社媒账号", f"{PAGINATION} keyword platform isValid"),
("get", "getAccountDetail", "查看社媒账号详情", "accountKey*"),
("save", "saveAccount", "新建或更新社媒账号",
"requestId accountKey platform brandName accountName accountHandle agentGuideMarkdown isValid validityNote expectedUpdatedAt", "json"),
("set-validity", "setAccountValidity", "设置社媒账号有效状态",
"accountKey requestId isValid validityNote expectedUpdatedAt", "json"),
]),
"contents": ("正式稿件", SOCIAL, [
("list", "getContentList", "查询正式稿件", f"{PAGINATION} keyword contentType"),
("get", "getContentDetail", "查看稿件正文、附件和发布记录", "contentId*"),
("save", "saveContent", "新建或更新正式稿件",
"requestId contentId contentType title body contentFormat coverFileIds mediaFileIds "
"creationNotes researchFacts researchSources imageDetails expectedUpdatedAt", "json"),
("save-image-detail", "saveImageDetail", "保存一张稿件图片的创作资料",
"contentId requestId expectedUpdatedAt fileId text prompt referenceFileIds notes", "json"),
("download", "downloadAsset", "下载与稿件关联的文件", "contentId* fileId*", "download"),
]),
"references": ("对标素材", SOCIAL, [
("list", "getReferenceList", "查询作品与评估。Agent 选题使用 --for-topic-selection true",
f"{PAGINATION} keyword platform contentType creatorId publishedFrom publishedTo transcriptStatus assessment forTopicSelection sort"),
("get", "getReferenceDetail", "读取作品详情和转写全文", "referenceId*"),
("save", "saveReference", "按平台作品 ID 写入采集数据",
"requestId platform platformContentId sourceUrl videoFileUrl audioFileUrl contentType title description publishedAt durationSeconds "
"coverFileId viewCount likeCount favoriteCount commentCount shareCount collectedAt creator", "json"),
("save-transcript", "saveReferenceTranscript", "保存作品转写",
"requestId referenceId expectedUpdatedAt transcriptStatus transcriptText transcriptSegments "
"transcriptLanguage transcriptModel transcribedAt", "json"),
("save-assessment", "saveReferenceAssessment", "保存人工选题评估、参考点和备注",
"requestId referenceId expectedUpdatedAt assessment referencePoints topicNotes", "json"),
("delete", "deleteReference", "删除作品记录及其评论", "referenceId requestId expectedUpdatedAt", "json"),
("download", "downloadReferenceAsset", "下载与作品关联的封面", "referenceId* fileId*", "download"),
]),
"publications": ("人工发布记录", SOCIAL, [
("list", "getPublicationList", "查询已登记的发布记录", f"{PAGINATION} contentId accountKey"),
("mark", "markPublication", "登记已经人工完成的平台发布",
"requestId contentId accountKey publishedAt publicUrl", "json"),
]),
"documents": ("通用文档和产品资料", DOCUMENT, [
("list", "getDocumentList", "查询文档,省略文件夹编号时搜索全库", f"{PAGINATION} keyword excludeKeyword searchScope matchMode projectId folderId"),
("get", "getDocumentDetail", "读取文档正文和附件", "documentId*"),
("save", "saveDocument", "新建、编辑或移动文档以及更新附件关联",
"requestId documentId expectedUpdatedAt title bodyMarkdown fileIds folderId", "json"),
("folders", "getFolderTree", "列出文档文件夹及其父目录", ""),
("save-folder", "saveFolder", "新建、重命名或移动文档文件夹", "requestId folderId parentId expectedUpdatedAt name", "json"),
("delete", "deleteDocument", "删除文档记录", "documentId requestId expectedUpdatedAt", "json"),
]),
"projects": ("短剧项目", SCRIPT, [
("list", "getProjectList", "查询短剧项目", f"{PAGINATION} keyword"),
("get", "getProjectDetail", "查看项目详情与文档关联", "projectId*"),
("context", "getCreationContext", "读取项目必读正文及参考文档清单", "projectId*"),
("save", "saveProject", "新建或更新短剧项目", "requestId projectId expectedUpdatedAt name description documents", "json"),
("delete", "deleteProject", "删除项目", SCRIPT_DELETE, "json"),
]),
"episodes": ("短剧分集", SCRIPT, [
("list", "getEpisodeList", "查询项目的分集", f"{PAGINATION} projectId* keyword"),
("get", "getEpisodeDetail", "查看分集详情", "episodeId*"),
("save", "saveEpisode", "新建或更新分集", "requestId episodeId expectedUpdatedAt projectId name sortOrder", "json"),
("delete", "deleteEpisode", "删除分集", SCRIPT_DELETE, "json"),
]),
"resources": ("角色、场景和道具", SCRIPT, [
("list", "getResourceList", "按项目查询资源", f"{PAGINATION} projectId* keyword type"),
("get", "getResourceDetail", "查看资源详情", "resourceId*"),
("save", "saveResource", "新建或更新资源", "requestId resourceId expectedUpdatedAt projectId name type prompt imageFileIds", "json"),
("delete", "deleteResource", "删除资源", SCRIPT_DELETE, "json"),
("download", "downloadResourceImage", "下载与资源关联的图片", "resourceId* fileId*", "download"),
]),
"videos": ("短剧视频与参考图", SCRIPT, [
("list", "getVideoList", "查询分集的视频", f"{PAGINATION} episodeId* keyword"),
("get", "getVideoDetail", "查看视频正文和参考图", "videoId*"),
("save", "saveVideo", "新建或更新视频",
"requestId videoId expectedUpdatedAt projectId episodeId name sortOrder mode durationSeconds "
"characterResourceIds sceneResourceIds propResourceIds style context body dialogue audioRequirements "
"visualRequirements staffNotes referenceImages", "json"),
("delete", "deleteVideo", "删除视频", SCRIPT_DELETE, "json"),
("prompt", "getVideoPrompt", "读取视频生成提示词和输入图", "videoId*"),
("image-prompt", "getReferenceImagePrompt", "读取指定参考图的生成提示词", "videoId* key*"),
("download", "downloadReferenceImage", "下载与视频关联的图片", "videoId* fileId*", "download"),
]),
"memos": ("Media 备忘录", "/memo", [
("check", "checkMemos", "检查已到提醒时间及已逾期的备忘", PAGINATION),
("list", "getMemoList", "按状态或标题查找备忘", f"{PAGINATION} status keyword excludeMemoId"),
("get", "getMemo", "查看备忘详情和备注", "memoId*"),
("save", "saveMemo", "新建、编辑或完成备忘", "requestId memoId expectedUpdatedAt title notes status priority dueAt remindAt remindDaysBefore relatedMemoIds fileIds", "json"),
]),
"storage": ("Media 存储绑定", "/storage", [
("get", "getConfig", "查看 Media 存储配置", ""),
("save", "saveConfig", "保存 Media 存储配置", "bucket clientSecret", "private"),
]),
}
def parse_bool(value):
values = {"true": True, "false": False}
if value not in values:
raise ValueError("需要 true 或 false")
return values[value]
def page_size(value):
parsed = positive_int(value)
if parsed > 100:
raise ValueError("每页最多 100 条")
return parsed
def add_field(parser, endpoint, spec):
field = spec.removesuffix("*")
flag = "--" + re.sub(r"[A-Z]", lambda hit: "-" + hit[0].lower(), field)
description = DESCRIPTIONS.get(field, f"JSON 字段 {field}")
values = enum_for(endpoint, field)
if values:
description += ",可选 " + " / ".join(values)
options = {"dest": field, "required": spec.endswith("*"), "help": description}
if field in ("pageNo", "pageSize"):
options["type"] = positive_int if field == "pageNo" else page_size
options["default"] = 1 if field == "pageNo" else 20
options["help"] += f",默认 {options['default']}"
elif field in ("isValid", "forTopicSelection"):
options.update(type=parse_bool, metavar="true|false")
elif field == "folderId":
options["type"] = folder_id
elif field == "id" or field.endswith("Id"):
options["type"] = positive_int
parser.add_argument(flag, **options)
return field
class ShowRequest(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
endpoint, fields = namespace.request_spec
schema = request_schema(endpoint, fields)
result = schema if option_string == "--schema" else example_body(endpoint, schema, values or "create")
print(json.dumps(result, ensure_ascii=False, indent=2))
parser.exit()
def read_body(args):
if not (args.body_file or args.body is not None):
return {field: getattr(args, field) for field in args.fields if getattr(args, field) is not None}
text = args.body_file.read_text(encoding="utf-8-sig") if args.body_file else args.body
try:
data = json.loads(text, parse_constant=reject_constant)
except (ValueError, UnicodeError):
raise ClientError("请求正文必须是有效 JSON 对象。") from None
if not isinstance(data, dict):
raise ClientError("请求正文必须是 JSON 对象。")
return data
def call(client, args):
body = read_body(args)
client.remember_secrets(body)
response = client.exchange(args.endpoint, compact(body).encode("utf-8"), output=args.output)
if args.output is not None and client.success(response) and not response.get("downloaded"):
raise ClientError("Media 响应未包含可下载的文件。", traceId=response.get("traceId"))
return format_response(client, response, Path.cwd() / ".work" / "lightcore" / "media", args.max_chars)
def add_operation(actions, prefix, name, endpoint, summary, fields, mode="fields"):
command = actions.add_parser(name, help=summary, description=summary, allow_abbrev=False)
command.set_defaults(handler=call, endpoint=prefix + "/" + endpoint, body=None, body_file=None, output=None)
if mode in ("json", "private"):
command.set_defaults(request_spec=(endpoint, fields.split()))
input_group = command.add_mutually_exclusive_group(required=True)
input_group.add_argument("--schema", action=ShowRequest, nargs=0,
help="离线查看 JSON 字段类型、必填条件和嵌套结构")
if endpoint in CASES:
input_group.add_argument("--example", action=ShowRequest, nargs="?", const="create",
choices=("create", "update"), help="离线生成示例 JSON,默认 create,更新用 update")
else:
input_group.add_argument("--example", action=ShowRequest, nargs=0, help="离线生成示例 JSON")
if mode == "private":
input_group.add_argument("--body-file", type=Path, help="本机私有 JSON 输入文件")
else:
input_group.add_argument("--body", help="JSON 对象")
input_group.add_argument("--body-file", type=Path, help="UTF-8 JSON 文件")
else:
command.set_defaults(fields=[add_field(command, endpoint, field) for field in fields.split()])
if mode == "download":
command.add_argument("--output", type=Path, required=True, help="保存路径,拒绝覆盖")
def add_commands(commands, file_actions):
for group, (description, prefix, operations) in GROUPS.items():
group_parser = commands.add_parser(group, help=description, description=description)
actions = group_parser.add_subparsers(required=True)
if group == "auth":
for name, handler, help_text in [
("refresh", lambda client, _: client.refresh(), "刷新本机 Media 会话"),
("logout", lambda client, _: client.logout(), "在服务端退出并清理本机 Token"),
]:
actions.add_parser(name, help=help_text, description=help_text).set_defaults(
handler=handler, endpoint=prefix + "/" + name,
)
for operation in operations:
add_operation(actions, prefix, *operation)
library = "/content/file"
add_operation(file_actions, library, "search", "searchFiles", "按文件名查找素材,省略文件夹编号时搜索全库", f"{PAGINATION} keyword type folderId")
add_operation(file_actions, library, "folders", "getFolderTree", "列出文件夹及其父目录", "")
add_operation(file_actions, library, "info", "getFile", "按文件编号查看描述和文本内容", "fileId*")
add_operation(file_actions, library, "preview", "previewFile", "获取临时预览地址", "fileId*")
add_operation(file_actions, library, "download", "downloadFile", "按文件编号下载原件", "fileId*", "download")
add_operation(file_actions, library, "update", "saveFile", "编辑文件名、描述或文本内容", "requestId fileId expectedUpdatedAt fileName description textContent", "json")
add_operation(file_actions, library, "save-folder", "saveFolder", "新建、重命名或移动文件夹", "requestId folderId parentId expectedUpdatedAt name", "json")
add_operation(file_actions, library, "move", "moveFiles", "移动一个或多个文件", "requestId folderId files", "json")