-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.py
1294 lines (1067 loc) · 35.7 KB
/
io.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
import datetime
import http.server
import json
import os.path
import shutil
import socketserver
import textwrap
import zipfile
from enum import Enum
from pathlib import Path as PathlibPath
from typing import TypeVar, Type, Optional, Union
import docker
import pysubs2
import yaml
from addict import Dict
from docker import DockerClient
from jsonpath_ng import parse
from langdetect import detect, LangDetectException
from loguru import logger
from pydantic import BaseModel
from pysubs2 import SSAEvent
from pyext.commons import CommandLine, Size
from pyext.exceptions import parse_exceptions
TF = TypeVar("TF", bound="File")
TPM = TypeVar("TPM", bound=BaseModel)
TAF = TypeVar("TAF", bound="AudioFile")
TSBT = TypeVar("TSBT", bound="SubtitleFile")
# region aeneas
class LanguageCode(str, Enum):
"""
aeneas支持的语言代码
"""
AFR = "afr"
AMH = "amh"
ARA = "ara"
ARG = "arg"
ASM = "asm"
AZE = "aze"
BEN = "ben"
BOS = "bos"
BUL = "bul"
CAT = "cat"
CES = "ces"
CMN = "cmn"
"""中文普通话"""
CYM = "cym"
DAN = "dan"
DEU = "deu"
ELL = "ell"
ENG = "eng"
EPO = "epo"
EST = "est"
EUS = "eus"
FAS = "fas"
FIN = "fin"
FRA = "fra"
GLA = "gla"
GLE = "gle"
GLG = "glg"
GRC = "grc"
GRN = "grn"
GUJ = "guj"
HEB = "heb"
HIN = "hin"
HRV = "hrv"
HUN = "hun"
HYE = "hye"
INA = "ina"
IND = "ind"
ISL = "isl"
ITA = "ita"
JBO = "jbo"
JPN = "jpn"
KAL = "kal"
KAN = "kan"
KAT = "kat"
KIR = "kir"
KOR = "kor"
KUR = "kur"
LAT = "lat"
LAV = "lav"
LFN = "lfn"
LIT = "lit"
MAL = "mal"
MAR = "mar"
MKD = "mkd"
MLT = "mlt"
MSA = "msa"
MYA = "mya"
NAH = "nah"
NEP = "nep"
NLD = "nld"
NOR = "nor"
ORI = "ori"
ORM = "orm"
PAN = "pan"
PAP = "pap"
POL = "pol"
POR = "por"
RON = "ron"
RUS = "rus"
SIN = "sin"
SLK = "slk"
SLV = "slv"
SPA = "spa"
SQI = "sqi"
SRP = "srp"
SWA = "swa"
SWE = "swe"
TAM = "tam"
TAT = "tat"
TEL = "tel"
THA = "tha"
TSN = "tsn"
TUR = "tur"
UKR = "ukr"
URD = "urd"
VIE = "vie"
YUE = "yue"
ZHO = "zho"
"""中文"""
@classmethod
def from_langdetect(cls, code: str) -> Optional["LanguageCode"]:
mapping = {
"en": cls.ENG,
"fr": cls.FRA,
"zh-cn": cls.CMN,
"ru": cls.RUS,
"ja": cls.JPN,
# 添加更多映射...
}
return mapping.get(code)
class Aeneas(object):
def __init__(self):
super().__init__()
@classmethod
def from_env(cls):
"""
自动
"""
try:
docker_client = docker.from_env()
logger.info("使用Docker运行aeneas")
return DockerAeneas(docker_client)
except:
logger.info("使用本地aeneas")
return LocalAeneas()
@classmethod
def detect_language(cls, text: str) -> LanguageCode | None:
"""
检测文本的语言
Args:
text: 文本
Returns:
语言代码
"""
try:
return detect(text)
except LangDetectException:
return None
# region 强制对齐音频和文本
def force_align(
self,
audio_file: TAF,
text: str,
language_code: LanguageCode = None,
format: str = "srt",
) -> Union["SrtSubtitleFile", "JsonFile"]:
"""
将音频文件与文本强制对齐
Args:
audio_file: 音频文件
text: 文本
language_code: 语言代码,如果为None,则自动检测
format: 格式,默认为srt
Returns:
srt字幕文件
"""
raise NotImplementedError()
# endregion
class LocalAeneas(Aeneas):
def __init__(self):
"""
使用本地aeneas
"""
super().__init__()
def force_align(
self,
audio_file: TAF,
text: str,
language_code: LanguageCode = None,
format: str = "srt",
) -> Union["SrtSubtitleFile", "JsonFile"]:
language_code = language_code or LanguageCode.from_langdetect(
self.detect_language(text)
)
content_text_file_name = f"{audio_file.path.stem}-content.txt"
content_text_file = File(str(audio_file.path.parent / content_text_file_name))
content_text_file.write_content(text)
audio_file_name = audio_file.path.name
audio_file_dir = str(audio_file.path.parent)
if format == "srt":
file_name = f"{audio_file.path.stem}.srt"
elif format == "json":
file_name = f"{audio_file.path.stem}.json"
else:
raise ValueError(f"不支持的格式: {format}")
command = [
"py",
"-3.9",
"-m",
"aeneas.tools.execute_task",
audio_file_name,
content_text_file_name,
f"task_language={language_code.value}|os_task_file_format={format}|is_text_type=plain",
file_name,
]
logger.info(f"使用以下命令行先将音频文件与文本强制对齐: {command}")
output = CommandLine.run_and_get(command, audio_file_dir).output
logger.info(f"将音频文件与文本强制对齐的日志: {output}")
if format == "srt":
return SrtSubtitleFile(str(audio_file.path.parent / file_name))
elif format == "json":
return JsonFile(str(audio_file.path.parent / file_name))
class DockerAeneas(Aeneas):
def __init__(
self, docker_client: DockerClient, aeneas_image: str = "dongjak/aeneas"
):
"""
使用Docker运行aeneas
"""
super().__init__()
self.docker_client = docker_client
"""docker客户端"""
self.aeneas_image = aeneas_image
"""使用的docker镜像"""
def force_align(
self,
audio_file: TAF,
text: str,
language_code: LanguageCode = None,
format: str = "srt",
) -> Union["SrtSubtitleFile", "JsonFile"]:
language_code = language_code or LanguageCode.from_langdetect(
self.detect_language(text)
)
content_text_file = File(
str(audio_file.path.parent / f"{audio_file.path.stem}-content.txt")
)
content_text_file.write_content(text)
if format == "srt":
file_name = f"{audio_file.path.stem}.srt"
elif format == "json":
file_name = f"{audio_file.path.stem}.json"
else:
raise ValueError(f"不支持的格式: {format}")
command = (
f'bash -c "source ~/miniconda3/etc/profile.d/conda.sh; '
f"conda activate aeneas; "
f"python -m aeneas.tools.execute_task "
f"/tmp_app/{audio_file.path.name} /tmp_app/{audio_file.path.stem}-content.txt "
f"'task_language={language_code.value}|os_task_file_format={format}|is_text_type=plain' "
f'/tmp_app/{file_name};"'
)
local_mapping_dir = str(audio_file.path.parent.absolute())
full_command = f"docker run --rm -it -v {local_mapping_dir}:/tmp_app {self.aeneas_image} {command}"
logger.info(f"使用以下命令行先将音频文件与文本强制对齐: {full_command}")
logs = (
self.docker_client.containers.run(
self.aeneas_image,
command,
volumes={local_mapping_dir: {"bind": "/tmp_app", "mode": "rw"}},
remove=True,
tty=True,
stdin_open=True,
)
.decode("utf-8")
.strip()
)
logger.info(f"将音频文件与文本强制对齐的日志: {logs}")
if format == "srt":
return SrtSubtitleFile(str(audio_file.path.parent / file_name))
elif format == "json":
return JsonFile(str(audio_file.path.parent / file_name))
# endregion
class File(object):
def __init__(self, path: str, auto_create_parent_dir=False):
"""
使用指定路径创建一个文件对象
Args:
path: 文件路径
auto_create_parent_dir: 是否自动创建父目录
"""
if not path:
raise IOError(f"路径{path}不是一个有效的路径")
self.path = PathlibPath(path)
if auto_create_parent_dir:
# 获取父目录
parent_dir = self.path.parent
# 创建父目录(如果不存在)
parent_dir.mkdir(parents=True, exist_ok=True)
def exists(self):
return self.path.exists()
def raise_for_not_exists(self):
if not self.exists():
raise IOError(f"文件{self.path}不存在")
def delete(self):
self.path.unlink()
def write_content(self, content: str):
"""
写入文本内容到该文件中
Args:
content: 文本内容
"""
with self.path.open("w", encoding="utf-8") as f:
f.write(content)
def read_content(self):
"""
读取文件内容
Returns:
文件内容
"""
with self.path.open("r", encoding="utf-8") as f:
return f.read()
def move_to(self, target_path: str) -> "File":
"""
移动文件到新路径
Args:
target_path: 目标路径
Returns:
新的文件对象
"""
shutil.move(str(self.path), str(target_path))
return File(str(target_path))
def rename(self, new_name: str) -> "File":
"""
重命名文件
Args:
new_name: 新名称
Returns:
File - 新的文件对象
"""
return File(str(self.path.rename(new_name)))
# 这里有个前向引用,所以用字符串, 参考https://poe.com/s/kxbWkhgiPORnv2D02LUJ
def copy_to(self, target: "str | Directory") -> "File":
"""
复制文件到新路径
Args:
target: 如果是字符串,则表示目标路径,如果是Directory对象,则表示目标目录
Returns:
新的文件对象
"""
if isinstance(target, Directory):
target_path = target.path / self.path.name
else:
target_path = PathlibPath(target)
shutil.copy2(str(self.path), str(target_path))
return File(str(target_path))
@property
def name(self):
return self.path.name
@property
def suffix(self):
return self.path.suffix
@property
def short_name(self):
return self.path.stem
@property
def last_modified(self):
"""
获取文件的最后修改时间
"""
# 获取文件的状态信息
file_stat = os.stat(self.path)
# 获取最后修改时间
modification_time = file_stat.st_mtime
# 将时间戳转换为 datetime 对象
modification_datetime = datetime.datetime.fromtimestamp(modification_time)
return modification_datetime
@property
def data_size(self):
return self.path.stat().st_size
# region 字幕文件
class SubtitleFile(File):
def __init__(self, path: str):
super().__init__(path)
class SrtSubtitleFile(SubtitleFile):
def __init__(self, path: str):
super().__init__(path)
# region ass字幕
class AssSubtitleFile(SubtitleFile):
def __init__(self, path: str):
super().__init__(path)
self.subs = pysubs2.load(path)
def set_info(self, info: [str, str]):
self.subs.info = info
def set_resolution(self, width: int, height: int):
"""
设置分辨率
Args:
width: 宽度
height: 高度
"""
self.subs.info["PlayResX"] = str(width)
self.subs.info["PlayResY"] = str(height)
self.subs.save(str(self.path))
def move_to(self, target_path: str) -> "AssSubtitleFile":
file = super().move_to(target_path)
return AssSubtitleFile(str(file.path.absolute()))
def copy_to(self, target: "str | Directory") -> "AssSubtitleFile":
file = super().copy_to(target)
return AssSubtitleFile(str(file.path.absolute()))
@property
def events(self):
return self.subs.events
@events.setter
def events(self, events: list[SSAEvent]):
"""
设定事件
Args:
events: 事件列表
"""
self.subs.events = events
@property
def styles(self):
"""
获取样式
Returns:
dict[str, pysubs2.SSAStyle]: 样式,键是样式名, 值是SSAStyle
"""
return self.subs.styles
@styles.setter
def styles(self, styles: dict[str, pysubs2.SSAStyle]):
"""
设定样式
Args:
styles: 样式
"""
self.subs.styles = styles
@property
def width(self):
"""
获取宽度
Returns:
int: 宽度
"""
return int(self.subs.info["PlayResX"])
@property
def height(self):
"""
获取高度
Returns:
int: 高度
"""
return int(self.subs.info["PlayResY"])
def create_style(self, style_name: str, **kwargs):
"""
创建样式
Args:
style_name: 样式名
**kwargs: 样式参数
"""
self.subs.styles[style_name] = pysubs2.SSAStyle(**kwargs)
self.subs.save(str(self.path))
def apply_style(
self, style_name: str, events_filter: callable = lambda event: True
):
"""
应用样式
Args:
style_name: 样式名
events_filter: 仅对符合条件的事件应用样式
"""
for event in self.subs.events:
if isinstance(event, pysubs2.SSAEvent) and events_filter(event):
event.style = style_name
self.subs.save(str(self.path))
def apply_style_by_index(self, index: int):
"""
应用样式
Args:
index: 样式索引
"""
style_name = list(self.subs.styles.keys())[index]
self.apply_style(style_name)
def set_max_width(
self,
max_width: int,
font_path: str,
font_size: int,
margin_left: int = 20,
margin_right: int = 20,
):
"""
设置最大宽度
Args:
max_width: 最大宽度
font_path: 字体路径
font_size: 字号
margin_left: 左边距
margin_right: 右边距
"""
new_events = []
for i, event in enumerate(self.subs.events):
lines = textwrap.wrap(event.text.strip(), width=max_width)
# region 固定位置
# line_start_y = self.height - (100+len(lines)*10)
# for line in lines:
# # new_events.append(
# # pysubs2.SSAEvent(start=event.start, end=event.end, style=event.style, name="", text=line))
# text_width, text_height = Text(line).calculate_text_width(font_path, font_size)
# pos_x = (self.width - text_width) // 2
# new_line = f"{{\\\\an1\\\\pos({pos_x},{line_start_y})}}" + line
# new_events.append(
# pysubs2.SSAEvent(start=event.start, end=event.end, style=event.style, name="", text=new_line))
# line_start_y += text_height+10
# endregion
# region 自动位置
new_line = r"\N\N".join(lines)
new_events.append(
pysubs2.SSAEvent(
start=event.start,
end=event.end,
style=event.style,
name="",
text=new_line,
)
)
# endregion
# new_events.append(
# pysubs2.SSAEvent(start=event.start, end=event.end, style=event.style, name="", text=new_line))
# for line in lines:
# text_width, text_height = Text(line).calculate_text_width( "resources/fonts/华文细黑.ttf", 36)
# pos_x = (1080 - text_width) // 2
# new_line = f"{{\\\\an1\\\\pos({pos_x},{line_start_y})}}" + line
# new_events.append(
# pysubs2.SSAEvent(start=event.start, end=event.end, style=event.style, name="", text=new_line))
# line_start_y += text_height
self.subs.events = new_events
self.subs.save(str(self.path))
# endregion
# endregion
# region 视频文件
class VideoFile(File):
def __init__(self, path: str = None):
super().__init__(path)
def extract_audio(self, audio_file_name: str = None) -> "AudioFile":
"""
提取视频的音频,然后放到视频文件的同级目录下
Args:
audio_file_name: 音频文件的名称,带后缀,比如"audio.mp3",如果没有指定,则默认为 "${视频文件名}.mp3"
Returns:
AudioFile: 音频文件对象
"""
video_file_name = self.path.name
if audio_file_name is None:
audio_file_name = f"{self.path.stem}.mp3"
audio_file_path = self.path.parent / audio_file_name
CommandLine.run(
f"ffmpeg -i {str(self.path.absolute())} -q:a 0 -map a {str(audio_file_path.absolute())}"
)
return AudioFile(str(audio_file_path))
@property
def volume(self):
"""
获取视频音量
"""
from pyext.ffmpeg import Ffmpeg
ffmpeg = Ffmpeg.from_env()
return ffmpeg.get_video_volume(self)
@property
def resolution(self):
"""
获取视频分辨率
Returns:
tuple[int, int]: 宽度, 高度
"""
result = CommandLine.run_and_get(
f'ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 "{self.path.absolute()}"'
)
width, height = result.stdout.strip().split("x")
return int(width), int(height)
def resize(self, new_width: int, new_height: int) -> "VideoFile":
"""
调整视频分辨率
Args:
new_width: 新宽度
new_height: 新高度
Returns:
VideoFile: 新的视频文件对象
"""
new_video_file = self.path.parent / f"{self.path.stem}-resized.mp4"
output = CommandLine.run_and_get(
f"""ffmpeg -i "{str(self.path.absolute())}" -vf scale={new_width}:{new_height} -c:a copy "{str(new_video_file.absolute())}" """
)
return VideoFile(str(new_video_file))
# endregion
# region 音频文件
class AudioFile(File):
def __init__(self, path: str):
super().__init__(path)
class Mp3File(AudioFile):
suffix = "mp3"
def __init__(self, path: str):
super().__init__(path)
# endregion
# region yaml文件
class YamlFile(File):
def __init__(self, path: str):
super().__init__(path)
def read_as_pydantic_model(self, model: Type[TPM]) -> TPM:
"""
读取文件内容并将其转换为 Pydantic 模型
Args:
model: Pydantic 模型类
Returns:
TPM: Pydantic 模型实例
"""
with open(self.path, "r", encoding="utf-8") as file:
yaml_data = yaml.safe_load(file)
# 将 YAML 数据转换为 Pydantic 类实例
return model(**yaml_data)
# endregion
# region Json文件
class JsonFile(File):
def __init__(self, path: str, auto_create_parent_dir=False):
super().__init__(path, auto_create_parent_dir)
def read_dict(self) -> dict[str, any]:
"""
读取文件内容并将其转换为字典对象
"""
with open(self.path, "r", encoding="utf-8") as file:
return json.load(file)
def write_dict(self, dict: dict[str, any]):
"""
将字典对象转换为json字符串并写入文件
"""
self.write_content(json.dumps(dict, indent=4, ensure_ascii=False))
def write_dataclass_json_obj(self, obj):
"""
对于使用了`@dataclass_json`的数据类对象,将其转换为json字符串并写入文件
"""
self.write_content(obj.to_json(indent=4, ensure_ascii=False))
def read_dataclass_json_obj(self, dataclass):
"""
读取文件内容并将其转换为数据类对象
"""
with open(self.path, "r", encoding="utf-8") as file:
return dataclass.from_json(file.read())
def write_pydanitc_model(self, model: TPM):
"""
将 Pydantic 模型写入文件
Args:
model: Pydantic 模型
"""
self.write_content(model.model_dump_json(indent=4, exclude_none=True))
def get_value_by_jsonpath(self, json_path):
"""
通过 JSON Path 获取值
Args:
json_path: JSON Path
Returns:
匹配到的值
"""
# 读取json为字典
# region 尝试移除BOM头
json_str = self.read_content()
if json_str.startswith("\ufeff"):
json_str = json_str[1:]
# endregion
data = json.loads(json_str)
# 解析 JSON Path
jsonpath_expr = parse(json_path)
# 查找匹配的位置
matches = jsonpath_expr.find(data)
# print(len(matches))
# 返回匹配到的值
if len(matches) > 0:
return matches[0].value
else:
return None
def set_value_by_jsonpath(self, json_path, new_value):
"""
通过 JSON Path 设置值
Args:
json_path: JSON Path
new_value: 新值
"""
# 读取json为字典
# region 尝试移除BOM头
json_str = self.read_content()
if json_str.startswith("\ufeff"):
json_str = json_str[1:]
# endregion
data = json.loads(json_str)
# 解析 JSON Path
jsonpath_expr = parse(json_path)
# 查找匹配的位置
new_data = jsonpath_expr.update(data, new_value)
# print(len(matches))
# # 修改匹配到的值
# for match in matches:
# match.value = new_value
# 写入文件
self.write_content(json.dumps(new_data, indent=4, ensure_ascii=False))
def read_as_addict(self):
"""
读取文件内容并将其转换为 Addict 对象
"""
with open(self.path, "r", encoding="utf-8") as file:
return Dict(json.load(file))
def read_as_pydanitc_model(
self, model: Type[TPM], additional_data: dict[str, any] = None
) -> TPM:
"""
读取文件内容并将其转换为 Pydantic 模型
Args:
model: Pydantic 模型
additional_data: 附加数据
Returns:
Pydantic 模型实例
Raises:
BusinessException: 读取文件内容失败时抛出异常
"""
with open(self.path, "r", encoding="utf-8") as file:
try:
dict = self.read_as_addict()
if additional_data:
dict.update(additional_data)
return model(**dict)
except Exception as e:
raise parse_exceptions(e)
# endregion
# region 目录
class Directory(object):
def __init__(self, path: str, auto_create=True):
"""
创建一个位于指定路径上的目录对象
Args:
path: 目录路径
auto_create: 是否自动创建目录,默认为True
"""
if not path:
raise IOError(f"路径{path}不是一个有效的路径")
self.path = PathlibPath(path)
if auto_create and not self.path.exists():
self.path.mkdir(parents=True)
if not self.path.is_dir():
raise ValueError(f"路径 {path} 不是一个目录")
def has_sibling(self, name: str):
"""
检查这个目录所在的同级目录中是否存在指定名称的目录
Args:
name: 要检查的目录名称
Returns:
bool - 如果存在指定名称的目录,则返回 True,否则返回 False。
Examples:
假设有如下目录结构:
```markdown
📦resources
┣ 📂fonts
┣ 📂font_presets
┗ 📂prompts
```
>>> dir = Directory("resources")
>>> dir.has_sibling("prompts")
True
"""
return self.path.parent.joinpath(name).exists()
def copy_to_sibling(self, name: str):
"""
将这个目录复制为同级目录
Args:
name: 新目录的名称
Returns:
Directory - 新目录对象
"""
npath = shutil.copytree(self.path, self.path.parent / name)
return Directory(str(npath))
@property
def absolute_path(self):
"""
获取这个目录的绝对路径
"""
return str(self.path.absolute())
@property
def last_modified(self):
"""
获取文件的最后修改时间
"""
# 获取文件的状态信息
file_stat = os.stat(self.path)
# 获取最后修改时间
modification_time = file_stat.st_mtime
# 将时间戳转换为 datetime 对象
modification_datetime = datetime.datetime.fromtimestamp(modification_time)
return modification_datetime
@property
def name(self):
"""
获取这个目录的名称
"""
return self.path.name
# region 删除目录
def delete(self):
"""
删除目录
"""
shutil.rmtree(self.path)
# endregion
# region 根据文件名查找文件
def find_file(self, file_name: str) -> File:
"""
在目录下查找指定文件
Args:
file_name: 文件名
Returns:
如果找到,则返回文件对象,否则返回None
"""
for file in self.list_files():
if file.name == file_name:
return File(str(file))
# endregion
def new_file(self, file_name: str) -> TF:
"""
创建一个新文件
Args:
file_name: 文件名