-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuploadergenius.py
9258 lines (7795 loc) · 352 KB
/
uploadergenius.py
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import threading
# import pdb; pdb.set_trace()
# Assuming filter_accounts is the function defined in api.py
from playhouse.shortcuts import model_to_dict
from pathlib import Path, PureWindowsPath, PurePath
from src.models.addtestdata import TestData
from src.bg_music import batchchangebgmusic
import psutil
# here put the import lib
from jsonschema import validate
from jsonschema import ValidationError
import json
import jsons
import tkinter as tk
import webbrowser
from tkinter import OptionMenu, filedialog, ttk, Message, Toplevel
import pandas as pd
import os, queue
import base64
import subprocess
import sys
import random
import os
import time
from src.models.create_tables import *
from src.models.proxy_model import *
from src.models.account_model import *
from src.comboxToolip import ComboboxTip
from src.models.platform_model import *
from src.models.upload_setting_model import *
from src.models.task_model import *
from src.models.youtube_video_model import *
# comment this fastapiserver import will cause cx freeze not include the file
# import src.app.fastapiserver
# from src.app import fastapiserver
from fastapi.staticfiles import StaticFiles
# import multiprocessing.dummy as mp
import concurrent
from glob import glob
from src.bg_music import using_free_music
from PIL import Image, ImageTk
import multiprocessing as mp
from src.upload import *
from src.tooltip import Tooltip
from datetime import datetime, date, timedelta
import asyncio
import requests
import re
import calendar
from upgenius.utils.webdriver.setupPL import checkRequirments
import logging
from src.gpt_thumbnail import draw_text_on_image, validateSeting
from src.checkIp import CheckIP
from src.models.create_tables import *
from src.utils.tkutils import showinfomsg, find_key
try:
import tkinter.scrolledtext as ScrolledText
except ImportError:
import Tkinter as tk # Python 2.x
import ScrolledText
import pyperclip as clip
import platform
from pystray import MenuItem as item
import pystray
from i18n_json import i18n_json
from src.log import logger
from src.accountTablecrud import *
from src.taskTablecrud import *
from src.proxyTablecrud import *
task_queue = queue.Queue()
done_tasks = 0
taskcounts=0
if platform.system() == "Windows":
ultra = i18n_json(shared_lock=True, recurse=True)
tmp = i18n_json(shared_lock=True, recurse=True)
citydb = i18n_json(shared_lock=True, recurse=True)
else:
ultra = i18n_json(recurse=True)
tmp = i18n_json(recurse=True)
citydb = i18n_json(recurse=True)
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
datadir = os.path.dirname(__file__)
# https://stackoverflow.com/questions/56733085/how-to-know-the-current-file-path-after-being-frozen-into-an-executable-using-cx
ROOT_DIR = datadir
# if sys.platform=='darwin':
# ROOT_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))
import os
tmp["ROOT_DIR"] = datadir
videoassetsfilename = "videos-assets.json"
citydbfilename = "assets/country-db/qq/en_loclist.json"
settingfilename = "settings.json"
iconfilename="assets/icon.ico"
locale = "en"
window_size = "1024x720"
height = 720
width = 1024
supported_video_exts = [".flv", ".mp4", ".avi"]
supported_thumb_exts = [".jpeg", ".png", ".jpg", "webp"]
supported_des_exts = [".des"]
supported_tag_exts = [".tags"]
supported_schedule_exts = [".schedule"]
supported_meta_exts = [".json", ".xls", ".xlsx", ".csv"]
window = None
availableScheduleTimes = []
uvicorn_subprocess=None
class QueueHandler(logging.Handler):
"""Class to send logging records to a queue
It can be used from different threads
"""
def __init__(self, log_queue):
super().__init__()
self.log_queue = log_queue
def emit(self, record):
self.log_queue.put(record)
class ConsoleUi:
"""Poll messages from a logging queue and display them in a scrolled text widget"""
def __init__(self, frame, root, row=0, column=0):
self.frame = frame
# Create a ScrolledText wdiget
self.scrolled_text = ScrolledText.ScrolledText(frame, state="disabled")
self.scrolled_text.bind_all("<Control-c>", self.copy)
# Bind right-click event to show context menu
# https://stackoverflow.com/questions/30668425/tkinter-right-click-popup-unresponsive-on-osx
MAC_OS = False
if sys.platform == "darwin":
MAC_OS = True
if MAC_OS:
self.scrolled_text.bind("<Button-2>", self.show_context_menu)
else:
self.scrolled_text.bind("<Button-3>", self.show_context_menu)
self.context_menu = tk.Menu(root, tearoff=0)
self.context_menu.add_command(label="Clear All Text", command=self.clear_text)
self.scrolled_text.grid(row=row, column=column, columnspan=2, sticky="nswe")
self.scrolled_text.configure(font="TkFixedFont")
self.scrolled_text.tag_config("INFO", foreground="black")
self.scrolled_text.tag_config("DEBUG", foreground="gray")
self.scrolled_text.tag_config("WARNING", foreground="orange")
self.scrolled_text.tag_config("ERROR", foreground="red")
self.scrolled_text.tag_config("CRITICAL", foreground="red", underline=1)
# Create a logging handler using a queue
self.log_queue = queue.Queue()
self.queue_handler = QueueHandler(self.log_queue)
formatter = logging.Formatter("%(asctime)s: %(message)s")
self.queue_handler.setFormatter(formatter)
logger.addHandler(self.queue_handler)
# Start polling messages from the queue
self.frame.after(100, self.poll_log_queue)
def clear_text(self):
self.scrolled_text.configure(state="normal") # Enable text widget
self.scrolled_text.delete(1.0, tk.END) # Delete all text
self.scrolled_text.configure(state="disabled") # Disable text widget again
# Create a right-click context menu
def show_context_menu(self, event):
self.context_menu.post(event.x_root, event.y_root)
def copy(self, event):
try:
string = event.widget.selection_get()
clip.copy(string)
except:
pass
def display(self, record):
msg = self.queue_handler.format(record)
self.scrolled_text.configure(state="normal")
self.scrolled_text.insert(tk.END, msg + "\n", record.levelname)
self.scrolled_text.configure(state="disabled")
# Autoscroll to the bottom
self.scrolled_text.yview(tk.END)
def poll_log_queue(self):
# Check every 100ms if there is a new message in the queue to display
while True:
try:
record = self.log_queue.get(block=False)
except queue.Empty:
break
else:
self.display(record)
self.frame.after(100, self.poll_log_queue)
class TextHandler(logging.Handler):
# This class allows you to log to a Tkinter Text or ScrolledText widget
# Adapted from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06
def __init__(self, text):
# run the regular Handler __init__
logging.Handler.__init__(self)
# Store a reference to the Text it will log to
self.text = text
self.max_length = 250
def emit(self, record):
msg = self.format(record)
if len(msg) > self.max_length:
lines = []
while len(msg) > self.max_length:
lines.append(msg[: self.max_length])
msg = msg[self.max_length :]
lines.append(msg)
msg = "\n".join(lines)
def append():
self.text.configure(state="normal")
self.text.insert(tk.END, msg + "\n")
self.text.configure(state="disabled")
# Autoscroll to the bottom
self.text.yview(tk.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
def url_ok(url, proxy_option=""):
try:
if not proxy_option == "":
# proxies = {
# 'http': 'http://proxy.example.com:8080',
# 'https': 'http://secureproxy.example.com:8090',
# }
if "http:" in proxy_option:
proxies = {"http": proxy_option}
elif "https:" in proxy_option:
proxies = {
"https": proxy_option,
}
elif "socks" in proxy_option:
proxies = {
"http": proxy_option,
"https": proxy_option,
}
else:
proxy_option = "http://"
proxies = {
"http": proxy_option,
"https": proxy_option,
}
print("use proxy", proxy_option)
response = requests.head(url, proxies=proxies)
print("google access is ok use {proxy_option}")
else:
response = requests.head(url)
print("we cant access google without proxy")
except Exception as e:
# print(f"NOT OK: {str(e)}")
print("we cant access google")
return False
else:
print("status code", response.status_code)
if response.status_code == 200:
print("we cant access google")
return True
else:
print(f"NOT OK: HTTP response code {response.status_code}")
return False
def isfilenamevalid(filename):
# print(imagename)
invalid = '…,<>:."/\|?*!$\'"#'
for char in invalid:
filename = filename.replace(char, "")
if len(filename) > 260:
filename = filename[:259]
return filename
def fix_size(old_image_path, new_image_path, canvas_width=1080, canvas_height=720):
"""Edited from https://stackoverflow.com/questions/44231209/resize-rectangular-image-to-square-keeping-ratio-and-fill-background-with-black"""
im = Image.open(old_image_path)
x, y = im.size
ratio = x / y
desired_ratio = canvas_width / canvas_height
w = max(canvas_width, x)
h = int(w / desired_ratio)
if h < y:
h = y
w = int(h * desired_ratio)
mode = im.mode
print(mode)
if len(mode) == 1: # L, 1
new_background = 0
if len(mode) == 3: # RGB
new_background = (0, 0, 0)
if len(mode) == 4: # RGBA, CMYK
new_background = (0, 0, 0, 0)
new_im = Image.new(mode, (w, h), new_background)
new_im.paste(im, ((w - x) // 2, (h - y) // 2))
img = new_im.resize((canvas_width, canvas_height))
if mode == "RGBA":
img = img.convert("RGB")
img.save(new_image_path)
def load_locales():
folder_path = ROOT_DIR + os.sep + "locales" + os.sep
# Get a list of all files in the folder
file_list = os.listdir(folder_path)
# Filter the list to include only JSON files
json_files = [f for f in file_list if f.endswith(".json")]
# Loop through the JSON files and read their contents
for json_file in json_files:
file_path = os.path.join(folder_path, json_file)
with open(file_path, "r") as file:
data = json.load(file)
def load_citydb():
global citydb
dbfile = PurePath(ROOT_DIR, citydbfilename)
print(f"start to load country data {dbfile}")
# print('===',open(dbfile,encoding='utf-8').read())
failed = False
if os.path.exists(dbfile):
try:
datas = json.loads(open(dbfile, encoding="utf-8").read())
# print('json data',datas)
citydb = datas
# for key,value in enumerate(datas):
# print(f'load country db {key} {value}')
# citydb[key]=value
except:
failed = True
print("load country db file failure")
else:
failed = True
print("country db file not exist")
def load_setting():
global settings
settingfile = os.path.join(ROOT_DIR, settingfilename)
failed = False
if os.path.exists(settingfile):
try:
fp = open(settingfile, "r", encoding="utf-8")
setting_json = fp.read()
fp.close()
settings = json.loads(setting_json)
except:
failed = True
else:
failed = True
if failed == True:
logger.debug("start initialize settings with default")
print("start initialize settings with default")
try:
settings
except:
if platform.system() != "Windows":
settings = i18n_json(recurse=True)
else:
settings = i18n_json(shared_lock=True, recurse=True)
settings["lastuselang"] = "en"
settings["zh"] = json.loads(
open(
os.path.join(ROOT_DIR + os.sep + "locales", "zh.json"),
"r",
encoding="utf-8",
).read()
)
settings["en"] = json.loads(
open(
os.path.join(ROOT_DIR + os.sep + "locales", "en.json"),
"r",
encoding="utf-8",
).read()
)
logger.debug("end to initialize settings with default")
# print(settings)
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
# 加载剧本
settingid = 0
# 保存配置
def select_tabview_video_folder(folder_variable, cache_var):
global thumbView_video_folder_path
try:
thumbView_video_folder_path = filedialog.askdirectory(
parent=root, initialdir="/", title="Please select a directory"
)
if os.path.exists(thumbView_video_folder_path):
folder_variable.set(thumbView_video_folder_path)
ultra[cache_var] = thumbView_video_folder_path
print(f"You chose {folder_variable.get()} for {cache_var}")
tmp[cache_var] = folder_variable.get()
otherfolders = [
"thumbView_video_folder",
"tagView_video_folder",
"scheduleView_video_folder",
"desView_video_folder",
"metaView_video_folder",
]
for i in otherfolders.remove(folder_variable):
if i == "" or i is None:
tmp[i] = folder_variable.get()
tmp["lastfolder"] = folder_variable.get()
print("==", tmp)
else:
print("please choose a valid video folder")
showinfomsg(message="please choose a valid video folder")
except:
print("please choose a valid video folder")
showinfomsg(message="please choose a valid video folder")
def openLocal(folder):
try:
webbrowser.open("file:///" + folder)
except:
logger.error(f"please choose a valid video folder:\n{folder}")
showinfomsg(message="please choose a valid video folder")
def select_videosView_video_folder():
global videosView_video_folder_path
try:
videosView_video_folder_path = filedialog.askdirectory(
parent=root, initialdir="/", title="Please select a directory"
)
if os.path.exists(videosView_video_folder_path):
print("You chose %s" % videosView_video_folder_path)
videosView_video_folder.set(videosView_video_folder_path)
print("You chose %s" % videosView_video_folder.get())
else:
print("please choose a valid video folder")
except:
print("please choose a valid video folder")
def select_videos_folder():
global video_folder_path
try:
video_folder_path = filedialog.askdirectory(
parent=root, initialdir="/", title="Please select a directory"
)
if os.path.exists(video_folder_path):
print("You chose %s" % video_folder_path)
else:
print("please choose a valid video folder")
except:
print("please choose a valid video folder")
def select_folder(dict, value):
global music_folder_path
try:
music_folder_path = filedialog.askdirectory(
parent=root, initialdir="/", title="Please select a directory"
)
if os.path.exists(music_folder_path):
print("You chose %s" % music_folder_path)
dict = music_folder_path
value.set(music_folder_path)
else:
print("please choose a valid music folder")
except:
print("please choose a valid music folder")
docsopen = False
def docs(frame, lang):
newWindow = tk.Toplevel(frame)
newWindow.geometry(window_size)
print("open docmentations")
label_helptext_setting = tk.Label(
newWindow,
text=settings[locale]["docs_str"].replace("\\n", "\n"),
justify="left",
wraplength=450,
)
label_helptext_setting.pack()
def version(frame, lang):
newWindow = tk.Toplevel(frame)
newWindow.geometry(window_size)
label_helptext_setting = tk.Label(
newWindow,
text=settings[locale]["version_str"].replace("\\n", "\n"),
# text = "First line\n and this is the second",
justify="left",
)
label_helptext_setting.pack()
def contact(frame, lang):
newWindow = tk.Toplevel(frame)
newWindow.geometry(window_size)
# due to \n in json string should in \\n, so read it from json need to convert to original
label_helptext_setting = tk.Label(
newWindow,
text=settings[locale]["contact_str"].replace("\\n", "\n"),
anchor="e",
justify="left",
wraplength=450,
)
label_helptext_setting.pack()
group = tk.Label(
newWindow,
text=settings[locale]["contact_str_group"],
anchor="e",
justify="left",
)
group.pack()
path_group = "./assets/feishu-chatgroup.jpg"
img_group = Image.open(path_group)
photo_group = ImageTk.PhotoImage(img_group)
label_group = tk.Label(newWindow, image=photo_group, height=400, width=256)
label_group.pack()
personal = tk.Label(
newWindow,
text=settings[locale]["contact_str_personal"].replace("\\n", "\n"),
anchor="e",
justify="left",
)
personal.pack()
path_personal = "./assets/wechat.jpg"
img_personal = Image.open(path_personal)
photo_personal = ImageTk.PhotoImage(img_personal) # 在root实例化创建,否则会报错
label_personal = tk.Label(newWindow, image=photo_personal, height=400, width=256)
label_personal.pack()
newWindow.mainloop()
def install():
# subprocess.check_call([sys.executable, "-m", "playwright ", "install"])
subprocess.check_call(["playwright ", "install"])
def testInstallRequirements():
print("check install requirments")
checkRequirments()
def testNetwork():
print("start to test network and proxy setting")
fnull = open(os.devnull, "w")
return1 = subprocess.call(
"ping www.whoer.net", shell=True, stdout=fnull, stderr=fnull
)
if return1:
print("network not ready")
# change_proxy()
testNetwork()
else:
fnull.close()
return True
print("netwrork and proxy test is done")
def ValidateSetting():
print("start to validate your upload settings")
time.sleep(4)
print("end to validate your upload settings")
async def bulk_pull_cookie_file():
ytupload = YoutubeUpload(browserType="firefox", logger=logger)
# query account in db
username = None
password = None
login = await ytupload.youtube_login(username, password)
if login:
logger.debug("we need save cookie to future usage")
cookiepath = username + datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".json"
await ytupload.page.context.storage_state(path=cookiepath)
def auto_gen_cookie_file(username, password, platform, proxy=None, cookiepath=None):
print("call upgenius gen cookie api")
if proxy is None or proxy == "":
proxyserver = None
else:
print(f"get proxy:{proxy}")
id = CustomID(custom_id=proxy).to_bin()
proxydata = ProxyModel.get_proxy_by_id(id=id)
certification = None
print(f"proxy username:{proxydata.proxy_username}")
if proxydata.proxy_username is not None:
certification = f"@{proxydata.proxy_username}:{proxydata.proxy_password}"
server = None
if proxydata.proxy_host is not None:
server = f"{proxydata.proxy_host}:{proxydata.proxy_port}"
protocol = None
if proxydata.proxy_protocol is not None:
protocol = proxydata.proxy_protocol.lower()
if certification is None:
proxyserver = f"{protocol}://{server}"
else:
proxyserver = f"{protocol}://{server}{certification}"
browserType = "firefox"
url = None
sites = settings[locale]["supportedsites"]
platformname = None
if type(platform) == int:
try:
platformname = getattr(PLATFORM_TYPE.PLATFORM_TYPE_TEXT, platform)
except:
logger.error("please add platform in database")
else:
platformname = platform
try:
url = sites[platformname]
except:
logger.error("please add url in json file")
print(f"url{url}")
if browserType in ["firefox", "webkit", "chromium"]:
if proxyserver:
command = (
"playwright codegen -b "
+ browserType
# + ' --device "iPhone 12" '
# + ' --device "iPad Pro 11 landscape" '
+ " --proxy-server "
+ proxyserver
+ " --lang 'en-GB' --save-storage="
+ username
+ "-cookie.json "
+ url
)
else:
command = (
"playwright codegen -b "
+ browserType
# + ' --device "iPhone 12" '
+ " --lang 'en-GB' --save-storage="
+ username
+ "-cookie.json "
+ url
)
result = subprocess.run(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
)
print(result)
if result.returncode:
print(f"failed to save cookie file:{result.stderr}")
logger.error(f"failed to save cookie file:{result.stderr}")
showinfomsg(message=f"failed to save cookie file:{result.stderr}")
else:
print(f"just check your cookie file:{username}-cookie.json")
logger.debug(f"just check your cookie file:{username}-cookie.json")
cookiepath.set(PurePath(ROOT_DIR, username + "-cookie.json "))
def select_file(title, variable, cached=None, limited="all", parent=None):
file_path = ""
try:
if limited == "json":
file_path = filedialog.askopenfilenames(
title=title,
filetypes=[("Json", "*.json"), ("All Files", "*")],
parent=parent,
)[0]
elif limited == "images":
file_path = filedialog.askopenfilenames(
title=title,
filetypes=[
("JPEG", "*.jpg"),
("PNG", "*.png"),
("JPG", "*.jpg"),
("WebP", "*.webp"),
("All Files", "*"),
],
parent=parent,
)[0]
else:
file_path = filedialog.askopenfilenames(
title=title, filetypes=[("All Files", "*")], parent=parent
)[0]
variable.set(file_path)
if cached is not None:
cached = file_path
except:
print("please select a valid file")
# 清理残留文件
def threadusing_free_musichelper(numbers):
using_free_music(numbers[0], numbers[1])
def init_worker(mps, fps, cut):
global memorizedPaths, filepaths, cutoff
global DG
print("process initializing", mp.current_process())
memorizedPaths, filepaths, cutoff = mps, fps, cut
DG = 1 ##nx.read_gml("KeggComplete.gml", relabel = True)
def hiddenwatermark():
print("add hiddenwatermark to each video for copyright theft")
def b64e(s):
return base64.b64encode(s.encode()).decode()
def autothumb():
# 文件夹下是否有视频文件
# 视频文件是否有同名的图片
try:
video_folder_path = tmp["video_folder"]
except NameError:
print("not found fastlane folder file")
else:
if video_folder_path:
print("sure, it was defined dir.", video_folder_path)
# check_video_thumb_pair(video_folder_path,False)
else:
print("pls choose file or folder")
def editVideoMetas():
print("go to web json editor to edit prepared video metas in json format")
def SelectMetafile(cachename, var):
logger.debug("start to import prepared video metas in json format")
try:
filepath = filedialog.askopenfilenames(
title="choose meta file",
filetypes=[
("Json", "*.json"),
("excel", "*.xls"),
("csv", "*.csv"),
("Excel", "*.xlsx"),
("All Files", "*"),
],
)[0]
tmp[cachename] = filepath
var.set(filepath)
except:
logger.error("you should choose a valid path")
# setting['channelcookiepath'] = channel_cookie_path
logger.debug("finished to import prepared video metas in json format")
def chooseAccountsView(newWindow, parentchooseaccounts):
chooseAccountsWindow = tk.Toplevel(newWindow)
chooseAccountsWindow.geometry(window_size)
chooseAccountsWindow.title("Choose associated account")
def refreshAccount(*args):
parentchooseaccounts.set(account_var.get())
account_var = tk.StringVar()
lbl16 = tk.Label(chooseAccountsWindow, text="binded accounts")
lbl16.grid(row=5, column=0, sticky=tk.W)
txt16 = tk.Entry(
chooseAccountsWindow,
textvariable=account_var,
width=int(int(window_size.split("x")[-1]) / 5),
)
txt16.grid(row=6, column=0, sticky=tk.W)
account_var.trace("w", refreshAccount)
accountView(chooseAccountsWindow, mode="bind", linkAccounts=account_var)
def isFilePairedMetas(r, videofilename, meta_exts_list, dict, meta_name):
logger.debug(f"start to check {meta_name} for video: {videofilename}")
print(f"before check:\n{jsons.dump(dict[meta_name])}")
for ext in meta_exts_list:
logger.debug(f"start to {ext}--{meta_name}")
print(f"start to {ext}")
metapath = os.path.join(r, videofilename + ext)
if os.path.exists(metapath):
logger.debug(
f"meta filed {meta_name} for {videofilename} is exist:\n {metapath}"
)
if dict[meta_name] is not None and metapath not in dict[meta_name]:
if dict[meta_name].has_key(videofilename) == False:
dict[meta_name][videofilename] = []
logger.debug(f"intial {meta_name} for {videofilename}:\n")
if not metapath in dict[meta_name][videofilename]:
dict[meta_name][videofilename].append(metapath)
print(f"append result:\n{dict[meta_name][videofilename]}")
if meta_name == "thumbFilePaths":
logger.debug(
f"found thumbfiles,start to set video metas {type(dict['videos'][videofilename]['thumbnail_local_path'])},{dict['videos'][videofilename]['thumbnail_local_path']}"
)
if (
dict["videos"][videofilename]["thumbnail_local_path"] is None
or dict["videos"][videofilename]["thumbnail_local_path"] == ""
):
print("video meta thumbnail is None")
print(f"try to add {metapath}")
print(dict["videos"][videofilename])
emptyfiles = []
emptyfiles.append(metapath)
print("empty", emptyfiles)
dict["videos"][videofilename]["thumbnail_local_path"] = str(
emptyfiles
)
print(dict["videos"][videofilename])
print(
"update video meta thumbnail",
dict["videos"][videofilename]["thumbnail_local_path"],
)
print(
f"found thumbfiles,end to set video metas is None== {ext}== {type(dict['videos'][videofilename]['thumbnail_local_path'])},{dict['videos'][videofilename]['thumbnail_local_path']}"
)
else:
if (
type(dict["videos"][videofilename]["thumbnail_local_path"])
== str
):
dict["videos"][videofilename][
"thumbnail_local_path"
] = eval(
dict["videos"][videofilename]["thumbnail_local_path"]
).append(
metapath
)
else:
if (
not metapath
in dict["videos"][videofilename]["thumbnail_local_path"]
):
dict["videos"][videofilename][
"thumbnail_local_path"
].append(metapath)
print(
f"found thumbfiles,end to set video metas {ext}== {type(dict['videos'][videofilename]['thumbnail_local_path'])},{dict['videos'][videofilename]['thumbnail_local_path']}"
)
logger.debug(
f"found thumbfiles,end to set video metas {type(dict['videos'][videofilename]['thumbnail_local_path'])},{dict['videos'][videofilename]['thumbnail_local_path']}"
)
elif meta_name == "desFilePaths":
logger.debug(
f"found des files,start to set video metas {type(dict['videos'][videofilename]['video_description'])},{dict['videos'][videofilename]['video_description']}"
)
# 判断后缀是否包含国家编码
#如果发现多个后缀为.des的文件,自动根据suffix判断,en为默认,其他的全部丢到 otherdes 这个字段中,列表形式存储
with open(metapath, "r", encoding="utf-8") as f:
lines = f.readlines()
contents = "\r".join(lines)
contents = contents.replace("\n", "")
dict["videos"][videofilename]["video_description"] = contents
logger.debug(
f"found des files,end to set video metas {type(dict['videos'][videofilename]['video_description'])},{dict['videos'][videofilename]['video_description']}"
)
elif meta_name == "tagFilePaths":
logger.debug(
f"found tag files,start to set video metas {type(dict['videos'][videofilename]['tags'])},{dict['videos'][videofilename]['tags']}"
)
with open(metapath, "r", encoding="utf-8") as f:
lines = f.readlines()
contents = "\r".join(lines)
contents = contents.replace("\n", "")
dict["videos"][videofilename]["tags"] = contents
logger.debug(
f"found tag files,end to set video metas {type(dict['videos'][videofilename]['tags'])},{dict['videos'][videofilename]['tags']}"
)
print(
f"after check:\n {jsons.dump(dict[meta_name])}:\n,{dict['videos'][videofilename]['thumbnail_local_path']}"
)
logger.debug(
f"after check:\n {jsons.dump(dict[meta_name])}:\n,{dict['videos'][videofilename]['thumbnail_local_path']}"
)
tmpjson = os.path.join(r, videofilename + ".json")
if os.path.exists(tmpjson):
logger.debug(f"update to {videofilename} meta json")
with open(tmpjson, "w") as f:
f.write(jsons.dumps(dict["videos"][videofilename]))
else:
logger.debug(f"create a fresh {videofilename} meta json")
with open(tmpjson, "a") as f:
f.write(jsons.dumps(dict["videos"][videofilename]))
def syncVideometa2assetsjson(selectedMetafileformat, folder):
changed_df_metas = None
if os.path.exists(
os.path.join(folder, "videos-meta." + selectedMetafileformat)
) and ultra.has_key(folder):
if selectedMetafileformat == "xlsx":
changed_df_metas = pd.read_excel(
os.path.join(folder, "videos-meta.xlsx"), index_col=[0]
)
changed_df_metas.replace("nan", "")
changed_df_metas = json.loads(changed_df_metas.to_json(orient="index"))
elif selectedMetafileformat == "json":
changed_df_metas = pd.read_json(os.path.join(folder, "videos-meta.json"))
changed_df_metas.replace("nan", "")
changed_df_metas = json.loads(changed_df_metas.to_json())
elif selectedMetafileformat == "csv":
changed_df_metas = pd.read_csv(
os.path.join(folder, "videos-meta.csv"), index_col=[0]
)