@tiens.nguyen/gu-cli 1.0.902 → 1.0.904

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 (187) hide show
  1. package/NOTICE +18 -0
  2. package/package.json +3 -2
  3. package/skills/core/deep-research/SKILL.md +51 -0
  4. package/skills/core/docx/LICENSE.txt +202 -0
  5. package/skills/core/docx/SKILL.md +97 -0
  6. package/skills/core/docx/scripts/__init__.py +1 -0
  7. package/skills/core/docx/scripts/accept_changes.py +135 -0
  8. package/skills/core/docx/scripts/comment.py +368 -0
  9. package/skills/core/docx/scripts/merge_runs.py +310 -0
  10. package/skills/core/docx/scripts/office/helpers/__init__.py +121 -0
  11. package/skills/core/docx/scripts/office/helpers/pptx_chart.py +283 -0
  12. package/skills/core/docx/scripts/office/helpers/pptx_slide.py +100 -0
  13. package/skills/core/docx/scripts/office/helpers/pptx_theme.py +114 -0
  14. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  15. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  16. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  17. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  18. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  19. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  20. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  21. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  22. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  23. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  24. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  25. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  26. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  27. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  28. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  29. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  30. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  31. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  32. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  33. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  34. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  35. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  36. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  37. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  38. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  39. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  40. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  41. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  42. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  43. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  44. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  45. package/skills/core/docx/scripts/office/schemas/mce/mc.xsd +75 -0
  46. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  47. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  48. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  49. package/skills/core/docx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  50. package/skills/core/docx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  51. package/skills/core/docx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  52. package/skills/core/docx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  53. package/skills/core/docx/scripts/office/soffice.py +192 -0
  54. package/skills/core/docx/scripts/office/validate.py +210 -0
  55. package/skills/core/docx/scripts/office/validators/__init__.py +15 -0
  56. package/skills/core/docx/scripts/office/validators/base.py +874 -0
  57. package/skills/core/docx/scripts/office/validators/docx.py +519 -0
  58. package/skills/core/docx/scripts/office/validators/pptx.py +549 -0
  59. package/skills/core/docx/scripts/office/validators/redlining.py +461 -0
  60. package/skills/core/docx/scripts/templates/comments.xml +3 -0
  61. package/skills/core/docx/scripts/templates/commentsExtended.xml +3 -0
  62. package/skills/core/docx/scripts/templates/commentsExtensible.xml +3 -0
  63. package/skills/core/docx/scripts/templates/commentsIds.xml +3 -0
  64. package/skills/core/docx/scripts/templates/people.xml +3 -0
  65. package/skills/core/pdf/FORMS.md +294 -0
  66. package/skills/core/pdf/LICENSE.txt +202 -0
  67. package/skills/core/pdf/REFERENCE.md +613 -0
  68. package/skills/core/pdf/SKILL.md +314 -0
  69. package/skills/core/pdf/scripts/check_bounding_boxes.py +65 -0
  70. package/skills/core/pdf/scripts/check_fillable_fields.py +11 -0
  71. package/skills/core/pdf/scripts/convert_pdf_to_images.py +33 -0
  72. package/skills/core/pdf/scripts/create_validation_image.py +37 -0
  73. package/skills/core/pdf/scripts/extract_form_field_info.py +122 -0
  74. package/skills/core/pdf/scripts/extract_form_structure.py +115 -0
  75. package/skills/core/pdf/scripts/fill_fillable_fields.py +98 -0
  76. package/skills/core/pdf/scripts/fill_pdf_form_with_annotations.py +107 -0
  77. package/skills/core/pptx/LICENSE.txt +202 -0
  78. package/skills/core/pptx/SKILL.md +275 -0
  79. package/skills/core/pptx/scripts/__init__.py +0 -0
  80. package/skills/core/pptx/scripts/add_slide.py +463 -0
  81. package/skills/core/pptx/scripts/apply_theme.js +107 -0
  82. package/skills/core/pptx/scripts/clean.py +309 -0
  83. package/skills/core/pptx/scripts/office/helpers/__init__.py +121 -0
  84. package/skills/core/pptx/scripts/office/helpers/pptx_chart.py +283 -0
  85. package/skills/core/pptx/scripts/office/helpers/pptx_slide.py +100 -0
  86. package/skills/core/pptx/scripts/office/helpers/pptx_theme.py +114 -0
  87. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  88. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  89. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  90. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  91. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  92. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  93. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  94. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  95. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  96. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  97. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  98. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  99. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  100. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  101. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  102. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  103. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  104. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  105. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  106. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  107. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  108. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  109. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  110. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  111. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  112. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  113. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  114. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  115. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  116. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  117. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  118. package/skills/core/pptx/scripts/office/schemas/mce/mc.xsd +75 -0
  119. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  120. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  121. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  122. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  123. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  124. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  125. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  126. package/skills/core/pptx/scripts/office/soffice.py +192 -0
  127. package/skills/core/pptx/scripts/office/validate.py +210 -0
  128. package/skills/core/pptx/scripts/office/validators/__init__.py +15 -0
  129. package/skills/core/pptx/scripts/office/validators/base.py +874 -0
  130. package/skills/core/pptx/scripts/office/validators/docx.py +519 -0
  131. package/skills/core/pptx/scripts/office/validators/pptx.py +549 -0
  132. package/skills/core/pptx/scripts/office/validators/redlining.py +461 -0
  133. package/skills/core/pptx/scripts/slide_text.py +132 -0
  134. package/skills/core/pptx/scripts/thumbnail.py +311 -0
  135. package/skills/core/xlsx/LICENSE.txt +202 -0
  136. package/skills/core/xlsx/SKILL.md +99 -0
  137. package/skills/core/xlsx/scripts/office/helpers/__init__.py +121 -0
  138. package/skills/core/xlsx/scripts/office/helpers/pptx_chart.py +283 -0
  139. package/skills/core/xlsx/scripts/office/helpers/pptx_slide.py +100 -0
  140. package/skills/core/xlsx/scripts/office/helpers/pptx_theme.py +114 -0
  141. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  142. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  143. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  144. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  145. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  146. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  147. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  148. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  149. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  150. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  151. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  152. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  153. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  154. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  155. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  156. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  157. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  158. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  159. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  160. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  161. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  162. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  163. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  164. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  165. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  166. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  167. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  168. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  169. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  170. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  171. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  172. package/skills/core/xlsx/scripts/office/schemas/mce/mc.xsd +75 -0
  173. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  174. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  175. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  176. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  177. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  178. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  179. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  180. package/skills/core/xlsx/scripts/office/soffice.py +192 -0
  181. package/skills/core/xlsx/scripts/office/validate.py +210 -0
  182. package/skills/core/xlsx/scripts/office/validators/__init__.py +15 -0
  183. package/skills/core/xlsx/scripts/office/validators/base.py +874 -0
  184. package/skills/core/xlsx/scripts/office/validators/docx.py +519 -0
  185. package/skills/core/xlsx/scripts/office/validators/pptx.py +549 -0
  186. package/skills/core/xlsx/scripts/office/validators/redlining.py +461 -0
  187. package/skills/core/xlsx/scripts/recalc.py +456 -0
@@ -0,0 +1,456 @@
1
+ """
2
+ Excel Formula Recalculation Script
3
+ Recalculates all formulas in an Excel file using LibreOffice
4
+ """
5
+
6
+ import contextlib
7
+ import io
8
+ import json
9
+ import os
10
+ import platform
11
+ import posixpath
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ import zipfile
19
+ from pathlib import Path
20
+
21
+ from office.soffice import get_soffice_env, run_soffice
22
+
23
+ MACRO_FILENAME = "Module1.xba"
24
+ SOFFICE_MISSING = "soffice not found on PATH; LibreOffice is required to recalculate"
25
+
26
+ MAX_LOCATIONS = 100
27
+
28
+ EXTERNAL_REF_RE = re.compile(r"""(?<![\w"\[])'?\[\d+\][^!"\[\]]*'?!""")
29
+
30
+ RECALCULATE_MACRO = """<?xml version="1.0" encoding="UTF-8"?>
31
+ <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
32
+ <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
33
+ Sub RecalculateAndSave()
34
+ ThisComponent.calculateAll()
35
+ ThisComponent.store()
36
+ ThisComponent.close(True)
37
+ End Sub
38
+ </script:module>"""
39
+
40
+
41
+ def has_gtimeout():
42
+ try:
43
+ subprocess.run(
44
+ ["gtimeout", "--version"], capture_output=True, timeout=1, check=False
45
+ )
46
+ return True
47
+ except (FileNotFoundError, subprocess.TimeoutExpired):
48
+ return False
49
+
50
+
51
+ def _stamp(path):
52
+ st = os.stat(path)
53
+ return st.st_mtime_ns, st.st_size
54
+
55
+
56
+ def setup_libreoffice_macro(profile_dir: Path, timeout=30):
57
+ url = profile_dir.as_uri()
58
+ try:
59
+ run_soffice(
60
+ ["--headless", "--terminate_after_init", f"-env:UserInstallation={url}"],
61
+ capture_output=True,
62
+ timeout=timeout,
63
+ )
64
+ except FileNotFoundError:
65
+ return None, SOFFICE_MISSING
66
+ except subprocess.TimeoutExpired:
67
+ return None, "LibreOffice timed out creating its profile; formulas were NOT recalculated"
68
+
69
+ macro_dir = profile_dir / "user" / "basic" / "Standard"
70
+ if not macro_dir.exists():
71
+ return None, "LibreOffice did not create a usable profile; formulas were NOT recalculated"
72
+
73
+ try:
74
+ (macro_dir / MACRO_FILENAME).write_text(RECALCULATE_MACRO)
75
+ except OSError as e:
76
+ return None, f"Could not install the recalculation macro: {e}"
77
+
78
+ return url, None
79
+
80
+
81
+ def _names_pattern(names):
82
+ if not names:
83
+ return None
84
+ return re.compile(r"\b(" + "|".join(re.escape(n) for n in sorted(names)) + r")\b")
85
+
86
+
87
+ def _existing_cells(ws):
88
+ if not hasattr(ws, "iter_rows"):
89
+ return []
90
+ return [ws._cells[key] for key in sorted(ws._cells)]
91
+
92
+
93
+ def external_links_at_risk(filename):
94
+ try:
95
+ with zipfile.ZipFile(filename) as archive:
96
+ names = archive.namelist()
97
+ except (zipfile.BadZipFile, OSError):
98
+ return []
99
+ if not any(n.startswith("xl/externalLinks/") for n in names):
100
+ return []
101
+
102
+ from openpyxl import load_workbook
103
+ from openpyxl.worksheet.formula import ArrayFormula
104
+
105
+ with contextlib.ExitStack() as stack:
106
+ formulas = load_workbook(filename, data_only=False)
107
+ stack.callback(formulas.close)
108
+ values = load_workbook(filename, data_only=True)
109
+ stack.callback(values.close)
110
+
111
+ defined_names = list(formulas.defined_names.items())
112
+ for scope_ws in formulas.worksheets:
113
+ defined_names.extend(scope_ws.defined_names.items())
114
+ name_texts = [
115
+ (name, dn.value)
116
+ for name, dn in defined_names
117
+ if isinstance(getattr(dn, "value", None), str)
118
+ ]
119
+ external_names = {name for name, text in name_texts if EXTERNAL_REF_RE.search(text)}
120
+ while True:
121
+ name_re = _names_pattern(external_names)
122
+ if name_re is None:
123
+ break
124
+ added = {
125
+ name
126
+ for name, text in name_texts
127
+ if name not in external_names and name_re.search(text)
128
+ }
129
+ if not added:
130
+ break
131
+ external_names |= added
132
+ name_re = _names_pattern(external_names)
133
+
134
+ at_risk = []
135
+ for sheet in formulas.sheetnames:
136
+ ws = formulas[sheet]
137
+ cached = values[sheet]
138
+ for cell in _existing_cells(ws):
139
+ v = cell.value
140
+ if isinstance(v, ArrayFormula):
141
+ v = v.text
142
+ if not (isinstance(v, str) and v.startswith("=")):
143
+ continue
144
+ reaches_out = EXTERNAL_REF_RE.search(v) or (name_re and name_re.search(v))
145
+ if reaches_out and cached[cell.coordinate].value is None:
146
+ at_risk.append(f"{sheet}!{cell.coordinate}")
147
+ return at_risk
148
+
149
+
150
+ def recalc(filename, timeout=30, force=False):
151
+ if not Path(filename).exists():
152
+ return {"error": f"File {filename} does not exist"}
153
+
154
+ abs_path = str(Path(filename).absolute())
155
+
156
+ if not os.access(abs_path, os.W_OK):
157
+ return {"error": f"{filename} is not writable; recalculation rewrites the file in place"}
158
+
159
+ try:
160
+ get_soffice_env()
161
+ except Exception as e:
162
+ return {"error": f"Could not prepare the LibreOffice environment: {e}"}
163
+
164
+ if not force:
165
+ try:
166
+ at_risk = external_links_at_risk(filename)
167
+ except Exception as e:
168
+ return {"error": f"Could not inspect {filename} for external links: {e}"}
169
+ if at_risk:
170
+ shown = at_risk[:MAX_LOCATIONS]
171
+ return {
172
+ "error": (
173
+ "Refusing to recalculate: this workbook links to another workbook, and "
174
+ f"{len(at_risk)} linked cell(s) have lost their cached value (openpyxl strips "
175
+ "these on save). Recalculating would resolve them to #NAME? and delete the "
176
+ "external links for good. Copy those cells' values from the original file "
177
+ "before saving, or pass --force to accept the loss. Charts and conditional "
178
+ "formats can hold external references too, so this list may not be exhaustive."
179
+ ),
180
+ "external_link_cells": shown,
181
+ "external_link_cells_truncated": max(0, len(at_risk) - len(shown)),
182
+ }
183
+
184
+ with tempfile.TemporaryDirectory(
185
+ prefix="recalc-lo-profile-", ignore_cleanup_errors=True
186
+ ) as profile_dir:
187
+ return _recalc_with_profile(filename, abs_path, timeout, Path(profile_dir))
188
+
189
+
190
+ def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
191
+ started = time.monotonic()
192
+ profile_url, err = setup_libreoffice_macro(profile_dir, timeout=timeout)
193
+ if err:
194
+ return {"error": err}
195
+
196
+ timeout = max(5, int(timeout - (time.monotonic() - started)))
197
+
198
+ before = _stamp(abs_path)
199
+
200
+ cmd = [
201
+ "soffice",
202
+ "--headless",
203
+ "--norestore",
204
+ f"-env:UserInstallation={profile_url}",
205
+ "vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application",
206
+ abs_path,
207
+ ]
208
+
209
+ if platform.system() == "Linux" and shutil.which("timeout"):
210
+ cmd = ["timeout", str(timeout)] + cmd
211
+ elif platform.system() == "Darwin" and has_gtimeout():
212
+ cmd = ["gtimeout", str(timeout)] + cmd
213
+
214
+ timed_out = f"LibreOffice timed out after {timeout}s; formulas were NOT recalculated. Re-run with a longer timeout."
215
+
216
+ try:
217
+ result = subprocess.run(
218
+ cmd, capture_output=True, text=True, env=get_soffice_env(), timeout=timeout + 15
219
+ )
220
+ except subprocess.TimeoutExpired:
221
+ return {"error": timed_out}
222
+ except FileNotFoundError:
223
+ return {"error": SOFFICE_MISSING}
224
+
225
+ if result.returncode == 124:
226
+ return {"error": timed_out}
227
+
228
+ if result.returncode != 0:
229
+ detail = (result.stderr or "").strip() or f"soffice exited {result.returncode}"
230
+ return {"error": f"LibreOffice failed to recalculate: {detail}"}
231
+
232
+ if _stamp(abs_path) == before:
233
+ return {
234
+ "error": (
235
+ "LibreOffice exited cleanly but never rewrote the file, so nothing was "
236
+ "recalculated. Check that no other LibreOffice instance is running, then retry."
237
+ )
238
+ }
239
+
240
+ return _report(filename)
241
+
242
+
243
+ EXCEL_ERRORS = ["#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"]
244
+
245
+ _MAIN_NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
246
+ _REL_NS = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
247
+ _CELL_REF_RE = re.compile(r"([A-Z]+)([0-9]+)")
248
+ MAX_MERGE_CHECKS = 1_000_000
249
+ _MERGE_RE = re.compile(rb'<(?:\w+:)?mergeCell\b[^>]*\bref="([^"]*)"')
250
+
251
+
252
+ def _error_in(text):
253
+ if "#" in text:
254
+ for err in EXCEL_ERRORS:
255
+ if err in text:
256
+ return err
257
+ return None
258
+
259
+
260
+ def _rich_text(node):
261
+ runs = node.findall(f"{_MAIN_NS}t") + node.findall(f"{_MAIN_NS}r/{_MAIN_NS}t")
262
+ return "".join(t.text or "" for t in runs)
263
+
264
+
265
+ def _row_major(coordinate):
266
+ column, row = _CELL_REF_RE.fullmatch(coordinate).groups()
267
+ number = 0
268
+ for letter in column:
269
+ number = number * 26 + ord(letter) - ord("A") + 1
270
+ return int(row), number
271
+
272
+
273
+ def _merged_ranges(sheet_xml):
274
+ ranges = []
275
+ for ref in _MERGE_RE.findall(sheet_xml):
276
+ first, _, last = ref.decode().partition(":")
277
+ ranges.append((*_row_major(first), *_row_major(last)))
278
+ return ranges
279
+
280
+
281
+ def _hidden_by_a_merge(merged, row, column):
282
+ return any(
283
+ top <= row <= bottom and left <= column <= right and (row, column) != (top, left)
284
+ for top, left, bottom, right in merged
285
+ )
286
+
287
+
288
+ def _scan_xml(filename):
289
+ from defusedxml.ElementTree import fromstring, iterparse
290
+
291
+ error_details = {err: [] for err in EXCEL_ERRORS}
292
+ formula_count = 0
293
+ merge_checks = 0
294
+
295
+ with zipfile.ZipFile(filename) as archive:
296
+ workbook = fromstring(archive.read("xl/workbook.xml"))
297
+ if workbook.tag != f"{_MAIN_NS}workbook":
298
+ raise ValueError("not a transitional OOXML workbook")
299
+ targets = {
300
+ rel.get("Id"): rel.get("Target")
301
+ for rel in fromstring(archive.read("xl/_rels/workbook.xml.rels"))
302
+ }
303
+
304
+ shared_errors, shared_equals = {}, set()
305
+ if "xl/sharedStrings.xml" in archive.namelist():
306
+ with archive.open("xl/sharedStrings.xml") as part:
307
+ index = 0
308
+ for _, node in iterparse(part):
309
+ if node.tag != f"{_MAIN_NS}si":
310
+ continue
311
+ text = _rich_text(node).replace("x005F_", "")
312
+ err = _error_in(text)
313
+ if err:
314
+ shared_errors[index] = err
315
+ if text.startswith("="):
316
+ shared_equals.add(index)
317
+ index += 1
318
+ node.clear()
319
+
320
+ for sheet in workbook.find(f"{_MAIN_NS}sheets"):
321
+ target = targets[sheet.get(f"{_REL_NS}id")]
322
+ if target.startswith("/"):
323
+ part_name = target.lstrip("/")
324
+ else:
325
+ part_name = posixpath.normpath(f"xl/{target}")
326
+ if "/worksheets/" not in part_name:
327
+ continue
328
+ found = []
329
+ xml = archive.read(part_name)
330
+ merged = _merged_ranges(xml)
331
+ for _, node in iterparse(io.BytesIO(xml)):
332
+ if node.tag == f"{_MAIN_NS}row":
333
+ node.clear()
334
+ if node.tag != f"{_MAIN_NS}c":
335
+ continue
336
+ if node.get("r") is None:
337
+ raise ValueError("a cell without its address")
338
+ formula = node.find(f"{_MAIN_NS}f")
339
+ is_formula = formula is not None and formula.get("t") != "dataTable"
340
+ err = None
341
+ cell_type = node.get("t", "n")
342
+ if cell_type == "s":
343
+ index = int(node.findtext(f"{_MAIN_NS}v"))
344
+ err = shared_errors.get(index)
345
+ is_formula = is_formula or (formula is None and index in shared_equals)
346
+ elif cell_type not in ("n", "b", "d"):
347
+ inline = node.find(f"{_MAIN_NS}is")
348
+ text = node.findtext(f"{_MAIN_NS}v") if inline is None else _rich_text(inline)
349
+ err = _error_in(text or "")
350
+ is_formula = is_formula or (formula is None and (text or "").startswith("="))
351
+ if not is_formula and not err:
352
+ continue
353
+ row, column = _row_major(node.get("r"))
354
+ merge_checks += len(merged)
355
+ if merge_checks > MAX_MERGE_CHECKS:
356
+ raise ValueError("too many merged ranges for this many cells")
357
+ if _hidden_by_a_merge(merged, row, column):
358
+ continue
359
+ formula_count += is_formula
360
+ if err:
361
+ found.append(((row, column), err, node.get("r")))
362
+ for _, err, coordinate in sorted(found):
363
+ error_details[err].append(f"{sheet.get('name')}!{coordinate}")
364
+
365
+ return error_details, formula_count
366
+
367
+
368
+ def _scan_with_openpyxl(filename):
369
+ from openpyxl import load_workbook
370
+ from openpyxl.worksheet.formula import ArrayFormula
371
+
372
+ error_details = {err: [] for err in EXCEL_ERRORS}
373
+ wb = load_workbook(filename, data_only=True)
374
+ for sheet_name in wb.sheetnames:
375
+ ws = wb[sheet_name]
376
+ for cell in _existing_cells(ws):
377
+ if isinstance(cell.value, str):
378
+ err = _error_in(cell.value)
379
+ if err:
380
+ error_details[err].append(f"{sheet_name}!{cell.coordinate}")
381
+ wb.close()
382
+
383
+ wb_formulas = load_workbook(filename, data_only=False)
384
+ formula_count = 0
385
+ for sheet_name in wb_formulas.sheetnames:
386
+ ws = wb_formulas[sheet_name]
387
+ for cell in _existing_cells(ws):
388
+ v = cell.value
389
+ if isinstance(v, ArrayFormula):
390
+ v = v.text
391
+ if isinstance(v, str) and v.startswith("="):
392
+ formula_count += 1
393
+ wb_formulas.close()
394
+
395
+ return error_details, formula_count
396
+
397
+
398
+ def _report(filename):
399
+ try:
400
+ try:
401
+ error_details, formula_count = _scan_xml(filename)
402
+ except Exception:
403
+ error_details, formula_count = _scan_with_openpyxl(filename)
404
+ except Exception as e:
405
+ return {"error": str(e)}
406
+
407
+ total_errors = sum(len(locations) for locations in error_details.values())
408
+ result = {
409
+ "status": "success" if total_errors == 0 else "errors_found",
410
+ "total_errors": total_errors,
411
+ "error_summary": {},
412
+ }
413
+
414
+ for err_type, locations in error_details.items():
415
+ if locations:
416
+ entry = {"count": len(locations), "locations": locations[:MAX_LOCATIONS]}
417
+ if len(locations) > MAX_LOCATIONS:
418
+ entry["locations_truncated"] = len(locations) - MAX_LOCATIONS
419
+ result["error_summary"][err_type] = entry
420
+
421
+ result["total_formulas"] = formula_count
422
+ return result
423
+
424
+
425
+ def main():
426
+ args = [a for a in sys.argv[1:] if a != "--force"]
427
+ force = "--force" in sys.argv[1:]
428
+
429
+ if not args:
430
+ print("Usage: python recalc.py <excel_file> [timeout_seconds] [--force]")
431
+ print("\nRecalculates all formulas in an Excel file using LibreOffice")
432
+ print("\nReturns JSON with error details:")
433
+ print(" - status: 'success' or 'errors_found'")
434
+ print(" - total_errors: Total number of Excel errors found")
435
+ print(" - total_formulas: Number of formulas in the file")
436
+ print(" - error_summary: Breakdown by error type with locations")
437
+ print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A")
438
+ print("\nOn any failure the JSON has an 'error' key and no 'status'.")
439
+ print("--force recalculates even when it would destroy external links.")
440
+ sys.exit(1)
441
+
442
+ filename = args[0]
443
+ try:
444
+ timeout = int(args[1]) if len(args) > 1 else 30
445
+ except ValueError:
446
+ result = {"error": f"timeout must be an integer number of seconds, got {args[1]!r}"}
447
+ print(json.dumps(result, indent=2))
448
+ sys.exit(1)
449
+
450
+ result = recalc(filename, timeout, force=force)
451
+ print(json.dumps(result, indent=2))
452
+ sys.exit(1 if "error" in result else 0)
453
+
454
+
455
+ if __name__ == "__main__":
456
+ main()