doc2tei-CERTIC 0.0.99__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. doc2tei/__init__.py +628 -0
  2. doc2tei/__main__.py +58 -0
  3. doc2tei/resources/saxon9.jar +0 -0
  4. doc2tei/resources/schema/metopes.rng +8914 -0
  5. doc2tei/resources/schema/openedition.rng +4204 -0
  6. doc2tei/resources/xsl-01-cleanup/.gitkeep +0 -0
  7. doc2tei/resources/xsl-01-cleanup/cleanup-delete.xsl +88 -0
  8. doc2tei/resources/xsl-01-cleanup/cleanup-nodes.xsl +166 -0
  9. doc2tei/resources/xsl-01-cleanup/cleanup-preserve.xsl +99 -0
  10. doc2tei/resources/xsl-01-cleanup/cleanup-styles.xsl +487 -0
  11. doc2tei/resources/xsl-01-cleanup/cleanup.xsl +71 -0
  12. doc2tei/resources/xsl-02-normalisation/a-normalize-stylename.xsl +77 -0
  13. doc2tei/resources/xsl-02-normalisation/b-normalize-nodes-cit.xsl +171 -0
  14. doc2tei/resources/xsl-02-normalisation/b-normalize-nodes-index.xsl +185 -0
  15. doc2tei/resources/xsl-02-normalisation/b-normalize-nodes.xsl +131 -0
  16. doc2tei/resources/xsl-02-normalisation/c-normalize-groupspan.xsl +89 -0
  17. doc2tei/resources/xsl-03-enrich/enrich.xsl +79 -0
  18. doc2tei/resources/xsl-04-group/group-cit.xsl +97 -0
  19. doc2tei/resources/xsl-04-group/group-figure-grp.xsl +76 -0
  20. doc2tei/resources/xsl-04-group/group-figure.xsl +96 -0
  21. doc2tei/resources/xsl-04-group/group-floatingText.xsl +86 -0
  22. doc2tei/resources/xsl-04-group/group-review.xsl +78 -0
  23. doc2tei/resources/xsl-04-group/group-sp.xsl +84 -0
  24. doc2tei/resources/xsl-04-group/hierarchize-floatingText.xsl +93 -0
  25. doc2tei/resources/xsl-04-group/hierarchize-review.xsl +122 -0
  26. doc2tei/resources/xsl-05-control/control-errors.xsl +57 -0
  27. doc2tei/resources/xsl-05-control/control-hierarchy.xsl +97 -0
  28. doc2tei/resources/xsl-05-control/control-styles-id.xsl +209 -0
  29. doc2tei/resources/xsl-06-hierarchize/hierarchize.xsl +111 -0
  30. doc2tei/resources/xsl-07-organise/organise.xsl +175 -0
  31. doc2tei/resources/xsl-08-totei/back.xsl +85 -0
  32. doc2tei/resources/xsl-08-totei/core_cit.xsl +334 -0
  33. doc2tei/resources/xsl-08-totei/core_code.xsl +85 -0
  34. doc2tei/resources/xsl-08-totei/core_div-para.xsl +234 -0
  35. doc2tei/resources/xsl-08-totei/core_figure.xsl +325 -0
  36. doc2tei/resources/xsl-08-totei/core_linking.xsl +94 -0
  37. doc2tei/resources/xsl-08-totei/core_list.xsl +90 -0
  38. doc2tei/resources/xsl-08-totei/core_note.xsl +78 -0
  39. doc2tei/resources/xsl-08-totei/core_typo.xsl +74 -0
  40. doc2tei/resources/xsl-08-totei/front.xsl +269 -0
  41. doc2tei/resources/xsl-08-totei/teiHeader.xsl +668 -0
  42. doc2tei/resources/xsl-08-totei/totei.xsl +81 -0
  43. doc2tei/resources/xsl-09-toOpenedition/toOpenedition.xsl +315 -0
  44. doc2tei_certic-0.0.99.dist-info/METADATA +43 -0
  45. doc2tei_certic-0.0.99.dist-info/RECORD +47 -0
  46. doc2tei_certic-0.0.99.dist-info/WHEEL +4 -0
  47. doc2tei_certic-0.0.99.dist-info/entry_points.txt +3 -0
doc2tei/__init__.py ADDED
@@ -0,0 +1,628 @@
1
+ import logging
2
+ import re
3
+ import fnmatch
4
+ from typing import List, Tuple
5
+ import os
6
+ import os.path
7
+ import sys
8
+ from subprocess import Popen, PIPE
9
+ import shutil
10
+ from xml.etree import ElementTree as ET
11
+ import glob
12
+ import base64
13
+ from typing import Union
14
+
15
+ SOFFICE_PATH = shutil.which("soffice")
16
+ JAVA_PATH = shutil.which("java")
17
+ RESOURCES_PATH = os.path.dirname(os.path.abspath(__file__)) + "/resources/"
18
+ SAXON_PATH = os.getenv("SAXON_PATH") or (RESOURCES_PATH + "saxon9.jar")
19
+ XMLLINT_PATH = shutil.which("xmllint")
20
+
21
+ if not SOFFICE_PATH:
22
+ sys.exit("Could not find soffice. Is it in your PATH ?")
23
+ if not JAVA_PATH:
24
+ sys.exit("Could not find java. Is it in your PATH ?")
25
+ if not SAXON_PATH:
26
+ sys.exit(
27
+ "Could not find the Saxon jar. Please set SAXON_PATH environment variable."
28
+ )
29
+ if not os.path.isfile(SAXON_PATH):
30
+ sys.exit(
31
+ "Could not find the Saxon jar. Please check your SAXON_PATH environment variable."
32
+ )
33
+ if not XMLLINT_PATH:
34
+ sys.exit("Could not find xmllint. Is it in your PATH ?")
35
+
36
+
37
+ def _silent_remove(path: str):
38
+ try:
39
+ os.remove(path)
40
+ except FileNotFoundError:
41
+ pass
42
+
43
+
44
+ def _union_java_output(std_out: bytes, std_err: bytes) -> Union[bytes, str]:
45
+ """
46
+ Java outputs errors to STDOUT ???
47
+ """
48
+ if std_err:
49
+ try:
50
+ out = std_err.decode("utf-8")
51
+ out = out.strip()
52
+ if out:
53
+ return out
54
+ except UnicodeDecodeError:
55
+ return std_err
56
+ if std_out:
57
+ try:
58
+ out = std_out.decode("utf-8")
59
+ out = out.strip()
60
+ if out:
61
+ return out
62
+ except UnicodeDecodeError:
63
+ return std_out
64
+ return "subprocess provided no error output"
65
+
66
+
67
+ def _find_files(what: str, where: str = ".") -> List[str]:
68
+ rule = re.compile(fnmatch.translate(what), re.IGNORECASE)
69
+ return [
70
+ "{}{}{}".format(where, os.path.sep, name)
71
+ for name in os.listdir(where)
72
+ if rule.match(name)
73
+ ]
74
+
75
+
76
+ def _cli_exec(cli_args: list, logger: logging.Logger) -> Tuple[int, bytes, bytes]:
77
+ logger.debug(" ".join(cli_args))
78
+ p = Popen(
79
+ cli_args,
80
+ stdout=PIPE,
81
+ stderr=PIPE,
82
+ )
83
+ out, err = p.communicate()
84
+ err_code = p.returncode
85
+ p.terminate()
86
+ return err_code, out, err
87
+
88
+
89
+ def _clean_transient_files(transient_files: list, keep_them: bool = False):
90
+ if not keep_them:
91
+ for transient_file_path in transient_files:
92
+ _silent_remove(transient_file_path)
93
+
94
+
95
+ def _check_validation_schema(schema_name: str, logger: logging.Logger) -> str:
96
+ valid_validation_schemas = ["metopes", "openedition"]
97
+ if schema_name not in valid_validation_schemas:
98
+ logger.warning(
99
+ f"{schema_name} validation schema not available. Forcing metopes validation schema."
100
+ )
101
+ return "metopes"
102
+ return schema_name
103
+
104
+
105
+ def _log_xml_error(saxon_output: bytes, logger: logging.Logger) -> bool:
106
+ has_fatal = False
107
+ control_xml = ET.fromstring(saxon_output.decode("utf-8"))
108
+ for error_node in control_xml.findall(".//{*}ERROR"):
109
+ logger.error(error_node.text)
110
+ has_fatal = True
111
+ return has_fatal
112
+
113
+
114
+ def _log_xml_warning(saxon_output: bytes, logger: logging.Logger) -> bool:
115
+ has_error = False
116
+ control_xml = ET.fromstring(saxon_output.decode("utf-8"))
117
+ for error_node in control_xml.findall(".//{*}WARNING"):
118
+ logger.warning(error_node.text)
119
+ has_error = True
120
+ return has_error
121
+
122
+
123
+ def _write_binary_to_file(
124
+ file_path: str, content: bytes, logger: logging.Logger
125
+ ) -> bool:
126
+ with open(file_path, "wb") as f:
127
+ f.write(content)
128
+ logger.debug("Wrote {}".format(os.path.basename(file_path)))
129
+ return True
130
+
131
+
132
+ def _call_saxon(
133
+ xsl_path: str,
134
+ source_path: str,
135
+ destination_path: str,
136
+ logger: logging.Logger,
137
+ transient_files: list,
138
+ ) -> Tuple[bool, str]:
139
+ return_code, out, err = _cli_exec(
140
+ [
141
+ JAVA_PATH,
142
+ "-jar",
143
+ SAXON_PATH,
144
+ source_path,
145
+ RESOURCES_PATH + xsl_path,
146
+ ],
147
+ logger,
148
+ )
149
+ if return_code != 0:
150
+ java_out = _union_java_output(out, err)
151
+ if type(java_out) == str:
152
+ return False, java_out
153
+ else:
154
+ return False, java_out.decode("utf-8")
155
+ if _write_binary_to_file(destination_path, out, logger):
156
+ transient_files.append(destination_path)
157
+ if _log_xml_error(out, logger):
158
+ return False, "Not OK"
159
+ _log_xml_warning(out, logger)
160
+ return True, "OK"
161
+ return False, "Not OK"
162
+
163
+
164
+ def _process_doc(
165
+ doc_file,
166
+ working_dir: str,
167
+ logger: logging.Logger,
168
+ keep_transient_files: bool = False,
169
+ validation_schema: str = "metopes",
170
+ ) -> Tuple[bool, Union[str, bytes]]:
171
+ validation_schema = _check_validation_schema(validation_schema, logger)
172
+ doc_file_no_extension = os.path.splitext(doc_file)[0]
173
+ transient_files = [doc_file]
174
+ #
175
+ # CONVERSION XML
176
+ #
177
+ transient_files.append(os.path.join(working_dir, doc_file_no_extension + ".xml"))
178
+ return_code, out, err = _cli_exec(
179
+ [
180
+ SOFFICE_PATH,
181
+ "--invisible",
182
+ "--convert-to",
183
+ "xml:OpenDocument Text Flat XML",
184
+ "--outdir",
185
+ working_dir,
186
+ doc_file,
187
+ ],
188
+ logger,
189
+ )
190
+
191
+ if return_code != 0:
192
+ _clean_transient_files(transient_files, keep_transient_files)
193
+ return False, _union_java_output(out, err)
194
+ else:
195
+ os.rename(
196
+ os.path.join(
197
+ working_dir,
198
+ doc_file_no_extension + ".xml",
199
+ ),
200
+ os.path.join(working_dir, doc_file_no_extension + "_00.xml"),
201
+ )
202
+ logger.debug(
203
+ "Wrote {}".format(os.path.basename(doc_file_no_extension + "_00.xml"))
204
+ )
205
+ transient_files.append(doc_file_no_extension + "_00.xml")
206
+
207
+ #
208
+ # TRANSFORMATIONS XSL : 1 cleanup
209
+ #
210
+
211
+ success, output = _call_saxon(
212
+ xsl_path="xsl-01-cleanup/cleanup.xsl",
213
+ source_path=f"{doc_file_no_extension}_00.xml",
214
+ destination_path=f"{doc_file_no_extension}_01_clean.xml",
215
+ logger=logger,
216
+ transient_files=transient_files,
217
+ )
218
+ if not success:
219
+ _clean_transient_files(transient_files, keep_transient_files)
220
+ return False, output
221
+
222
+ #
223
+ # TRANSFORMATIONS XSL : 2 normalisation (3 steps)
224
+ #
225
+
226
+ # Normalize, step 1
227
+ success, output = _call_saxon(
228
+ xsl_path="xsl-02-normalisation/a-normalize-stylename.xsl",
229
+ source_path=f"{doc_file_no_extension}_01_clean.xml",
230
+ destination_path=f"{doc_file_no_extension}_02a_normalize.xml",
231
+ logger=logger,
232
+ transient_files=transient_files,
233
+ )
234
+ if not success:
235
+ _clean_transient_files(transient_files, keep_transient_files)
236
+ return False, output
237
+
238
+ # Normalize step 2
239
+ success, output = _call_saxon(
240
+ xsl_path="xsl-02-normalisation/b-normalize-nodes.xsl",
241
+ source_path=f"{doc_file_no_extension}_02a_normalize.xml",
242
+ destination_path=f"{doc_file_no_extension}_02b_normalize.xml",
243
+ logger=logger,
244
+ transient_files=transient_files,
245
+ )
246
+ if not success:
247
+ _clean_transient_files(transient_files, keep_transient_files)
248
+ return False, output
249
+
250
+ # Normalize, step 3
251
+ success, output = _call_saxon(
252
+ xsl_path="xsl-02-normalisation/c-normalize-groupspan.xsl",
253
+ source_path=f"{doc_file_no_extension}_02b_normalize.xml",
254
+ destination_path=f"{doc_file_no_extension}_02c_normalize.xml",
255
+ logger=logger,
256
+ transient_files=transient_files,
257
+ )
258
+ if not success:
259
+ _clean_transient_files(transient_files, keep_transient_files)
260
+ return False, output
261
+
262
+ #
263
+ # TRANSFORMATIONS XSL : 3 enrich
264
+ #
265
+ success, output = _call_saxon(
266
+ xsl_path="xsl-03-enrich/enrich.xsl",
267
+ source_path=f"{doc_file_no_extension}_02c_normalize.xml",
268
+ destination_path=f"{doc_file_no_extension}_03_enrich.xml",
269
+ logger=logger,
270
+ transient_files=transient_files,
271
+ )
272
+ if not success:
273
+ _clean_transient_files(transient_files, keep_transient_files)
274
+ return False, output
275
+
276
+ #
277
+ # TRANSFORMATIONS XSL : 4 group (a:sp)
278
+ #
279
+ success, output = _call_saxon(
280
+ xsl_path="xsl-04-group/group-sp.xsl",
281
+ source_path=f"{doc_file_no_extension}_03_enrich.xml",
282
+ destination_path=f"{doc_file_no_extension}_04a_sp.xml",
283
+ logger=logger,
284
+ transient_files=transient_files,
285
+ )
286
+ if not success:
287
+ _clean_transient_files(transient_files, keep_transient_files)
288
+ return False, output
289
+
290
+ #
291
+ # TRANSFORMATIONS XSL : 4 group (b:quote)
292
+ #
293
+ success, output = _call_saxon(
294
+ xsl_path="xsl-04-group/group-cit.xsl",
295
+ source_path=f"{doc_file_no_extension}_04a_sp.xml",
296
+ destination_path=f"{doc_file_no_extension}_04b_cit.xml",
297
+ logger=logger,
298
+ transient_files=transient_files,
299
+ )
300
+ if not success:
301
+ _clean_transient_files(transient_files, keep_transient_files)
302
+ return False, output
303
+
304
+ #
305
+ # TRANSFORMATIONS XSL : 4 group (c:figure)
306
+ #
307
+ success, output = _call_saxon(
308
+ xsl_path="xsl-04-group/group-figure.xsl",
309
+ source_path=f"{doc_file_no_extension}_04b_cit.xml",
310
+ destination_path=f"{doc_file_no_extension}_04c_fig.xml",
311
+ logger=logger,
312
+ transient_files=transient_files,
313
+ )
314
+ if not success:
315
+ _clean_transient_files(transient_files, keep_transient_files)
316
+ return False, output
317
+
318
+ #
319
+ # TRANSFORMATIONS XSL : 4 group (cbis:figure-grp)
320
+ #
321
+ success, output = _call_saxon(
322
+ xsl_path="xsl-04-group/group-figure-grp.xsl",
323
+ source_path=f"{doc_file_no_extension}_04c_fig.xml",
324
+ destination_path=f"{doc_file_no_extension}_04c-bis_fig.xml",
325
+ logger=logger,
326
+ transient_files=transient_files,
327
+ )
328
+ if not success:
329
+ _clean_transient_files(transient_files, keep_transient_files)
330
+ return False, output
331
+
332
+ #
333
+ # TRANSFORMATIONS XSL : 4 group (d:recension)
334
+ #
335
+ success, output = _call_saxon(
336
+ xsl_path="xsl-04-group/group-review.xsl",
337
+ source_path=f"{doc_file_no_extension}_04c-bis_fig.xml",
338
+ destination_path=f"{doc_file_no_extension}_04d_review.xml",
339
+ logger=logger,
340
+ transient_files=transient_files,
341
+ )
342
+ if not success:
343
+ _clean_transient_files(transient_files, keep_transient_files)
344
+ return False, output
345
+
346
+ #
347
+ # TRANSFORMATIONS XSL : 4 group (dbis:review hierarchise)
348
+ #
349
+ success, output = _call_saxon(
350
+ xsl_path="xsl-04-group/hierarchize-review.xsl",
351
+ source_path=f"{doc_file_no_extension}_04d_review.xml",
352
+ destination_path=f"{doc_file_no_extension}_04e_review.xml",
353
+ logger=logger,
354
+ transient_files=transient_files,
355
+ )
356
+ if not success:
357
+ _clean_transient_files(transient_files, keep_transient_files)
358
+ return False, output
359
+
360
+ #
361
+ # TRANSFORMATIONS XSL : 4 group (e:floatingText)
362
+ #
363
+ success, output = _call_saxon(
364
+ xsl_path="xsl-04-group/group-floatingText.xsl",
365
+ source_path=f"{doc_file_no_extension}_04e_review.xml",
366
+ destination_path=f"{doc_file_no_extension}_04f_floatingText.xml",
367
+ logger=logger,
368
+ transient_files=transient_files,
369
+ )
370
+ if not success:
371
+ _clean_transient_files(transient_files, keep_transient_files)
372
+ return False, output
373
+
374
+ #
375
+ # TRANSFORMATIONS XSL : 4 group (ebis:floatingText hierarchise)
376
+ #
377
+ success, output = _call_saxon(
378
+ xsl_path="xsl-04-group/hierarchize-floatingText.xsl",
379
+ source_path=f"{doc_file_no_extension}_04f_floatingText.xml",
380
+ destination_path=f"{doc_file_no_extension}_04g_floatingText.xml",
381
+ logger=logger,
382
+ transient_files=transient_files,
383
+ )
384
+ if not success:
385
+ _clean_transient_files(transient_files, keep_transient_files)
386
+ return False, output
387
+
388
+ #
389
+ # TRANSFORMATIONS XSL : 5 control hierarchy
390
+ #
391
+ success, output = _call_saxon(
392
+ xsl_path="xsl-05-control/control-hierarchy.xsl",
393
+ source_path=f"{doc_file_no_extension}_04g_floatingText.xml",
394
+ destination_path=f"{doc_file_no_extension}_05_control.xml",
395
+ logger=logger,
396
+ transient_files=transient_files,
397
+ )
398
+ if not success:
399
+ _clean_transient_files(transient_files, keep_transient_files)
400
+ return False, output
401
+
402
+ #
403
+ # TRANSFORMATIONS XSL : 6 hierarchize
404
+ #
405
+ success, output = _call_saxon(
406
+ xsl_path="xsl-06-hierarchize/hierarchize.xsl",
407
+ source_path=f"{doc_file_no_extension}_05_control.xml",
408
+ destination_path=f"{doc_file_no_extension}_06_hierarchize.xml",
409
+ logger=logger,
410
+ transient_files=transient_files,
411
+ )
412
+ if not success:
413
+ _clean_transient_files(transient_files, keep_transient_files)
414
+ return False, output
415
+
416
+ #
417
+ # TRANSFORMATIONS XSL : 7 organise
418
+ #
419
+ success, output = _call_saxon(
420
+ xsl_path="xsl-07-organise/organise.xsl",
421
+ source_path=f"{doc_file_no_extension}_06_hierarchize.xml",
422
+ destination_path=f"{doc_file_no_extension}_07_organise.xml",
423
+ logger=logger,
424
+ transient_files=transient_files,
425
+ )
426
+ if not success:
427
+ _clean_transient_files(transient_files, keep_transient_files)
428
+ return False, output
429
+
430
+ #
431
+ # TRANSFORMATIONS XSL : 8 to TEI
432
+ #
433
+ success, output = _call_saxon(
434
+ xsl_path="xsl-08-totei/totei.xsl",
435
+ source_path=f"{doc_file_no_extension}_07_organise.xml",
436
+ destination_path=f"{doc_file_no_extension}_08_tei.xml",
437
+ logger=logger,
438
+ transient_files=transient_files,
439
+ )
440
+ if not success:
441
+ _clean_transient_files(transient_files, keep_transient_files)
442
+ return False, output
443
+
444
+ #
445
+ # TRANSFORMATIONS XSL : 9 control styles and id
446
+ #
447
+ success, output = _call_saxon(
448
+ xsl_path="xsl-05-control/control-styles-id.xsl",
449
+ source_path=f"{doc_file_no_extension}_08_tei.xml",
450
+ destination_path=f"{doc_file_no_extension}_09_tei_plus.xml",
451
+ logger=logger,
452
+ transient_files=transient_files,
453
+ )
454
+ if not success:
455
+ _clean_transient_files(transient_files, keep_transient_files)
456
+ return False, output
457
+
458
+ #
459
+ # TRANSFORMATIONS XSL : 10 suppression des erreurs
460
+ #
461
+ success, output = _call_saxon(
462
+ xsl_path="xsl-05-control/control-errors.xsl",
463
+ source_path=f"{doc_file_no_extension}_09_tei_plus.xml",
464
+ destination_path=f"{doc_file_no_extension}_10_tei_metopes.xml",
465
+ logger=logger,
466
+ transient_files=transient_files,
467
+ )
468
+ if not success:
469
+ _clean_transient_files(transient_files, keep_transient_files)
470
+ return False, output
471
+
472
+ if validation_schema == "metopes":
473
+ #
474
+ # VALIDATION METOPES
475
+ #
476
+ return_code, out, err = _cli_exec(
477
+ [
478
+ XMLLINT_PATH,
479
+ "--relaxng",
480
+ RESOURCES_PATH + "schema/metopes.rng",
481
+ doc_file_no_extension + "_10_tei_metopes.xml",
482
+ ],
483
+ logger,
484
+ )
485
+ transient_files.append(doc_file_no_extension + "_10_tei_metopes.xml")
486
+ if return_code != 0:
487
+ logger.error(
488
+ "Validate {} {}".format(
489
+ os.path.basename(doc_file_no_extension + "_10_tei_metopes.xml"),
490
+ _union_java_output(out, err),
491
+ )
492
+ )
493
+ else:
494
+ logger.info(
495
+ "Validate {}".format(
496
+ os.path.basename(
497
+ doc_file_no_extension
498
+ + "_10_tei_metopes.xml validates {}".format(validation_schema)
499
+ )
500
+ )
501
+ )
502
+ elif validation_schema == "openedition":
503
+ #
504
+ # TRANSFORMATIONS XSL : 11 to OpenEdition
505
+ #
506
+ success, output = _call_saxon(
507
+ xsl_path="xsl-09-toOpenedition/toOpenedition.xsl",
508
+ source_path=f"{doc_file_no_extension}_10_tei_metopes.xml",
509
+ destination_path=f"{doc_file_no_extension}_11_tei_openedition.xml",
510
+ logger=logger,
511
+ transient_files=transient_files,
512
+ )
513
+ if not success:
514
+ _clean_transient_files(transient_files, keep_transient_files)
515
+ return False, output
516
+
517
+ #
518
+ # VALIDATION OPENEDITION
519
+ #
520
+ return_code, out, err = _cli_exec(
521
+ [
522
+ XMLLINT_PATH,
523
+ # "--valid",
524
+ "--relaxng",
525
+ "http://lodel.org/ns/tei/draft/commons-publishing-openedition.rng",
526
+ doc_file_no_extension + "_11_tei_openedition.xml",
527
+ # "--noout",
528
+ ],
529
+ logger,
530
+ )
531
+ if return_code != 0:
532
+ logger.error(
533
+ "Validate {} {}".format(
534
+ os.path.basename(doc_file_no_extension + "_11_tei_openedition.xml"),
535
+ _union_java_output(out, err),
536
+ )
537
+ )
538
+ else:
539
+ logger.info(
540
+ "Validate {}".format(
541
+ os.path.basename(
542
+ doc_file_no_extension
543
+ + "_11_tei_openedition.xml validates {}".format(
544
+ validation_schema
545
+ )
546
+ )
547
+ )
548
+ )
549
+ #
550
+ # TRAITEMENT DES IMAGES
551
+ #
552
+ for b64_path in glob.glob(working_dir + "/images/*.base64"):
553
+ destination_path, _ = os.path.splitext(b64_path)
554
+ with open(destination_path, "wb") as destination_file:
555
+ with open(b64_path, "rb") as b64_file:
556
+ destination_file.write(base64.decodebytes(b64_file.read()))
557
+ _silent_remove(b64_path)
558
+
559
+ final_file_destination = os.path.join(working_dir, doc_file_no_extension + ".xml")
560
+ if validation_schema == "metopes":
561
+ shutil.copy(
562
+ os.path.join(working_dir, doc_file_no_extension + "_10_tei_metopes.xml"),
563
+ final_file_destination,
564
+ )
565
+ if validation_schema == "openedition":
566
+ shutil.copy(
567
+ os.path.join(
568
+ working_dir, doc_file_no_extension + "_11_tei_openedition.xml"
569
+ ),
570
+ final_file_destination,
571
+ )
572
+ transient_files.remove(final_file_destination)
573
+ _clean_transient_files(transient_files, keep_transient_files)
574
+
575
+ return True, "All OK"
576
+
577
+
578
+ def doc2tei(working_dir: str, logger: logging.Logger, options: dict = None):
579
+ options = options or {}
580
+ keep_transient_files = False
581
+ if options.get("keep_transient_files", False) == "oui":
582
+ keep_transient_files = True
583
+ success_counter = 0
584
+ failure_counter = 0
585
+ doc_files = _find_files("*.docx", working_dir) + _find_files("*.odt", working_dir)
586
+ logger.info("{} file(s) to convert.".format(len(doc_files)))
587
+ for doc_file in doc_files:
588
+ logger.info("converting {}".format(os.path.basename(doc_file)))
589
+ success, output = _process_doc(
590
+ doc_file,
591
+ working_dir,
592
+ logger,
593
+ keep_transient_files,
594
+ options.get("validation_schema", "metopes"),
595
+ )
596
+ if not success:
597
+ logger.error(
598
+ "could not convert {}. Process output: {}".format(
599
+ os.path.basename(doc_file), output
600
+ )
601
+ )
602
+ failure_counter = failure_counter + 1
603
+ else:
604
+ success_counter = success_counter + 1
605
+ logger.info("{}: success".format(os.path.basename(doc_file)))
606
+ logger.info("Job done, {} files converted".format(success_counter))
607
+
608
+
609
+ doc2tei.description = {
610
+ "label": "Docx vers TEI",
611
+ "help": "Convertir les fichiers *.docx et *.odt en fichiers *.xml (vocabulaire TEI)",
612
+ "options": [
613
+ {
614
+ "id": "keep_transient_files",
615
+ "label": "garder les fichiers intermédiaires",
616
+ "values": {"oui": "oui", "non": "non"},
617
+ "default": "non",
618
+ "free_input": False,
619
+ },
620
+ {
621
+ "id": "validation_schema",
622
+ "label": "schéma de validation",
623
+ "values": {"metopes": "Métopes", "openedition": "openedition"},
624
+ "default": "metopes",
625
+ "free_input": False,
626
+ },
627
+ ],
628
+ }
doc2tei/__main__.py ADDED
@@ -0,0 +1,58 @@
1
+ import logging
2
+ import sys
3
+
4
+ import argh
5
+ from doc2tei import _process_doc
6
+ import os
7
+ import shutil
8
+ import sys
9
+
10
+ logger = logging.getLogger(__name__)
11
+ logger.setLevel(logging.INFO)
12
+ logger.addHandler(logging.StreamHandler())
13
+
14
+
15
+ def _convert_file(
16
+ input_file_path: str,
17
+ keep_transient_files: bool = False,
18
+ schema: str = "metopes",
19
+ out_dir: str = None,
20
+ verbose: bool = False,
21
+ ):
22
+ """
23
+ Converts a *.docx file to XML TEI.
24
+ """
25
+ if verbose:
26
+ logger.setLevel(logging.DEBUG)
27
+ destination_folder = os.path.dirname(os.path.abspath(input_file_path))
28
+ if out_dir:
29
+ out_dir = os.path.abspath(out_dir)
30
+ if (
31
+ out_dir == destination_folder
32
+ ): # when out_dir is the directory of input_file_path...
33
+ out_dir = None # ...this is effectively the same as not specifying out_dir
34
+ else:
35
+ os.makedirs(out_dir, exist_ok=True)
36
+ copy_dest = os.path.join(out_dir, os.path.basename(input_file_path))
37
+ shutil.copy(input_file_path, copy_dest)
38
+ input_file_path = copy_dest
39
+ destination_folder = out_dir
40
+ if not os.path.exists(input_file_path):
41
+ sys.exit(f"no such file: {input_file_path}")
42
+ success, output = _process_doc(
43
+ input_file_path,
44
+ destination_folder,
45
+ logger,
46
+ keep_transient_files,
47
+ schema,
48
+ )
49
+ if not success:
50
+ sys.exit(output)
51
+
52
+
53
+ def run_cli():
54
+ argh.dispatch_command(_convert_file)
55
+
56
+
57
+ if __name__ == "__main__":
58
+ run_cli()
Binary file