编辑Caption JSON字符串 支持批处理:输入列表,输出列表
(self, json_string, new_caption="", add_prefix="",
add_suffix="", replace_from="", replace_to="", new_lang="en")
| 64 | OUTPUT_IS_LIST = (True, True, True) |
| 65 | |
| 66 | def edit_caption_json(self, json_string, new_caption="", add_prefix="", |
| 67 | add_suffix="", replace_from="", replace_to="", new_lang="en"): |
| 68 | """ |
| 69 | 编辑Caption JSON字符串 |
| 70 | 支持批处理:输入列表,输出列表 |
| 71 | """ |
| 72 | # 确保json_string是列表 |
| 73 | if not isinstance(json_string, list): |
| 74 | json_string = [json_string] |
| 75 | |
| 76 | json_output_list = [] |
| 77 | caption_list = [] |
| 78 | lang_list = [] |
| 79 | |
| 80 | # 解析替换词列表(只解析一次,应用到所有项) |
| 81 | from_words = [] |
| 82 | to_words = [] |
| 83 | if replace_from and (isinstance(replace_from, str) and replace_from.strip()): |
| 84 | from_words = [line.strip() for line in replace_from.strip().split('\n') if line.strip()] |
| 85 | to_words = [line.strip() for line in replace_to.strip().split('\n') if line.strip()] if replace_to else [] |
| 86 | # 确保替换列表长度一致 |
| 87 | while len(to_words) < len(from_words): |
| 88 | to_words.append("") # 如果替换词不够,用空字符串替换(即删除) |
| 89 | |
| 90 | # 处理每个JSON字符串 |
| 91 | for idx, json_str in enumerate(json_string): |
| 92 | try: |
| 93 | # 类型转换 |
| 94 | if isinstance(json_str, list): |
| 95 | json_str = str(json_str[0]) if json_str else "" |
| 96 | if not isinstance(json_str, str): |
| 97 | json_str = str(json_str) |
| 98 | |
| 99 | # 解析输入的JSON字符串 |
| 100 | try: |
| 101 | data = json.loads(json_str) |
| 102 | caption = data.get("caption", "") |
| 103 | lang = data.get("lang", "en") |
| 104 | except json.JSONDecodeError as e: |
| 105 | print(f"PD CaptionJSONEditor: 第{idx+1}项JSON解析失败: {e}") |
| 106 | # 尝试直接作为普通文本处理 |
| 107 | caption = json_str.strip() |
| 108 | lang = "en" |
| 109 | |
| 110 | # 处理caption内容 |
| 111 | # 1. 如果提供了新的caption,则完全替换 |
| 112 | if new_caption: |
| 113 | if isinstance(new_caption, list): |
| 114 | current_new_caption = new_caption[idx] if idx < len(new_caption) else "" |
| 115 | else: |
| 116 | current_new_caption = new_caption |
| 117 | |
| 118 | if isinstance(current_new_caption, str) and current_new_caption.strip(): |
| 119 | caption = current_new_caption.strip() |
| 120 | |
| 121 | # 2. 执行词语替换 |
| 122 | for from_word, to_word in zip(from_words, to_words): |
| 123 | if from_word: |
nothing calls this directly
no outgoing calls
no test coverage detected