-
Notifications
You must be signed in to change notification settings - Fork 0
/
odt2nw.py
2397 lines (1998 loc) · 81.6 KB
/
odt2nw.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/python3
"""Convert ODT to novelWriter
Version 0.1.1
Requires Python 3.6+
Copyright (c) 2023 Peter Triesberger
For further information see https://github.com/peter88213/odt2nw
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
import argparse
import os
import sys
import gettext
import locale
__all__ = ['Error',
'_',
'LOCALE_PATH',
'CURRENT_LANGUAGE',
'norm_path',
'string_to_list',
'list_to_string',
]
class Error(Exception):
pass
LOCALE_PATH = f'{os.path.dirname(sys.argv[0])}/locale/'
try:
CURRENT_LANGUAGE = locale.getlocale()[0][:2]
except:
CURRENT_LANGUAGE = locale.getdefaultlocale()[0][:2]
try:
t = gettext.translation('pywriter', LOCALE_PATH, languages=[CURRENT_LANGUAGE])
_ = t.gettext
except:
def _(message):
return message
def norm_path(path):
if path is None:
path = ''
return os.path.normpath(path)
def string_to_list(text, divider=';'):
elements = []
try:
tempList = text.split(divider)
for element in tempList:
element = element.strip()
if element and not element in elements:
elements.append(element)
return elements
except:
return []
def list_to_string(elements, divider=';'):
try:
text = divider.join(elements)
return text
except:
return ''
class Ui:
def __init__(self, title):
self.infoWhatText = ''
self.infoHowText = ''
def ask_yes_no(self, text):
return True
def set_info_how(self, message):
if message.startswith('!'):
message = f'FAIL: {message.split("!", maxsplit=1)[1].strip()}'
sys.stderr.write(message)
self.infoHowText = message
def set_info_what(self, message):
self.infoWhatText = message
def show_warning(self, message):
pass
def start(self):
pass
class UiCmd(Ui):
def __init__(self, title):
super().__init__(title)
print(title)
def ask_yes_no(self, text):
result = input(f'{_("WARNING")}: {text} (y/n)')
if result.lower() == 'y':
return True
else:
return False
def set_info_how(self, message):
if message.startswith('!'):
message = f'FAIL: {message.split("!", maxsplit=1)[1].strip()}'
self.infoHowText = message
print(message)
def set_info_what(self, message):
print(message)
def show_warning(self, message):
print(f'\nWARNING: {message}\n')
def open_document(document):
try:
os.startfile(norm_path(document))
except:
try:
os.system('xdg-open "%s"' % norm_path(document))
except:
try:
os.system('open "%s"' % norm_path(document))
except:
pass
import re
from typing import Iterator, Pattern
class BasicElement:
def __init__(self):
self.title: str = None
self.desc: str = None
self.kwVar: dict[str, str] = {}
class Chapter(BasicElement):
def __init__(self):
super().__init__()
self.chLevel: int = None
self.chType: int = None
self.suppressChapterTitle: bool = None
self.isTrash: bool = None
self.suppressChapterBreak: bool = None
self.srtScenes: list[str] = []
from typing import Pattern
ADDITIONAL_WORD_LIMITS: Pattern = re.compile('--|—|–')
NO_WORD_LIMITS: Pattern = re.compile('\[.+?\]|\/\*.+?\*\/|-|^\>', re.MULTILINE)
NON_LETTERS: Pattern = re.compile('\[.+?\]|\/\*.+?\*\/|\n|\r')
class Scene(BasicElement):
STATUS: set = (None, 'Outline', 'Draft', '1st Edit', '2nd Edit', 'Done')
ACTION_MARKER: str = 'A'
REACTION_MARKER: str = 'R'
NULL_DATE: str = '0001-01-01'
NULL_TIME: str = '00:00:00'
def __init__(self):
super().__init__()
self._sceneContent: str = None
self.wordCount: int = 0
self.letterCount: int = 0
self.scType: int = None
self.doNotExport: bool = None
self.status: int = None
self.notes: str = None
self.tags: list[str] = None
self.field1: str = None
self.field2: str = None
self.field3: str = None
self.field4: str = None
self.appendToPrev: bool = None
self.isReactionScene: bool = None
self.isSubPlot: bool = None
self.goal: str = None
self.conflict: str = None
self.outcome: str = None
self.characters: list[str] = None
self.locations: list[str] = None
self.items: list[str] = None
self.date: str = None
self.time: str = None
self.day: str = None
self.lastsMinutes: str = None
self.lastsHours: str = None
self.lastsDays: str = None
self.image: str = None
self.scnArcs: str = None
self.scnStyle: str = None
@property
def sceneContent(self) -> str:
return self._sceneContent
@sceneContent.setter
def sceneContent(self, text: str):
self._sceneContent = text
text = ADDITIONAL_WORD_LIMITS.sub(' ', text)
text = NO_WORD_LIMITS.sub('', text)
wordList = text.split()
self.wordCount = len(wordList)
text = NON_LETTERS.sub('', self._sceneContent)
self.letterCount = len(text)
class WorldElement(BasicElement):
def __init__(self):
super().__init__()
self.image: str = None
self.tags: list[str] = None
self.aka: str = None
class Character(WorldElement):
MAJOR_MARKER: str = 'Major'
MINOR_MARKER: str = 'Minor'
def __init__(self):
super().__init__()
self.notes: str = None
self.bio: str = None
self.goals: str = None
self.fullName: str = None
self.isMajor: bool = None
LANGUAGE_TAG: Pattern = re.compile('\[lang=(.*?)\]')
class Novel(BasicElement):
def __init__(self):
super().__init__()
self.authorName: str = None
self.authorBio: str = None
self.fieldTitle1: str = None
self.fieldTitle2: str = None
self.fieldTitle3: str = None
self.fieldTitle4: str = None
self.wordTarget: int = None
self.wordCountStart: int = None
self.wordTarget: int = None
self.chapters: dict[str, Chapter] = {}
self.scenes: dict[str, Scene] = {}
self.languages: list[str] = None
self.srtChapters: list[str] = []
self.locations: dict[str, WorldElement] = {}
self.srtLocations: list[str] = []
self.items: dict[str, WorldElement] = {}
self.srtItems: list[str] = []
self.characters: dict[str, Character] = {}
self.srtCharacters: list[str] = []
self.projectNotes: dict[str, BasicElement] = {}
self.srtPrjNotes: list[str] = []
self.languageCode: str = None
self.countryCode: str = None
def get_languages(self):
def languages(text: str) -> Iterator[str]:
if text:
m = LANGUAGE_TAG.search(text)
while m:
text = text[m.span()[1]:]
yield m.group(1)
m = LANGUAGE_TAG.search(text)
self.languages = []
for scId in self.scenes:
text = self.scenes[scId].sceneContent
if text:
for language in languages(text):
if not language in self.languages:
self.languages.append(language)
def check_locale(self):
if not self.languageCode:
try:
sysLng, sysCtr = locale.getlocale()[0].split('_')
except:
sysLng, sysCtr = locale.getdefaultlocale()[0].split('_')
self.languageCode = sysLng
self.countryCode = sysCtr
return
try:
if len(self.languageCode) == 2:
if len(self.countryCode) == 2:
return
except:
pass
self.languageCode = 'zxx'
self.countryCode = 'none'
class YwCnvUi:
def __init__(self):
self.ui = Ui('')
self.newFile = None
def export_from_yw(self, source, target):
self.ui.set_info_what(
_('Input: {0} "{1}"\nOutput: {2} "{3}"').format(source.DESCRIPTION, norm_path(source.filePath), target.DESCRIPTION, norm_path(target.filePath)))
try:
self.check(source, target)
source.novel = Novel()
source.read()
target.novel = source.novel
target.write()
except Exception as ex:
message = f'!{str(ex)}'
self.newFile = None
else:
message = f'{_("File written")}: "{norm_path(target.filePath)}".'
self.newFile = target.filePath
finally:
self.ui.set_info_how(message)
def create_yw7(self, source, target):
self.ui.set_info_what(
_('Create a yWriter project file from {0}\nNew project: "{1}"').format(source.DESCRIPTION, norm_path(target.filePath)))
if os.path.isfile(target.filePath):
self.ui.set_info_how(f'!{_("File already exists")}: "{norm_path(target.filePath)}".')
else:
try:
self.check(source, target)
source.novel = Novel()
source.read()
target.novel = source.novel
target.write()
except Exception as ex:
message = f'!{str(ex)}'
self.newFile = None
else:
message = f'{_("File written")}: "{norm_path(target.filePath)}".'
self.newFile = target.filePath
finally:
self.ui.set_info_how(message)
def import_to_yw(self, source, target):
self.ui.set_info_what(
_('Input: {0} "{1}"\nOutput: {2} "{3}"').format(source.DESCRIPTION, norm_path(source.filePath), target.DESCRIPTION, norm_path(target.filePath)))
self.newFile = None
try:
self.check(source, target)
target.novel = Novel()
target.read()
source.novel = target.novel
source.read()
target.novel = source.novel
target.write()
except Exception as ex:
message = f'!{str(ex)}'
else:
message = f'{_("File written")}: "{norm_path(target.filePath)}".'
self.newFile = target.filePath
if source.scenesSplit:
self.ui.show_warning(_('New scenes created during conversion.'))
finally:
self.ui.set_info_how(message)
def _confirm_overwrite(self, filePath):
return self.ui.ask_yes_no(_('Overwrite existing file "{}"?').format(norm_path(filePath)))
def _open_newFile(self):
open_document(self.newFile)
sys.exit(0)
def check(self, source, target):
if source.filePath is None:
raise Error(f'{_("File type is not supported")}.')
if not os.path.isfile(source.filePath):
raise Error(f'{_("File not found")}: "{norm_path(source.filePath)}".')
if target.filePath is None:
raise Error(f'{_("File type is not supported")}.')
if os.path.isfile(target.filePath) and not self._confirm_overwrite(target.filePath):
raise Error(f'{_("Action canceled by user")}.')
from urllib.parse import quote
class File:
DESCRIPTION = _('File')
EXTENSION = None
SUFFIX = None
PRJ_KWVAR = []
CHP_KWVAR = []
SCN_KWVAR = []
CRT_KWVAR = []
LOC_KWVAR = []
ITM_KWVAR = []
PNT_KWVAR = []
def __init__(self, filePath, **kwargs):
super().__init__()
self.novel = None
self._filePath = None
self.projectName = None
self.projectPath = None
self.scenesSplit = False
self.filePath = filePath
@property
def filePath(self):
return self._filePath
@filePath.setter
def filePath(self, filePath):
if self.SUFFIX is not None:
suffix = self.SUFFIX
else:
suffix = ''
if filePath.lower().endswith(f'{suffix}{self.EXTENSION}'.lower()):
self._filePath = filePath
try:
head, tail = os.path.split(os.path.realpath(filePath))
except:
head, tail = os.path.split(filePath)
self.projectPath = quote(head.replace('\\', '/'), '/:')
self.projectName = quote(tail.replace(f'{suffix}{self.EXTENSION}', ''))
def read(self):
raise NotImplementedError
def write(self):
raise NotImplementedError
def _convert_from_yw(self, text, quick=False):
return text.rstrip()
def _convert_to_yw(self, text):
return text.rstrip()
import zipfile
from xml import sax
import xml.etree.ElementTree as ET
class OdtParser(sax.ContentHandler):
def __init__(self):
super().__init__()
self._emTags = ['Emphasis']
self._strongTags = ['Strong_20_Emphasis']
self._blockquoteTags = ['Quotations']
self._languageTags = {}
self._headingTags = {}
self._heading = None
self._paragraph = False
self._commentParagraphCount = None
self._blockquote = False
self._list = False
self._span = []
self._style = None
def feed_file(self, filePath):
namespaces = dict(
office='urn:oasis:names:tc:opendocument:xmlns:office:1.0',
style='urn:oasis:names:tc:opendocument:xmlns:style:1.0',
fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
dc='http://purl.org/dc/elements/1.1/',
meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0'
)
try:
with zipfile.ZipFile(filePath, 'r') as odfFile:
content = odfFile.read('content.xml')
styles = odfFile.read('styles.xml')
try:
meta = odfFile.read('meta.xml')
except KeyError:
meta = None
except:
raise Error(f'{_("Cannot read file")}: "{norm_path(filePath)}".')
root = ET.fromstring(styles)
styles = root.find('office:styles', namespaces)
for defaultStyle in styles.findall('style:default-style', namespaces):
if defaultStyle.get(f'{{{namespaces["style"]}}}family') == 'paragraph':
textProperties = defaultStyle.find('style:text-properties', namespaces)
lngCode = textProperties.get(f'{{{namespaces["fo"]}}}language')
ctrCode = textProperties.get(f'{{{namespaces["fo"]}}}country')
self.handle_starttag('body', [('language', lngCode), ('country', ctrCode)])
break
if meta:
root = ET.fromstring(meta)
meta = root.find('office:meta', namespaces)
title = meta.find('dc:title', namespaces)
if title is not None:
if title.text:
self.handle_starttag('title', [()])
self.handle_data(title.text)
self.handle_endtag('title')
author = meta.find('meta:initial-creator', namespaces)
if author is not None:
if author.text:
self.handle_starttag('meta', [('', 'author'), ('', author.text)])
desc = meta.find('dc:description', namespaces)
if desc is not None:
if desc.text:
self.handle_starttag('meta', [('', 'description'), ('', desc.text)])
sax.parseString(content, self)
def characters(self, content):
if self._commentParagraphCount is not None:
if self._commentParagraphCount == 1:
self._comment = f'{self._comment}{content}'
elif self._paragraph:
self.handle_data(content)
elif self._heading is not None:
self.handle_data(content)
def endElement(self, name):
if name == 'text:p':
if self._commentParagraphCount is None:
while self._span:
self.handle_endtag(self._span.pop())
if self._blockquote:
self.handle_endtag('blockquote')
self._blockquote = False
elif self._heading:
self.handle_endtag(self._heading)
self._heading = None
else:
self.handle_endtag('p')
self._paragraph = False
elif name == 'text:span':
if self._span:
self.handle_endtag(self._span.pop())
elif name == 'text:section':
self.handle_endtag('div')
elif name == 'office:annotation':
self.handle_comment(self._comment)
self._commentParagraphCount = None
elif name == 'text:h':
self.handle_endtag(self._heading)
self._heading = None
elif name == 'text:list-item':
self._list = False
elif name == 'style:style':
self._style = None
def startElement(self, name, attrs):
xmlAttributes = {}
for attribute in attrs.items():
attrKey, attrValue = attribute
xmlAttributes[attrKey] = attrValue
style = xmlAttributes.get('text:style-name', '')
if name == 'text:p':
param = [()]
if style in self._languageTags:
param = [('lang', self._languageTags[style])]
if self._commentParagraphCount is not None:
self._commentParagraphCount += 1
elif style in self._blockquoteTags:
self.handle_starttag('blockquote', param)
self._paragraph = True
self._blockquote = True
elif style.startswith('Heading'):
self._heading = f'h{style[-1]}'
self.handle_starttag(self._heading, [()])
elif style in self._headingTags:
self._heading = self._headingTags[style]
self.handle_starttag(self._heading, [()])
elif self._list:
self.handle_starttag('li', [()])
self._paragraph = True
else:
self.handle_starttag('p', param)
self._paragraph = True
if style in self._emTags:
self._span.append('em')
self.handle_starttag('em', [()])
if style in self._strongTags:
self._span.append('strong')
self.handle_starttag('strong', [()])
elif name == 'text:span':
if style in self._emTags:
self._span.append('em')
self.handle_starttag('em', [()])
if style in self._strongTags:
self._span.append('strong')
self.handle_starttag('strong', [()])
if style in self._languageTags:
self._span.append('lang')
self.handle_starttag('lang', [('lang', self._languageTags[style])])
elif name == 'text:section':
sectionId = xmlAttributes['text:name']
self.handle_starttag('div', [('id', sectionId)])
elif name == 'office:annotation':
self._commentParagraphCount = 0
self._comment = ''
elif name == 'text:h':
try:
self._heading = f'h{xmlAttributes["text:outline-level"]}'
except:
self._heading = f'h{style[-1]}'
self.handle_starttag(self._heading, [()])
elif name == 'text:list-item':
self._list = True
elif name == 'style:style':
self._style = xmlAttributes.get('style:name', None)
styleName = xmlAttributes.get('style:parent-style-name', '')
if styleName.startswith('Heading'):
self._headingTags[self._style] = f'h{styleName[-1]}'
elif styleName == 'Quotations':
self._blockquoteTags.append(self._style)
elif name == 'style:text-properties':
if xmlAttributes.get('fo:font-style', None) == 'italic':
self._emTags.append(self._style)
if xmlAttributes.get('fo:font-weight', None) == 'bold':
self._strongTags.append(self._style)
if xmlAttributes.get('fo:language', False):
lngCode = xmlAttributes['fo:language']
ctrCode = xmlAttributes['fo:country']
if ctrCode != 'none':
locale = f'{lngCode}-{ctrCode}'
else:
locale = lngCode
self._languageTags[self._style] = locale
elif name == 'text:s':
self.handle_starttag('s', [()])
def handle_comment(self, data):
pass
def handle_data(self, data):
pass
def handle_endtag(self, tag):
pass
def handle_starttag(self, tag, attrs):
pass
class OdtReader(File, OdtParser):
EXTENSION = '.odt'
_TYPE = 0
_COMMENT_START = '/*'
_COMMENT_END = '*/'
_SC_TITLE_BRACKET = '~'
_BULLET = '-'
_INDENT = '>'
def __init__(self, filePath, **kwargs):
super().__init__(filePath)
self._lines = []
self._scId = None
self._chId = None
self._newline = False
self._language = ''
self._skip_data = False
def handle_comment(self, data):
if self._scId is not None:
self._lines.append(f'{self._COMMENT_START}{data}{self._COMMENT_END}')
def handle_starttag(self, tag, attrs):
if tag == 'div':
if attrs[0][0] == 'id':
if attrs[0][1].startswith('ScID'):
self._scId = re.search('[0-9]+', attrs[0][1]).group()
if not self._scId in self.novel.scenes:
self.novel.scenes[self._scId] = Scene()
self.novel.chapters[self._chId].srtScenes.append(self._scId)
self.novel.scenes[self._scId].scType = self._TYPE
elif attrs[0][1].startswith('ChID'):
self._chId = re.search('[0-9]+', attrs[0][1]).group()
if not self._chId in self.novel.chapters:
self.novel.chapters[self._chId] = Chapter()
self.novel.chapters[self._chId].srtScenes = []
self.novel.srtChapters.append(self._chId)
self.novel.chapters[self._chId].chType = self._TYPE
elif tag == 's':
self._lines.append(' ')
def read(self):
OdtParser.feed_file(self, self.filePath)
def _convert_to_yw(self, text):
text = text.replace('\n', ' ')
text = text.replace('\r', ' ')
text = text.replace('\t', ' ')
while ' ' in text:
text = text.replace(' ', ' ')
return text
class Splitter:
PART_SEPARATOR: str = '#'
CHAPTER_SEPARATOR: str = '##'
SCENE_SEPARATOR: str = '###'
DESC_SEPARATOR: str = '|'
_CLIP_TITLE: int = 20
def split_scenes(self, file):
def create_chapter(chapterId: str, title: str, desc: str, level: int):
newChapter = Chapter()
newChapter.title = title
newChapter.desc = desc
newChapter.chLevel = level
newChapter.chType = 0
file.novel.chapters[chapterId] = newChapter
def create_scene(sceneId: str, parent: str, splitCount: int, title: str, desc: str):
WARNING: str = '(!)'
newScene = Scene()
if title:
newScene.title = title
elif parent.title:
if len(parent.title) > self._CLIP_TITLE:
title = f'{parent.title[:self._CLIP_TITLE]}...'
else:
title = parent.title
newScene.title = f'{title} Split: {splitCount}'
else:
newScene.title = f'{_("New Scene")} Split: {splitCount}'
if desc:
newScene.desc = desc
if parent.desc and not parent.desc.startswith(WARNING):
parent.desc = f'{WARNING}{parent.desc}'
if parent.goal and not parent.goal.startswith(WARNING):
parent.goal = f'{WARNING}{parent.goal}'
if parent.conflict and not parent.conflict.startswith(WARNING):
parent.conflict = f'{WARNING}{parent.conflict}'
if parent.outcome and not parent.outcome.startswith(WARNING):
parent.outcome = f'{WARNING}{parent.outcome}'
if parent.status > 2:
parent.status = 2
newScene.status = parent.status
newScene.scType = parent.scType
newScene.date = parent.date
newScene.time = parent.time
newScene.day = parent.day
newScene.lastsDays = parent.lastsDays
newScene.lastsHours = parent.lastsHours
newScene.lastsMinutes = parent.lastsMinutes
file.novel.scenes[sceneId] = newScene
chIdMax = 0
scIdMax = 0
for chId in file.novel.srtChapters:
if int(chId) > chIdMax:
chIdMax = int(chId)
for scId in file.novel.scenes:
if int(scId) > scIdMax:
scIdMax = int(scId)
scenesSplit = False
srtChapters = []
for chId in file.novel.srtChapters:
srtChapters.append(chId)
chapterId = chId
srtScenes = []
for scId in file.novel.chapters[chId].srtScenes:
srtScenes.append(scId)
if not file.novel.scenes[scId].sceneContent:
continue
sceneId = scId
lines = file.novel.scenes[scId].sceneContent.split('\n')
newLines = []
inScene = True
sceneSplitCount = 0
for line in lines:
heading = line.strip('# ').split(self.DESC_SEPARATOR)
title = heading[0]
try:
desc = heading[1]
except:
desc = ''
if line.startswith(self.SCENE_SEPARATOR):
file.novel.scenes[sceneId].sceneContent = '\n'.join(newLines)
newLines = []
sceneSplitCount += 1
scIdMax += 1
sceneId = str(scIdMax)
create_scene(sceneId, file.novel.scenes[scId], sceneSplitCount, title, desc)
srtScenes.append(sceneId)
scenesSplit = True
inScene = True
elif line.startswith(self.CHAPTER_SEPARATOR):
if inScene:
file.novel.scenes[sceneId].sceneContent = '\n'.join(newLines)
newLines = []
sceneSplitCount = 0
inScene = False
file.novel.chapters[chapterId].srtScenes = srtScenes
srtScenes = []
chIdMax += 1
chapterId = str(chIdMax)
if not title:
title = _('New Chapter')
create_chapter(chapterId, title, desc, 0)
srtChapters.append(chapterId)
scenesSplit = True
elif line.startswith(self.PART_SEPARATOR):
if inScene:
file.novel.scenes[sceneId].sceneContent = '\n'.join(newLines)
newLines = []
sceneSplitCount = 0
inScene = False
file.novel.chapters[chapterId].srtScenes = srtScenes
srtScenes = []
chIdMax += 1
chapterId = str(chIdMax)
if not title:
title = _('New Part')
create_chapter(chapterId, title, desc, 1)
srtChapters.append(chapterId)
elif not inScene:
newLines.append(line)
sceneSplitCount += 1
scIdMax += 1
sceneId = str(scIdMax)
create_scene(sceneId, file.novel.scenes[scId], sceneSplitCount, '', '')
srtScenes.append(sceneId)
scenesSplit = True
inScene = True
else:
newLines.append(line)
file.novel.scenes[sceneId].sceneContent = '\n'.join(newLines)
file.novel.chapters[chapterId].srtScenes = srtScenes
file.novel.srtChapters = srtChapters
return scenesSplit
class OdtRFormatted(OdtReader):
_COMMENT_START = '/*'
_COMMENT_END = '*/'
_SC_TITLE_BRACKET = '~'
_BULLET = '-'
_INDENT = '>'
def read(self):
self.novel.languages = []
super().read()
sceneSplitter = Splitter()
self.scenesSplit = sceneSplitter.split_scenes(self)
def _cleanup_scene(self, text):
tags = ['i', 'b']
for language in self.novel.languages:
tags.append(f'lang={language}')
for tag in tags:
text = text.replace(f'[/{tag}][{tag}]', '')
text = text.replace(f'[/{tag}]\n[{tag}]', '\n')
text = text.replace(f'[/{tag}]\n> [{tag}]', '\n> ')
return text
class OdtRImport(OdtRFormatted):
DESCRIPTION = _('Work in progress')
SUFFIX = ''
_SCENE_DIVIDER = '* * *'
_LOW_WORDCOUNT = 10
def __init__(self, filePath, **kwargs):
super().__init__(filePath)
self._chCount = 0
self._scCount = 0
def handle_comment(self, data):
if self._scId is not None:
if not self._lines:
try:
self.novel.scenes[self._scId].title = data.strip()
except:
pass
return
self._lines.append(f'{self._COMMENT_START}{data.strip()}{self._COMMENT_END}')
def handle_data(self, data):
if self._scId is not None and self._SCENE_DIVIDER in data:
self._scId = None
else:
self._lines.append(data)
def handle_endtag(self, tag):
if tag in ('p', 'blockquote'):
if self._language:
self._lines.append(f'[/lang={self._language}]')
self._language = ''
self._lines.append('\n')
if self._scId is not None:
sceneText = ''.join(self._lines).rstrip()