-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathlingdonggooglejuben.py
More file actions
2137 lines (1818 loc) · 98.3 KB
/
lingdonggooglejuben.py
File metadata and controls
2137 lines (1818 loc) · 98.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
灵动智能体 - 谷歌剧本节点模块
支持上传谷歌剧本txt文件,并分行显示
"""
import os
import sys
import traceback
import csv
import io
from PySide6.QtWidgets import (
QGraphicsItem, QGraphicsProxyWidget, QTableWidget, QTableWidgetItem,
QFileDialog, QHeaderView, QWidget, QVBoxLayout, QLabel, QAbstractItemView,
QMenu, QApplication, QStyledItemDelegate
)
from PySide6.QtCore import Qt, QRectF, QMimeData, QUrl, QPoint, QTimer, QSettings, QSize
from PySide6.QtGui import QColor, QFont, QBrush, QDrag, QPixmap, QPainter, QAction, QIcon
# 导入图片查看器
from lingdongpng import ImageViewerDialog
# 导入召唤魔法模块
from lingdongmofa import MagicDialog, MagicConfig
# from lingdongTXT import TextEditDialog # 移除旧引用
from textEDITgoogle import handle_google_table_double_click, open_edit_dialog_for_item
import json
import base64
import requests
import time
from datetime import datetime
from PySide6.QtCore import QThread, Signal
class PeopleImageGenerationWorker(QThread):
"""人物图片生成工作线程 - 逐个生成图片"""
image_completed = Signal(int, str, str) # 行号(1-based), 图片路径, 提示词
all_completed = Signal(list) # 所有图片信息
error_occurred = Signal(str)
progress_updated = Signal(int, int) # 当前进度, 总数
def __init__(self, image_api, config_file, data_rows):
super().__init__()
self.image_api = image_api # "BANANA" / "BANANA2" / "Midjourney"
self.config_file = config_file
self.data_rows = data_rows
self.all_images = []
self.output_dir = os.path.join(os.getcwd(), "jpg", "people")
# Register to global registry to prevent GC
app = QApplication.instance()
if app:
if not hasattr(app, '_active_people_workers'):
app._active_people_workers = []
app._active_people_workers.append(self)
self.finished.connect(self._cleanup_worker)
def _cleanup_worker(self):
app = QApplication.instance()
if app and hasattr(app, '_active_people_workers'):
if self in app._active_people_workers:
app._active_people_workers.remove(self)
self.deleteLater()
def run(self):
try:
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
total_rows = len(self.data_rows)
# 人物提示词在第3列 (索引2)
prompt_idx = 2
print(f"\n{'='*60}")
print(f"[人物图片生成] 启动任务")
print(f"[人物图片生成] API: {self.image_api}")
print(f"[人物图片生成] 配置文件: {self.config_file}")
print(f"[人物图片生成] 总数: {total_rows}")
# 读取配置
api_config = {}
if self.config_file and os.path.exists(self.config_file):
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
api_config = json.load(f)
except Exception as e:
print(f"[人物图片生成] 读取配置失败: {e}")
# 逐个生成
for i, row_data in enumerate(self.data_rows):
row_idx = i # 0-based index
# 获取提示词
if prompt_idx >= len(row_data):
continue
prompt = str(row_data[prompt_idx]).strip()
if not prompt:
continue
print(f"[人物图片生成] 正在生成第 {row_idx + 1}/{total_rows} 张")
# 获取源图片路径 (如果有)
source_image_path = None
if len(row_data) > 3:
source_image_path = row_data[3]
# 生成图片
image_path = self.generate_single_image(row_idx + 1, prompt, api_config, source_image_path)
if image_path:
self.all_images.append((row_idx + 1, image_path, prompt))
self.image_completed.emit(row_idx + 1, image_path, prompt)
self.progress_updated.emit(row_idx + 1, total_rows)
self.all_completed.emit(self.all_images)
except Exception as e:
error_msg = f"生成失败: {str(e)}"
print(f"[人物图片生成] 错误: {error_msg}")
traceback.print_exc()
self.error_occurred.emit(error_msg)
def generate_single_image(self, shot_number, prompt, api_config, source_image_path=None):
"""生成单张图片"""
try:
if self.image_api == "BANANA":
return self.generate_with_gemini25(shot_number, prompt, api_config, source_image_path)
elif self.image_api == "BANANA2":
return self.generate_with_gemini30(shot_number, prompt, api_config, source_image_path)
elif self.image_api == "Midjourney":
return self.generate_with_midjourney(shot_number, prompt, api_config, source_image_path)
return None
except Exception as e:
print(f"[人物图片生成] 生成失败: {e}")
return None
def generate_with_gemini25(self, shot_number, prompt, api_config, source_image_path=None):
"""使用 BANANA (Gemini 2.0 Flash) 生成"""
try:
# api_config 已经是 gemini.json 的内容
api_key = api_config.get('api_key', '')
api_url = api_config.get('base_url', 'https://generativelanguage.googleapis.com/v1beta')
model = api_config.get('model', 'gemini-2.0-flash-exp')
if not api_key:
print("[BANANA] API Key未配置")
return None
url = f"{api_url}/models/{model}:generateContent?key={api_key}"
parts = [{"text": prompt}]
# 如果有源图片,添加到输入中
if source_image_path and os.path.exists(source_image_path):
try:
with open(source_image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# 简单的MIME类型推断
mime_type = "image/jpeg"
ext = os.path.splitext(source_image_path)[1].lower()
if ext == '.png': mime_type = "image/png"
elif ext == '.webp': mime_type = "image/webp"
parts.append({
"inline_data": {
"mime_type": mime_type,
"data": encoded_string
}
})
print(f"[BANANA] 已添加参考图片: {source_image_path}")
except Exception as e:
print(f"[BANANA] 读取参考图片失败: {e}")
payload = {
"contents": [{"parts": parts}],
"generationConfig": {
"response_modalities": ["IMAGE"],
"temperature": 1.0,
"imageConfig": {"aspectRatio": "16:9", "imageSize": "1K"}
}
}
# Debug: 打印完整的 payload
print(f"[BANANA] Debug Payload:")
try:
# 复制 payload 以避免修改原数据,将 base64 数据截断打印以免刷屏
debug_payload = json.loads(json.dumps(payload))
if 'contents' in debug_payload:
for content in debug_payload['contents']:
if 'parts' in content:
for part in content['parts']:
if 'inline_data' in part and 'data' in part['inline_data']:
part['inline_data']['data'] = "[BASE64_IMAGE_DATA_TRUNCATED]"
print(json.dumps(debug_payload, indent=2, ensure_ascii=False))
except Exception as e:
print(f"[BANANA] Debug Payload Error: {e}")
response = requests.post(url, json=payload, timeout=300)
if response.status_code == 200:
result = response.json()
if 'candidates' in result and result['candidates']:
parts = result['candidates'][0].get('content', {}).get('parts', [])
for part in parts:
image_data = part.get('inline_data', {}).get('data') or part.get('inlineData', {}).get('data')
if image_data:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"people_{shot_number:03d}_{timestamp}.jpg"
filepath = os.path.join(self.output_dir, filename)
with open(filepath, 'wb') as f:
f.write(base64.b64decode(image_data))
return filepath
else:
print(f"[BANANA] 请求失败: {response.status_code} {response.text}")
return None
except Exception as e:
print(f"[BANANA] Error: {e}")
return None
def generate_with_gemini30(self, shot_number, prompt, api_config, source_image_path=None):
"""使用 BANANA2 (Gemini 3.0 Pro) 生成"""
try:
# api_config 已经是 gemini30.json 的内容
api_key = api_config.get('api_key', '')
if not api_key:
print("[BANANA2] API Key未配置")
return None
api_url = api_config.get('base_url', 'https://generativelanguage.googleapis.com/v1beta')
api_url = api_url.rstrip('/')
model = api_config.get('model', 'gemini-3-pro-image-preview')
url = f"{api_url}/models/{model}:generateContent?key={api_key}"
image_config = {
'aspectRatio': api_config.get('size', '16:9'),
'imageSize': api_config.get('resolution', '1K'),
'jpegQuality': int(api_config.get('quality', '80')),
'numberOfImages': 1
}
parts = [{"text": prompt}]
# 如果有源图片,添加到输入中
if source_image_path and os.path.exists(source_image_path):
try:
with open(source_image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# 简单的MIME类型推断
mime_type = "image/jpeg"
ext = os.path.splitext(source_image_path)[1].lower()
if ext == '.png': mime_type = "image/png"
elif ext == '.webp': mime_type = "image/webp"
parts.append({
"inline_data": {
"mime_type": mime_type,
"data": encoded_string
}
})
print(f"[BANANA2] 已添加参考图片: {source_image_path}")
except Exception as e:
print(f"[BANANA2] 读取参考图片失败: {e}")
payload = {
"contents": [{"parts": parts}],
"generationConfig": {
"responseModalities": ["IMAGE", "TEXT"],
"imageConfig": image_config,
"temperature": 0.5
}
}
# Debug: 打印完整的 payload
print(f"[BANANA2] Debug Payload:")
try:
# 复制 payload 以避免修改原数据,将 base64 数据截断打印以免刷屏
debug_payload = json.loads(json.dumps(payload))
if 'contents' in debug_payload:
for content in debug_payload['contents']:
if 'parts' in content:
for part in content['parts']:
if 'inline_data' in part and 'data' in part['inline_data']:
part['inline_data']['data'] = "[BASE64_IMAGE_DATA_TRUNCATED]"
print(json.dumps(debug_payload, indent=2, ensure_ascii=False))
except Exception as e:
print(f"[BANANA2] Debug Payload Error: {e}")
response = requests.post(url, json=payload, timeout=600)
if response.status_code == 200:
result = response.json()
if 'candidates' in result and result['candidates']:
candidate = result['candidates'][0]
parts = candidate.get('content', {}).get('parts', [])
for part in parts:
image_data = part.get('inline_data', {}).get('data') or part.get('inlineData', {}).get('data')
if image_data:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"people_{shot_number:03d}_{timestamp}_{image_config['imageSize']}.jpg"
filepath = os.path.join(self.output_dir, filename)
with open(filepath, 'wb') as f:
f.write(base64.b64decode(image_data))
return filepath
else:
print(f"[BANANA2] 请求失败: {response.status_code} {response.text}")
return None
except Exception as e:
print(f"[BANANA2] Error: {e}")
return None
def generate_with_midjourney(self, shot_number, prompt, api_config, source_image_path=None):
"""使用 Midjourney 生成"""
try:
# api_config 已经是 mj.json 的内容
api_key = api_config.get('api_key', '')
api_url = api_config.get('base_url', '')
if not api_key or not api_url:
print("[Midjourney] API Key或Base URL未配置")
return None
# 去除末尾斜杠,并适配可能的后缀
api_url = api_url.rstrip('/')
# 假设用户填写的Base URL是 https://api.example.com/v1
# 我们需要构造 /imagine 和 /status/taskId
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
# 准备base64图片数据
base64_array = []
if source_image_path and os.path.exists(source_image_path):
try:
with open(source_image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# 尝试构建 Data URI
ext = os.path.splitext(source_image_path)[1].lower().replace('.', '')
if ext == 'jpg': ext = 'jpeg'
data_uri = f"data:image/{ext};base64,{encoded_string}"
base64_array.append(data_uri)
print(f"[Midjourney] 已添加参考图片(Base64): {source_image_path}")
except Exception as e:
print(f"[Midjourney] 读取参考图片失败: {e}")
# 这里假设是 GoAPI 或类似的 MJ Proxy 接口格式
# 提交任务
imagine_url = f"{api_url}/mj/submit/imagine"
# 尝试多种常见路径
paths_to_try = ["/mj/submit/imagine", "/submit/imagine", "/imagine"]
task_id = None
for path in paths_to_try:
try:
current_url = f"{api_url}{path}"
if path.startswith("http"): # 如果用户填写的base_url已经包含了完整路径
current_url = path
payload = {
'prompt': f"{prompt} --ar 16:9",
'base64Array': base64_array,
'notifyHook': "",
'state': ""
}
# Debug: 打印完整的 payload
print(f"[Midjourney] Debug Payload:")
try:
# 复制 payload 以避免修改原数据,将 base64 数据截断打印以免刷屏
debug_payload = json.loads(json.dumps(payload))
if 'base64Array' in debug_payload:
debug_payload['base64Array'] = [f"{item[:30]}...[BASE64_IMAGE_DATA_TRUNCATED]" for item in debug_payload['base64Array']]
print(json.dumps(debug_payload, indent=2, ensure_ascii=False))
except Exception as e:
print(f"[Midjourney] Debug Payload Error: {e}")
print(f"[Midjourney] 尝试提交任务: {current_url}")
resp = requests.post(current_url, headers=headers, json=payload, timeout=30)
if resp.status_code == 200:
res_json = resp.json()
task_id = res_json.get('result') or res_json.get('taskId') or res_json.get('id')
if task_id:
break
except:
continue
if not task_id:
print(f"[Midjourney] 提交任务失败,无法获取Task ID")
return None
print(f"[Midjourney] 任务已提交,Task ID: {task_id}")
# 轮询状态
# 通常查询路径是 /mj/task/{id}/fetch 或 /task/{id}/fetch
fetch_paths = ["/mj/task/{id}/fetch", "/task/{id}/fetch", "/status/{id}"]
max_retries = 60 # 5分钟
for i in range(max_retries):
time.sleep(5)
for path in fetch_paths:
fetch_url = f"{api_url}{path.format(id=task_id)}"
try:
resp = requests.get(fetch_url, headers=headers, timeout=30)
if resp.status_code == 200:
res_json = resp.json()
status = res_json.get('status')
if status == 'SUCCESS' or status == 'completed':
image_url = res_json.get('imageUrl') or res_json.get('url')
if image_url:
# 下载图片
img_resp = requests.get(image_url, timeout=60)
if img_resp.status_code == 200:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"people_{shot_number:03d}_{timestamp}_mj.png"
filepath = os.path.join(self.output_dir, filename)
with open(filepath, 'wb') as f:
f.write(img_resp.content)
return filepath
elif status == 'FAILURE' or status == 'failed':
print(f"[Midjourney] 任务失败: {res_json.get('failReason')}")
return None
# IN_PROGRESS, SUBMITTED 等待
break # 成功获取状态,跳出路径循环,继续等待
except:
pass
print("[Midjourney] 任务超时")
return None
except Exception as e:
print(f"[Midjourney] Error: {e}")
return None
# 批量魔法处理函数 -> 二创员工处理函数
def perform_batch_generation(node, prompt_template):
"""执行批量生成"""
from PySide6.QtWidgets import QMessageBox, QTableWidgetItem
# 1. 检查是否有选中行
selected_rows = set()
for item in node.table.selectedItems():
selected_rows.add(item.row())
target_rows = sorted(list(selected_rows))
# 2. 如果没有选中行,询问是否处理所有行
if not target_rows:
reply = QMessageBox.question(
None,
"二创员工",
"当前未选中任何行,是否对所有行生成提示词?",
QMessageBox.Yes | QMessageBox.No
)
if reply == QMessageBox.No:
return
target_rows = range(node.table.rowCount())
if not target_rows:
QMessageBox.information(None, "提示", "表格为空,无法生成。")
return
# 3. 检查/创建提示词(CN)列
magic_col_index = -1
target_header = "提示词(CN)"
for c in range(node.table.columnCount()):
header_item = node.table.horizontalHeaderItem(c)
if header_item and header_item.text() == target_header:
magic_col_index = c
break
if magic_col_index == -1:
magic_col_index = node.table.columnCount()
node.table.insertColumn(magic_col_index)
node.table.setHorizontalHeaderItem(magic_col_index, QTableWidgetItem(target_header))
node.table.setColumnWidth(magic_col_index, 300)
# 4. 获取提示词模版
# 优先使用中文提示词 (content 通常为中文/原始提示词)
template_content = prompt_template.get("content")
# 如果中文为空,尝试使用英文
if not template_content:
template_content = prompt_template.get("content_en")
if not template_content:
QMessageBox.warning(None, "提示", f"提示词 '{prompt_template.get('name')}' 内容为空,请先设置。")
return
# 5. 开始批量处理
count = 0
for row in target_rows:
# 填充
node.table.setItem(row, magic_col_index, QTableWidgetItem(template_content))
count += 1
QMessageBox.information(None, "完成", f"已为 {count} 个镜头生成提示词(CN)!(使用模板: {prompt_template.get('name')})")
def batch_magic_handler(node):
"""处理二创员工按钮点击"""
from PySide6.QtWidgets import QMessageBox, QMenu
from PySide6.QtGui import QCursor, QAction
from lingdongmofa import MagicConfig, BatchMagicSettingsDialog
# 弹出菜单选择操作
menu = QMenu()
# 1. 设置提示词
settings_action = menu.addAction("⚙️ 设置提示词模版 (风林火山)")
menu.addSeparator()
# 2. 批量生成选项
menu.addAction(QAction("⚡ 二创员工 (请选择提示词):", menu, enabled=False))
prompts = MagicConfig.load_prompts()
for prompt in prompts:
name = prompt.get("name", "未命名")
content_en = prompt.get("content_en", "")
# 显示名称
display_name = f" {name}"
if content_en:
display_name += f" ({content_en[:15]}...)"
action = menu.addAction(display_name)
action.triggered.connect(lambda checked, p=prompt: perform_batch_generation(node, p))
# 在鼠标位置显示菜单
action = menu.exec(QCursor.pos())
if action == settings_action:
# 打开设置对话框
dialog = BatchMagicSettingsDialog(node.scene().views()[0] if node.scene() else None)
dialog.exec()
# 导入提示词列模块
try:
from lingdonggugetishici import add_prompt_column
except ImportError:
print("Warning: lingdonggugetishici module not found")
def add_prompt_column(node):
print("add_prompt_column not available")
class DragTableWidget(QTableWidget):
"""支持拖拽图片的表格控件"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._drag_start_item = None
self.drag_start_pos = None
self.script_dir = None # 用于解析相对路径
self.node = None # 引用父节点
# 连接双击信号,替代mouseDoubleClickEvent以确保在代理控件中能稳定触发
self.cellDoubleClicked.connect(self.on_cell_double_clicked)
def contextMenuEvent(self, event):
"""右键菜单 - 召唤魔法"""
item = self.itemAt(event.pos())
if not item:
super().contextMenuEvent(event)
return
# 创建菜单
menu = QMenu(self)
# 1. 基础操作
copy_action = QAction("📄 复制内容", menu)
copy_action.triggered.connect(lambda: QApplication.clipboard().setText(item.text()))
menu.addAction(copy_action)
menu.addSeparator()
# 2. 魔法操作
# 判断当前列类型
# 0=镜号, 1=时间码, 2=景别, 3=画面内容, 4=台词/音效, 5=备注, 6=开始帧, 7=结束帧
col = item.column()
is_image_col = col in [6, 7]
if is_image_col:
# === 图片列逻辑 ===
# 召唤魔法动作
magic_action = QAction("🔮 召唤魔法", menu)
# 传递当前行和列,以及初始tab索引0 (风)
magic_action.triggered.connect(lambda: self.open_magic_dialog(item.row(), item.column(), 0))
menu.addAction(magic_action)
# 添加保存的提示词作为快捷选项
try:
prompts = MagicConfig.load_prompts()
if prompts:
menu.addSeparator()
menu.addAction(QAction("快捷施法:", menu, enabled=False))
for i, prompt_data in enumerate(prompts):
# 处理字典格式或旧的字符串格式
if isinstance(prompt_data, dict):
name = prompt_data.get("name", f"提示词 {i+1}")
content = prompt_data.get("content", "")
else:
name = f"提示词 {i+1}"
content = str(prompt_data)
# 显示名称,Tooltip显示内容
display_text = name
action = QAction(f"✨ {display_text}", menu)
if content:
action.setToolTip(content[:200])
# 点击直接生成图片
if self.node:
action.triggered.connect(lambda checked, c=content, r=item.row(), col=item.column():
self.node.trigger_magic_generation(c, r, col))
menu.addAction(action)
except Exception as e:
print(f"Error loading magic prompts: {e}")
# 检查是否有图片,如果有,添加生成图片节点选项
img_path = item.text().strip()
user_role_path = item.data(Qt.UserRole)
if user_role_path and isinstance(user_role_path, str) and os.path.exists(user_role_path):
img_path = user_role_path
elif img_path and not os.path.isabs(img_path) and self.script_dir:
try_path = os.path.join(self.script_dir, img_path)
if os.path.exists(try_path):
img_path = try_path
if img_path and os.path.exists(img_path):
menu.addSeparator()
create_node_action = QAction("🖼️ 生成图片节点", menu)
create_node_action.triggered.connect(lambda: self.node.create_image_node(img_path))
menu.addAction(create_node_action)
else:
# === 文本列逻辑 ===
# 允许使用当前文本生成图片到开始帧/结束帧
text_content = item.text().strip()
if text_content:
menu.addAction(QAction("🎨以此文本生成图片:", menu, enabled=False))
gen_start = QAction(" 👉 生成到 [开始帧]", menu)
gen_start.triggered.connect(lambda: self.node.trigger_magic_generation(text_content, item.row(), 6))
menu.addAction(gen_start)
gen_end = QAction(" 👉 生成到 [结束帧]", menu)
gen_end.triggered.connect(lambda: self.node.trigger_magic_generation(text_content, item.row(), 7))
menu.addAction(gen_end)
# 同时也允许调用快捷提示词(追加模式?)
# 暂时先只提供直接生成,避免菜单过长
menu.exec(event.globalPos())
def edit_item_prompt(self, item):
"""编辑单元格的自定义提示词"""
from PySide6.QtWidgets import QInputDialog
# 获取当前提示词 (UserRole + 1)
current_prompt = item.data(Qt.UserRole + 1) or ""
text, ok = QInputDialog.getMultiLineText(
self,
"编辑提示词",
"请输入该图片的专属提示词(设置后将跳过二创员工):",
current_prompt
)
if ok:
# 保存提示词
item.setData(Qt.UserRole + 1, text.strip())
# 更新Tooltip
if text.strip():
item.setToolTip(f"自定义提示词:\n{text.strip()}")
# 可以考虑改变背景色或添加标记,这里暂时只更新Tooltip
else:
item.setToolTip("")
def get_row_content(self, row):
"""获取指定行的文本内容(用于上下文)"""
if row < 0 or row >= self.rowCount():
return ""
# 获取关键列:景别(2), 画面内容(3), 台词(4), 备注(5)
shot = self.item(row, 0).text() if self.item(row, 0) else ""
view = self.item(row, 2).text() if self.item(row, 2) else ""
content = self.item(row, 3).text() if self.item(row, 3) else ""
dialogue = self.item(row, 4).text() if self.item(row, 4) else ""
note = self.item(row, 5).text() if self.item(row, 5) else ""
return f"镜号:{shot} | 景别:{view} | 画面:{content} | 台词:{dialogue} | 备注:{note}"
def open_magic_dialog(self, row, col, initial_index=0):
"""打开召唤魔法对话框"""
# 获取当前图片路径(如果存在)
item = self.item(row, col)
if not item: return
# 尝试获取图片路径
file_path = None
user_role_path = item.data(Qt.UserRole)
if user_role_path and isinstance(user_role_path, str) and os.path.exists(user_role_path):
file_path = user_role_path
else:
text_path = item.text().strip()
if text_path and not os.path.isabs(text_path) and self.script_dir:
try_path = os.path.join(self.script_dir, text_path)
if os.path.exists(try_path):
file_path = try_path
elif text_path and os.path.exists(text_path):
file_path = text_path
# 构建上下文信息
context_info = ""
try:
prev_row = self.get_row_content(row - 1)
curr_row = self.get_row_content(row)
next_row = self.get_row_content(row + 1)
context_info = f"上一镜: {prev_row}\n当前镜: {curr_row}\n下一镜: {next_row}"
except Exception as e:
print(f"Error getting context: {e}")
# 打开对话框
dialog = MagicDialog(file_path, QApplication.activeWindow(), context_info=context_info)
if isinstance(initial_index, int):
dialog.current_index = initial_index
dialog.refresh_tabs()
# 信号连接:当对话框保存提示词后,处理结果
def on_prompts_saved():
# 检查是否有名为"提示词(CN)"的列
magic_col_index = -1
target_header = "提示词(CN)"
for c in range(self.columnCount()):
header_item = self.horizontalHeaderItem(c)
if header_item and header_item.text() == target_header:
magic_col_index = c
break
# 如果没有,创建新列
if magic_col_index == -1:
magic_col_index = self.columnCount()
self.insertColumn(magic_col_index)
self.setHorizontalHeaderItem(magic_col_index, QTableWidgetItem(target_header))
# 如果有node引用,同步更新headers属性(虽然通常是动态获取的)
if self.node:
# 触发节点更新(如果需要)
pass
# 获取当前生成的提示词(优先中文)
# 或者更直接地,我们可以让MagicDialog在保存时发出信号,带上内容
# 这里简单起见,重新加载配置
try:
prompts = MagicConfig.load_prompts()
if prompts and len(prompts) > dialog.current_index:
prompt_data = prompts[dialog.current_index]
# 优先使用中文提示词
content = ""
if isinstance(prompt_data, dict):
content = prompt_data.get("content", "")
if not content:
content = prompt_data.get("content_en", "")
else:
content = str(prompt_data)
if content:
# 填充到当前行的魔法词列
self.setItem(row, magic_col_index, QTableWidgetItem(content))
# 自动调整列宽
self.resizeColumnToContents(magic_col_index)
if self.columnWidth(magic_col_index) > 300:
self.setColumnWidth(magic_col_index, 300)
except Exception as e:
print(f"Error updating magic word column: {e}")
dialog.accepted.connect(on_prompts_saved)
dialog.exec()
def mousePressEvent(self, event):
# 记录鼠标按下时的item
# 尝试直接获取 (适用于viewport坐标)
self._drag_start_item = self.itemAt(event.pos())
# 如果失败,尝试映射坐标 (兼容旧逻辑)
if not self._drag_start_item:
viewport_pos = self.viewport().mapFrom(self, event.pos())
self._drag_start_item = self.itemAt(viewport_pos)
if event.button() == Qt.LeftButton:
self.drag_start_pos = event.pos()
super().mousePressEvent(event)
def mouseReleaseEvent(self, event):
self.drag_start_pos = None
super().mouseReleaseEvent(event)
def on_cell_double_clicked(self, row, column):
"""处理单元格双击信号"""
# 委托给外部模块处理
handle_google_table_double_click(self, row, column, self.script_dir, ImageViewerDialog)
def open_edit_dialog(self, item):
"""打开文本编辑对话框"""
open_edit_dialog_for_item(item, None)
def mouseMoveEvent(self, event):
if self.drag_start_pos and self._drag_start_item:
# 动态检查是否可以拖拽
item = self._drag_start_item
col = item.column()
# 检查表头
header_text = self.horizontalHeaderItem(col).text() if self.horizontalHeaderItem(col) else ""
is_image_col = header_text in ["开始帧", "结束帧", "草稿"]
# 检查是否有图片数据
user_role_path = item.data(Qt.UserRole)
has_image_data = user_role_path and isinstance(user_role_path, str) and os.path.exists(user_role_path)
# 检查文本是否像图片路径
text = item.text().strip()
looks_like_image = text and (text.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp')))
if is_image_col or has_image_data or looks_like_image:
dist = (event.pos() - self.drag_start_pos).manhattanLength()
if dist >= QApplication.startDragDistance():
# 确定最终路径
final_path = None
if has_image_data:
final_path = user_role_path
else:
# 尝试解析路径
if text and not os.path.isabs(text) and self.script_dir:
try_path = os.path.join(self.script_dir, text)
if os.path.exists(try_path):
final_path = try_path
elif text and os.path.exists(text):
final_path = text
if final_path and os.path.exists(final_path):
event.accept()
self._perform_drag(final_path)
self.drag_start_pos = None
return
super().mouseMoveEvent(event)
def _perform_drag(self, file_path):
drag = QDrag(self)
mime_data = QMimeData()
mime_data.setUrls([QUrl.fromLocalFile(file_path)])
drag.setMimeData(mime_data)
# 尝试加载图片作为拖拽预览
pixmap = QPixmap(file_path)
if not pixmap.isNull():
# 缩放图片以适应拖拽预览
# 保持纵横比,最大尺寸 200x200
pixmap = pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
else:
# 设置简单的拖拽视觉反馈 (回退)
pixmap = QPixmap(120, 40)
pixmap.fill(QColor(60, 60, 60, 200))
painter = QPainter(pixmap)
painter.setPen(QColor(255, 255, 255))
font = painter.font()
font.setBold(True)
painter.setFont(font)
painter.drawText(pixmap.rect(), Qt.AlignCenter, "📄 图片文件")
painter.end()
drag.setPixmap(pixmap)
# 设置热点在图片中心
drag.setHotSpot(QPoint(pixmap.width() // 2, pixmap.height() // 2))
# 防止 QGraphicsItem::ungrabMouse 错误
# 在开始拖拽前,如果可能,释放鼠标捕获
# 注意:DragTableWidget 是 QWidget,不能直接调用 ungrabMouse
# 需要通过 graphicsProxyWidget 获取代理项
proxy = self.graphicsProxyWidget()
if proxy and proxy.scene():
grabber = proxy.scene().mouseGrabberItem()
if grabber == proxy:
proxy.ungrabMouse()
drag.exec(Qt.CopyAction | Qt.MoveAction)
# SVG图标定义
SVG_GOOGLE_ICON = '''<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" stroke="currentColor" stroke-width="2"/>
<path d="M14 2v6h6" stroke="currentColor" stroke-width="2"/>
<line x1="16" y1="13" x2="8" y2="13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<line x1="16" y1="17" x2="8" y2="17" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<line x1="10" y1="9" x2="8" y2="9" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>'''
class GoogleScriptNode:
"""谷歌剧本节点"""
@staticmethod
def create_node(CanvasNode):
"""动态创建GoogleScriptNode类,继承自CanvasNode"""
class DynamicDelegate(QStyledItemDelegate):
"""动态调整字体和图标大小的代理"""
def paint(self, painter, option, index):
# 计算动态字体大小
row_height = option.rect.height()
# 基础行高40对应字体10,大行高按比例增加
font_size = max(10, int(row_height / 3.5))
option.font.setPixelSize(font_size)
# 调整图标大小
icon_size = int(row_height * 0.8)
option.decorationSize = QSize(icon_size, icon_size)
super().paint(painter, option, index)
class GoogleScriptNodeImpl(CanvasNode):
# 静态计数器
instance_count = 0
def __init__(self, x, y):
# 更新计数器
GoogleScriptNodeImpl.instance_count += 1
self.node_id = GoogleScriptNodeImpl.instance_count
super().__init__(x, y, 600, 400, f"谷歌剧本 #{self.node_id}", SVG_GOOGLE_ICON)
# 设置背景色
self.setBrush(QBrush(QColor("#ffffff")))
# 创建代理部件容器
self.proxy_widget = QGraphicsProxyWidget(self)
self.proxy_widget.setZValue(10) # 确保在顶层,优先接收点击
# 创建内部部件
self.container = QWidget()
self.container.setStyleSheet("background-color: transparent;")
self.layout = QVBoxLayout(self.container)
self.layout.setContentsMargins(10, 45, 10, 10) # 顶部预留给标题栏
# 初始提示标签
self.hint_label = QLabel("双击上传谷歌剧本TXT/CSV文件")
self.hint_label.setStyleSheet("""
QLabel {
color: #333333;
font-size: 16px;
font-weight: bold;
background-color: transparent;
}
""")
self.hint_label.setAlignment(Qt.AlignCenter)
self.layout.addWidget(self.hint_label)
# 表格部件 (初始隐藏)
self.table = DragTableWidget()
self.table.node = self # 绑定节点引用
self.table.setItemDelegate(DynamicDelegate(self.table)) # 设置动态代理
self.table.setColumnCount(10)
self.table.setHorizontalHeaderLabels(["镜号", "时间码", "景别", "画面内容", "人物", "人物关系/构图", "地点/环境", "运镜", "台词/音效", "备注"])
# 表格样式 - 浅色模式
self.table.setStyleSheet("""
QTableWidget {
background-color: #ffffff;
color: #202124;
gridline-color: #e0e0e0;
border: 1px solid #e0e0e0;
border-radius: 4px;
selection-background-color: #e8f0fe;
selection-color: #1967d2;
}
QHeaderView::section {
background-color: #f1f3f4;
color: #5f6368;
padding: 6px;
border: 1px solid #e0e0e0;
font-weight: bold;
}
QTableWidget::item {
padding: 5px;
}
QScrollBar:vertical {
border: none;
background: #f1f1f1;
width: 10px;
margin: 0px;
}
QScrollBar::handle:vertical {
background: #c1c1c1;