robert 2.2.0__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 (261) hide show
  1. robert/__init__.py +9 -0
  2. robert/__main__.py +20 -0
  3. robert/_version.py +3 -0
  4. robert/api.py +646 -0
  5. robert/aqme.py +280 -0
  6. robert/argument_parser.py +98 -0
  7. robert/checkml.py +433 -0
  8. robert/checkml_score.py +50 -0
  9. robert/curate.py +217 -0
  10. robert/evaluate_bot_retrieval.py +125 -0
  11. robert/evaluate_bot_support.py +102 -0
  12. robert/evaluate_workflow_summaries.py +87 -0
  13. robert/export_bot_docs_knowledge.py +1632 -0
  14. robert/generate.py +249 -0
  15. robert/generate_utils.py +311 -0
  16. robert/gui_easyrob/__init__.py +0 -0
  17. robert/gui_easyrob/assets/gif_easyrob.gif +0 -0
  18. robert/gui_easyrob/bot/__init__.py +47 -0
  19. robert/gui_easyrob/bot/answer_metadata.py +198 -0
  20. robert/gui_easyrob/bot/bot_context.py +679 -0
  21. robert/gui_easyrob/bot/bot_engine.py +1100 -0
  22. robert/gui_easyrob/bot/bot_panel.py +1231 -0
  23. robert/gui_easyrob/bot/bot_rag.py +1178 -0
  24. robert/gui_easyrob/bot/bot_window.py +39 -0
  25. robert/gui_easyrob/bot/bot_worker.py +149 -0
  26. robert/gui_easyrob/bot/credential_store.py +143 -0
  27. robert/gui_easyrob/bot/error_parser.py +105 -0
  28. robert/gui_easyrob/bot/evidence_policy.py +164 -0
  29. robert/gui_easyrob/bot/heuristics.py +859 -0
  30. robert/gui_easyrob/bot/icons.py +56 -0
  31. robert/gui_easyrob/bot/input_csv_audit.py +212 -0
  32. robert/gui_easyrob/bot/knowledge/aqme_context.json +5907 -0
  33. robert/gui_easyrob/bot/knowledge/robert_context.json +4817 -0
  34. robert/gui_easyrob/bot/knowledge/ui_context.json +8293 -0
  35. robert/gui_easyrob/bot/knowledge_schema.py +1252 -0
  36. robert/gui_easyrob/bot/knowledge_sources/aqme_user_guidance.json +442 -0
  37. robert/gui_easyrob/bot/knowledge_sources/coverage_manifest.json +95 -0
  38. robert/gui_easyrob/bot/knowledge_sources/robert_user_guidance.json +471 -0
  39. robert/gui_easyrob/bot/knowledge_sources/ui_user_guidance.json +1312 -0
  40. robert/gui_easyrob/bot/llm_providers.py +1573 -0
  41. robert/gui_easyrob/bot/online_docs.py +105 -0
  42. robert/gui_easyrob/bot/prompt_policy.py +575 -0
  43. robert/gui_easyrob/bot/question_intent.py +562 -0
  44. robert/gui_easyrob/bot/response_quality.py +104 -0
  45. robert/gui_easyrob/bot/result_insights.py +225 -0
  46. robert/gui_easyrob/bot/token_usage.py +75 -0
  47. robert/gui_easyrob/bot/workflow_results.py +1396 -0
  48. robert/gui_easyrob/checkml_launcher.py +15 -0
  49. robert/gui_easyrob/easyrob.py +29 -0
  50. robert/gui_easyrob/easyrob_launcher.py +113 -0
  51. robert/gui_easyrob/main/__init__.py +9 -0
  52. robert/gui_easyrob/main/window.py +5152 -0
  53. robert/gui_easyrob/result_navigation.py +14 -0
  54. robert/gui_easyrob/tabs/__init__.py +23 -0
  55. robert/gui_easyrob/tabs/advanced_options.py +370 -0
  56. robert/gui_easyrob/tabs/aqme.py +1234 -0
  57. robert/gui_easyrob/tabs/checkml.py +898 -0
  58. robert/gui_easyrob/tabs/images.py +427 -0
  59. robert/gui_easyrob/tabs/interactive_predictions.py +555 -0
  60. robert/gui_easyrob/tabs/molssi.py +447 -0
  61. robert/gui_easyrob/tabs/predictions.py +484 -0
  62. robert/gui_easyrob/tabs/result_catalog.py +170 -0
  63. robert/gui_easyrob/tabs/results.py +490 -0
  64. robert/gui_easyrob/tabs/results_workspace.py +120 -0
  65. robert/gui_easyrob/test_bot_input_csv_audit.py +152 -0
  66. robert/gui_easyrob/test_bot_question_routing.py +383 -0
  67. robert/gui_easyrob/test_bot_result_analysis.py +356 -0
  68. robert/gui_easyrob/test_bot_retrieval_evaluation.py +110 -0
  69. robert/gui_easyrob/test_bot_ui_integration.py +278 -0
  70. robert/gui_easyrob/test_checkml_app_mode.py +124 -0
  71. robert/gui_easyrob/test_checkml_completion.py +57 -0
  72. robert/gui_easyrob/test_checkml_defaults.py +37 -0
  73. robert/gui_easyrob/test_checkml_result_summary.py +113 -0
  74. robert/gui_easyrob/test_checkml_web_mode.py +57 -0
  75. robert/gui_easyrob/test_dialog_layout.py +33 -0
  76. robert/gui_easyrob/test_gui_bot_regressions.py +320 -0
  77. robert/gui_easyrob/test_molssi_auto.py +569 -0
  78. robert/gui_easyrob/test_tutorial_view.py +215 -0
  79. robert/gui_easyrob/tutorials/check_model.md +25 -0
  80. robert/gui_easyrob/tutorials/chemdraw.md +49 -0
  81. robert/gui_easyrob/tutorials/csv.md +53 -0
  82. robert/gui_easyrob/tutorials/descriptors.md +21 -0
  83. robert/gui_easyrob/tutorials/overview.md +65 -0
  84. robert/gui_easyrob/tutorials/predictions.md +25 -0
  85. robert/gui_easyrob/tutorials/robbot.md +29 -0
  86. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_1.png +0 -0
  87. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_2.png +0 -0
  88. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_3.png +0 -0
  89. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_4.png +0 -0
  90. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_5.png +0 -0
  91. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_6.png +0 -0
  92. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_7.png +0 -0
  93. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_1.png +0 -0
  94. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_10.png +0 -0
  95. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_11.png +0 -0
  96. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_12.png +0 -0
  97. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_13.png +0 -0
  98. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_2.png +0 -0
  99. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_3.png +0 -0
  100. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_4.png +0 -0
  101. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_5.png +0 -0
  102. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_6.png +0 -0
  103. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_7.png +0 -0
  104. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_8.png +0 -0
  105. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_9.png +0 -0
  106. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1.png +0 -0
  107. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_1.png +0 -0
  108. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_2.png +0 -0
  109. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_3.png +0 -0
  110. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_4.png +0 -0
  111. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_5.png +0 -0
  112. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_2.png +0 -0
  113. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_3.png +0 -0
  114. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_4.png +0 -0
  115. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_5.png +0 -0
  116. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_6.png +0 -0
  117. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_7.png +0 -0
  118. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_8.png +0 -0
  119. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_9.png +0 -0
  120. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_1.png +0 -0
  121. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_2.png +0 -0
  122. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_3.png +0 -0
  123. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_4.png +0 -0
  124. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_5.png +0 -0
  125. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_6.png +0 -0
  126. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1.png +0 -0
  127. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_1.png +0 -0
  128. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_2.png +0 -0
  129. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_3.png +0 -0
  130. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_4.png +0 -0
  131. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_5.png +0 -0
  132. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_6.png +0 -0
  133. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_7.png +0 -0
  134. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_8.png +0 -0
  135. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_2.png +0 -0
  136. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_3.png +0 -0
  137. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_4.png +0 -0
  138. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5.png +0 -0
  139. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_1.png +0 -0
  140. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_2.png +0 -0
  141. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_3.png +0 -0
  142. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_6.png +0 -0
  143. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1.png +0 -0
  144. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1_1.png +0 -0
  145. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_2.png +0 -0
  146. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_3.png +0 -0
  147. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_4.png +0 -0
  148. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_5.png +0 -0
  149. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_6.png +0 -0
  150. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_1.png +0 -0
  151. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_2.png +0 -0
  152. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_3.png +0 -0
  153. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_4.png +0 -0
  154. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_5.png +0 -0
  155. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_6.png +0 -0
  156. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_7.png +0 -0
  157. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_8.png +0 -0
  158. robert/gui_easyrob/utils/__init__.py +0 -0
  159. robert/gui_easyrob/utils/aqme_utils.py +238 -0
  160. robert/gui_easyrob/utils/molssi_utils.py +584 -0
  161. robert/gui_easyrob/utils/predictions_utils.py +985 -0
  162. robert/gui_easyrob/utils/utils_gui.py +738 -0
  163. robert/gui_easyrob/version.py +68 -0
  164. robert/gui_easyrob/web/app.css +484 -0
  165. robert/gui_easyrob/web/app.html +134 -0
  166. robert/gui_easyrob/web/app.js +764 -0
  167. robert/gui_easyrob/web/checkml_brand.png +0 -0
  168. robert/gui_easyrob/web/easyrob_background.gif +0 -0
  169. robert/gui_easyrob/web/easyrob_background.png +0 -0
  170. robert/gui_easyrob/web/images.css +89 -0
  171. robert/gui_easyrob/web/images.html +39 -0
  172. robert/gui_easyrob/web/images.js +101 -0
  173. robert/gui_easyrob/web/results.js +499 -0
  174. robert/gui_easyrob/web/robert_brand.png +0 -0
  175. robert/gui_easyrob/web_dialogs.py +64 -0
  176. robert/gui_easyrob/web_results.py +253 -0
  177. robert/gui_easyrob/web_shell.py +684 -0
  178. robert/gui_easyrob/workflow_progress.py +89 -0
  179. robert/gui_easyrob/workflow_run_lock.py +27 -0
  180. robert/icons/CheckML_icon.png +0 -0
  181. robert/icons/Robert_icon.png +0 -0
  182. robert/icons/Robert_logo.jpg +0 -0
  183. robert/icons/Robert_logo_transparent.png +0 -0
  184. robert/icons/documentation_icon.png +0 -0
  185. robert/icons/info_icon.png +0 -0
  186. robert/icons/pdf_icon.png +0 -0
  187. robert/icons/play_icon.png +0 -0
  188. robert/icons/stop_icon.png +0 -0
  189. robert/icons/youtube_icon.ico +0 -0
  190. robert/predict.py +193 -0
  191. robert/predict_utils.py +410 -0
  192. robert/report/CheckML_logo.jpg +0 -0
  193. robert/report/GENERATE.png +0 -0
  194. robert/report/Robert_icon.ico +0 -0
  195. robert/report/Robert_logo.jpg +0 -0
  196. robert/report/Robert_logo1.jpg +0 -0
  197. robert/report/abbrev.png +0 -0
  198. robert/report/adv_anal.png +0 -0
  199. robert/report/checkml_pass.svg +3 -0
  200. robert/report/checkml_unclear.svg +3 -0
  201. robert/report/checkml_warning.svg +3 -0
  202. robert/report/features.png +0 -0
  203. robert/report/outliers.png +0 -0
  204. robert/report/pred.png +0 -0
  205. robert/report/repro.png +0 -0
  206. robert/report/robust_x.png +0 -0
  207. robert/report/robust_y_high.png +0 -0
  208. robert/report/robust_y_low.png +0 -0
  209. robert/report/score.png +0 -0
  210. robert/report/score_0.jpg +0 -0
  211. robert/report/score_1.jpg +0 -0
  212. robert/report/score_10.jpg +0 -0
  213. robert/report/score_2.jpg +0 -0
  214. robert/report/score_3.jpg +0 -0
  215. robert/report/score_4.jpg +0 -0
  216. robert/report/score_5.jpg +0 -0
  217. robert/report/score_6.jpg +0 -0
  218. robert/report/score_7.jpg +0 -0
  219. robert/report/score_8.jpg +0 -0
  220. robert/report/score_9.jpg +0 -0
  221. robert/report/score_gray_0.jpg +0 -0
  222. robert/report/score_gray_1.jpg +0 -0
  223. robert/report/score_gray_10.jpg +0 -0
  224. robert/report/score_gray_2.jpg +0 -0
  225. robert/report/score_gray_3.jpg +0 -0
  226. robert/report/score_gray_4.jpg +0 -0
  227. robert/report/score_gray_5.jpg +0 -0
  228. robert/report/score_gray_6.jpg +0 -0
  229. robert/report/score_gray_7.jpg +0 -0
  230. robert/report/score_gray_8.jpg +0 -0
  231. robert/report/score_gray_9.jpg +0 -0
  232. robert/report/score_w_1_0.jpg +0 -0
  233. robert/report/score_w_1_1.jpg +0 -0
  234. robert/report/score_w_2_0.jpg +0 -0
  235. robert/report/score_w_2_1.jpg +0 -0
  236. robert/report/score_w_2_2.jpg +0 -0
  237. robert/report/score_w_2_gray_0.jpg +0 -0
  238. robert/report/score_w_2_gray_1.jpg +0 -0
  239. robert/report/score_w_2_gray_2.jpg +0 -0
  240. robert/report/score_w_3_0.jpg +0 -0
  241. robert/report/score_w_3_1.jpg +0 -0
  242. robert/report/score_w_3_2.jpg +0 -0
  243. robert/report/score_w_3_3.jpg +0 -0
  244. robert/report/score_w_4_0.jpg +0 -0
  245. robert/report/score_w_4_1.JPG +0 -0
  246. robert/report/score_w_4_2.jpg +0 -0
  247. robert/report/score_w_4_3.jpg +0 -0
  248. robert/report/score_w_4_4.jpg +0 -0
  249. robert/report/transpa.png +0 -0
  250. robert/report/y_distrib.png +0 -0
  251. robert/report.py +2880 -0
  252. robert/report_utils.py +2270 -0
  253. robert/robert.py +181 -0
  254. robert/utils.py +4763 -0
  255. robert/verify.py +606 -0
  256. robert-2.2.0.dist-info/METADATA +55 -0
  257. robert-2.2.0.dist-info/RECORD +261 -0
  258. robert-2.2.0.dist-info/WHEEL +5 -0
  259. robert-2.2.0.dist-info/entry_points.txt +3 -0
  260. robert-2.2.0.dist-info/licenses/LICENSE +21 -0
  261. robert-2.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1632 @@
1
+ """Export ROBERT and AQME docs into packaged JSON knowledge chunks for the bot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import ast
8
+ import hashlib
9
+ import math
10
+ import tempfile
11
+ import unicodedata
12
+ import warnings
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Mapping
16
+
17
+ from gui_easyrob.bot.knowledge_schema import (
18
+ CONTEXT_SECTIONS,
19
+ CONTEXT_VERSION as SCHEMA_CONTEXT_VERSION,
20
+ DOMAINS,
21
+ SCHEMA_VERSION,
22
+ KnowledgeLoadIssue,
23
+ KnowledgeValidationError,
24
+ validate_context_set,
25
+ validate_guidance_source_set,
26
+ )
27
+
28
+
29
+ ROOT_DIR = Path(__file__).resolve().parent
30
+ KNOWLEDGE_DIR = ROOT_DIR / "gui_easyrob" / "bot" / "knowledge"
31
+ ROBERT_DOCS_DIR = ROOT_DIR.parent / "docs"
32
+ AQME_DOCS_DIR = ROOT_DIR.parent.parent / "aqme" / "docs"
33
+ ROBERT_CODE_DIR = ROOT_DIR
34
+ EASYROB_CODE_DIR = ROOT_DIR / "gui_easyrob"
35
+ AQME_CODE_DIR = ROOT_DIR.parent.parent / "aqme" / "aqme"
36
+ HEADING_CHARS = {"=", "-", "~", "^", '"'}
37
+ GENERIC_SECTION_TITLES = {"parameters", "parameter", "examples", "notes", "options"}
38
+ SKIP_SECTION_TITLE_PARTS = {
39
+ "running the tests",
40
+ "tests",
41
+ "developers",
42
+ "development",
43
+ "how to cite",
44
+ "license",
45
+ "special acknowledgments",
46
+ "acknowledgments",
47
+ }
48
+ KNOWN_MODULES = {
49
+ "AQME",
50
+ "CURATE",
51
+ "GENERATE",
52
+ "PREDICT",
53
+ "VERIFY",
54
+ "REPORT",
55
+ "QDESCP",
56
+ "CSEARCH",
57
+ "CMIN",
58
+ "QCORR",
59
+ "QPREP",
60
+ }
61
+ CODE_RELEVANCE_TERMS = {
62
+ "aqme",
63
+ "descriptor",
64
+ "descriptors",
65
+ "error",
66
+ "extrapolation",
67
+ "mae",
68
+ "metric",
69
+ "metrics",
70
+ "model",
71
+ "models",
72
+ "parameter",
73
+ "parameters",
74
+ "pfi",
75
+ "prediction",
76
+ "predictions",
77
+ "r2",
78
+ "report",
79
+ "rmse",
80
+ "warning",
81
+ }
82
+ CONTEXT_VERSION = SCHEMA_CONTEXT_VERSION
83
+ UI_TABS = {"ROBERT", "Advanced Options", "Reports", "Predictions", "Images", "MolSSI Databases"}
84
+ FINAL_CONTEXT_FILENAMES = {
85
+ "robert_context.json",
86
+ "aqme_context.json",
87
+ "ui_context.json",
88
+ }
89
+ LEGACY_KNOWLEDGE_FILENAMES = {
90
+ "robert_docs.json",
91
+ "aqme_docs.json",
92
+ "robert_code_docstrings.json",
93
+ "easyrob_code_docstrings.json",
94
+ "aqme_code_docstrings.json",
95
+ "curated_overrides.json",
96
+ "workflow_requirements.json",
97
+ "workflow_outputs.json",
98
+ "troubleshooting_runtime.json",
99
+ "troubleshooting_inputs.json",
100
+ "robert_backend_logic.json",
101
+ "molssi_integration.json",
102
+ "ml_operational_concepts.json",
103
+ "gui_overview.json",
104
+ "aqme_integration.json",
105
+ }
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class ExportSources:
110
+ robert_docs: Path
111
+ aqme_docs: Path
112
+ robert_code: Path
113
+ easyrob_code: Path
114
+ aqme_code: Path
115
+ tutorials: Path
116
+ user_guidance: Path
117
+
118
+
119
+ DEFAULT_EXPORT_SOURCES = ExportSources(
120
+ robert_docs=ROBERT_DOCS_DIR,
121
+ aqme_docs=AQME_DOCS_DIR,
122
+ robert_code=ROBERT_CODE_DIR,
123
+ easyrob_code=EASYROB_CODE_DIR,
124
+ aqme_code=AQME_CODE_DIR,
125
+ tutorials=EASYROB_CODE_DIR / "tutorials",
126
+ user_guidance=ROOT_DIR / "gui_easyrob" / "bot" / "knowledge_sources",
127
+ )
128
+ TRUSTED_COVERAGE_MANIFEST = (
129
+ ROOT_DIR
130
+ / "gui_easyrob"
131
+ / "bot"
132
+ / "knowledge_sources"
133
+ / "coverage_manifest.json"
134
+ )
135
+
136
+
137
+ def clean_text(text: str) -> str:
138
+ cleaned = text.replace("\r\n", "\n").replace("\r", "\n")
139
+ cleaned = re.sub(r":[a-zA-Z0-9_-]+:`([^`]+)`", r"\1", cleaned)
140
+ cleaned = re.sub(r"`([^`]+)`_?", r"\1", cleaned)
141
+ cleaned = re.sub(r"\*\*([^*]+)\*\*", r"\1", cleaned)
142
+ cleaned = re.sub(r"\*([^*]+)\*", r"\1", cleaned)
143
+ cleaned = re.sub(r"\|([^|]+)\|", r"\1", cleaned)
144
+ kept_lines: list[str] = []
145
+ skip_indented_block = False
146
+ block_indent = 0
147
+ skip_developer_section = False
148
+ developer_indent = 0
149
+ skip_traceback = False
150
+ traceback_indent = 0
151
+ skip_exception_group = False
152
+ for line in cleaned.splitlines():
153
+ stripped = line.strip()
154
+ indent = len(line) - len(line.lstrip())
155
+ if skip_exception_group:
156
+ if re.match(r"^\+-{5,}\+?$", stripped):
157
+ skip_exception_group = False
158
+ continue
159
+ if skip_traceback:
160
+ # A Python traceback ends with an exception summary dedented to the
161
+ # traceback marker's level. Using structure rather than class-name
162
+ # suffixes supports arbitrary user-defined exception names.
163
+ if stripped and indent <= traceback_indent:
164
+ skip_traceback = False
165
+ continue
166
+ if not stripped:
167
+ skip_traceback = False
168
+ kept_lines.append("")
169
+ continue
170
+ if stripped in {
171
+ "During handling of the above exception, another exception occurred:",
172
+ "The above exception was the direct cause of the following exception:",
173
+ }:
174
+ continue
175
+ if skip_developer_section:
176
+ if not stripped or indent > developer_indent:
177
+ continue
178
+ skip_developer_section = False
179
+ if re.match(
180
+ r"^(?:args|arguments|attributes|examples|returns|raises|yields):\s*$",
181
+ stripped,
182
+ re.IGNORECASE,
183
+ ):
184
+ skip_developer_section = True
185
+ developer_indent = indent
186
+ continue
187
+ if stripped.casefold().startswith("traceback (most recent call last):"):
188
+ skip_traceback = True
189
+ traceback_indent = indent
190
+ continue
191
+ group_marker = stripped.lstrip("+| ")
192
+ if group_marker.casefold().startswith(
193
+ "exception group traceback (most recent call last):"
194
+ ):
195
+ skip_exception_group = True
196
+ continue
197
+ if skip_indented_block:
198
+ if not stripped or indent > block_indent:
199
+ continue
200
+ skip_indented_block = False
201
+ if not stripped:
202
+ kept_lines.append("")
203
+ continue
204
+ directive = re.match(r"^\.\.\s+(?:\S+\s+)?([a-zA-Z0-9_-]+)::", stripped)
205
+ if directive:
206
+ if directive.group(1).lower() in {"code", "code-block", "raw"}:
207
+ skip_indented_block = True
208
+ block_indent = indent
209
+ continue
210
+ if stripped.startswith(".. "):
211
+ continue
212
+ if re.match(r"^:[a-zA-Z0-9_-]+(?:\s+[^:]+)?:(?:\s|$)", stripped):
213
+ continue
214
+ lowered = stripped.lower()
215
+ if lowered.startswith("<input"):
216
+ continue
217
+ if any(
218
+ marker in lowered
219
+ for marker in (
220
+ "badge.svg",
221
+ "shields.io/",
222
+ "travis-ci.",
223
+ "codecov.io/",
224
+ "actions/workflows/",
225
+ "build status",
226
+ )
227
+ ):
228
+ continue
229
+ if set(stripped) <= {"=", "-", "+", "~", "^"}:
230
+ continue
231
+ without_html = re.sub(
232
+ r"</?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?/?>",
233
+ "",
234
+ line,
235
+ )
236
+ if without_html.strip():
237
+ kept_lines.append(without_html)
238
+ cleaned = "\n".join(kept_lines)
239
+ cleaned = re.sub(r"\.{2,}\s+", ". ", cleaned)
240
+ cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
241
+ cleaned = re.sub(r"[ \t]+", " ", cleaned)
242
+ return cleaned.strip()
243
+
244
+
245
+ def slugify(value: str) -> str:
246
+ slug = re.sub(r"[^a-z0-9]+", "-", str(value or "").lower()).strip("-")
247
+ return slug or "chunk"
248
+
249
+
250
+ def stable_chunk_id(source_name: str, source_file: str, identity: str) -> str:
251
+ normalized_file = Path(source_file.replace("\\", "/")).as_posix().lower()
252
+ raw_identity = f"{source_name}:{normalized_file}:{identity}"
253
+ digest = hashlib.sha1(raw_identity.encode("utf-8")).hexdigest()[:8]
254
+ path_label = slugify(str(Path(normalized_file).with_suffix("")))
255
+ private_identity = ".".join(
256
+ f"private-{part[1:]}" if part.startswith("_") else part
257
+ for part in identity.split(".")
258
+ )
259
+ return "-".join(
260
+ (
261
+ slugify(source_name),
262
+ path_label,
263
+ slugify(private_identity),
264
+ digest,
265
+ )
266
+ )
267
+
268
+
269
+ def iter_documented_nodes(tree: ast.AST) -> list[tuple[str, ast.AST]]:
270
+ nodes: list[tuple[str, ast.AST]] = [("module", tree)]
271
+
272
+ def visit(body: list[ast.stmt], prefix: str = "") -> None:
273
+ occurrences: dict[str, int] = {}
274
+
275
+ def visit_node(node: ast.AST) -> None:
276
+ if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
277
+ occurrences[node.name] = occurrences.get(node.name, 0) + 1
278
+ occurrence = occurrences[node.name]
279
+ local_identity = node.name if occurrence == 1 else f"{node.name}#{occurrence}"
280
+ qualified = f"{prefix}.{local_identity}" if prefix else local_identity
281
+ nodes.append((qualified, node))
282
+ visit(getattr(node, "body", []), qualified)
283
+ return
284
+ for child in ast.iter_child_nodes(node):
285
+ visit_node(child)
286
+
287
+ for node in body:
288
+ visit_node(node)
289
+
290
+ visit(getattr(tree, "body", []))
291
+ return nodes
292
+
293
+
294
+ def should_skip_section(title: str, body: str) -> bool:
295
+ lowered_title = title.strip().lower()
296
+ lowered_body = body.strip().lower()
297
+ if any(part == lowered_title or part in lowered_title for part in SKIP_SECTION_TITLE_PARTS):
298
+ return True
299
+ if "pytest" in lowered_body or "tests-end" in lowered_body:
300
+ return True
301
+ if not lowered_body:
302
+ return True
303
+ return False
304
+
305
+
306
+ def split_rst_sections(text: str) -> list[tuple[str, str]]:
307
+ lines = text.splitlines()
308
+ sections: list[tuple[str, str]] = []
309
+ current_title = ""
310
+ current_body: list[str] = []
311
+ index = 0
312
+
313
+ while index < len(lines):
314
+ line = lines[index]
315
+ next_line = lines[index + 1] if index + 1 < len(lines) else ""
316
+ stripped = line.strip()
317
+ next_stripped = next_line.strip()
318
+ if stripped and next_stripped and set(next_stripped) <= HEADING_CHARS and len(next_stripped) >= len(stripped):
319
+ if current_title or "".join(current_body).strip():
320
+ sections.append((current_title or "Overview", clean_text("\n".join(current_body))))
321
+ current_title = stripped
322
+ current_body = []
323
+ index += 2
324
+ continue
325
+ current_body.append(line)
326
+ index += 1
327
+
328
+ if current_title or "".join(current_body).strip():
329
+ sections.append((current_title or "Overview", clean_text("\n".join(current_body))))
330
+ return [(title, body) for title, body in sections if title or body]
331
+
332
+
333
+ def infer_module(source_file: str, title: str, program: str, fallback_module: str = "") -> str:
334
+ candidates = [title.strip().upper(), fallback_module.strip().upper()]
335
+ candidates.extend(part.upper() for part in Path(source_file).parts)
336
+ for candidate in candidates:
337
+ matches = [module for module in KNOWN_MODULES if module in candidate]
338
+ if matches:
339
+ return min(matches, key=lambda module: (candidate.index(module), module))
340
+ return fallback_module or program.upper()
341
+
342
+
343
+ def infer_kind(source_file: str, title: str, body: str) -> str:
344
+ lowered = f"{source_file} {title} {body}".lower()
345
+ title_lowered = title.strip().lower()
346
+ if title_lowered in {"parameters", "parameter"} or " parameter " in f" {lowered} ":
347
+ return "parameter"
348
+ if any(token in lowered for token in ("rmse", "mae", "r2", "score", "metric", "report", "reproducibility")):
349
+ return "results"
350
+ if any(token in lowered for token in ("file", "folder", "output", "pdf", "csv", "image", "plot")):
351
+ return "output"
352
+ if "workflow" in lowered or "step" in lowered or "before running" in lowered:
353
+ return "workflow"
354
+ if "error" in lowered or "warning" in lowered or "missing" in lowered or "required" in lowered:
355
+ return "diagnostic"
356
+ if any(part in lowered for part in ("tutorial", "quickstart", "example", "installation")):
357
+ return "tutorial"
358
+ return "concept"
359
+
360
+
361
+ def infer_tab(program: str, source_file: str, kind: str) -> str:
362
+ lowered = source_file.lower()
363
+ if "report" in lowered or kind == "results":
364
+ return "Reports"
365
+ if "predict" in lowered:
366
+ return "Predictions"
367
+ if program == "AQME":
368
+ return "AQME"
369
+ if kind == "parameter":
370
+ return "Advanced Options"
371
+ return "ROBERT"
372
+
373
+
374
+ def build_question_patterns(title: str, module: str, kind: str) -> list[str]:
375
+ title_lower = title.strip().lower()
376
+ patterns = [title_lower] if title_lower else []
377
+ if module:
378
+ module_lower = module.lower()
379
+ if kind == "parameter":
380
+ patterns.append(f"what does {title_lower} do")
381
+ patterns.append(f"what is {title_lower}")
382
+ elif kind == "results":
383
+ patterns.append(f"what does {title_lower} mean")
384
+ patterns.append(f"how should i interpret {title_lower}")
385
+ else:
386
+ patterns.append(f"what is {module_lower}")
387
+ patterns.append(f"how does {module_lower} work")
388
+ return [pattern for pattern in patterns if pattern]
389
+
390
+
391
+ def infer_priority(source_file: str, kind: str) -> float:
392
+ lowered = source_file.lower()
393
+ if kind in {"parameter", "results"}:
394
+ return 0.95
395
+ if "tutorial" in lowered or "quickstart" in lowered or "modules" in lowered:
396
+ return 0.85
397
+ if "example" in lowered:
398
+ return 0.7
399
+ if "api" in lowered:
400
+ return 0.45
401
+ return 0.6
402
+
403
+
404
+ def is_user_relevant_python_doc(path: str, name: str, docstring: str) -> bool:
405
+ terms = set(re.findall(r"[a-z0-9_]+", f"{path} {name} {docstring}".lower()))
406
+ if terms & CODE_RELEVANCE_TERMS:
407
+ return True
408
+ return any(term in f"{path} {name} {docstring}".lower() for term in ("r squared", "mean absolute error"))
409
+
410
+
411
+ def infer_kind_from_python_doc(path: str, name: str, docstring: str) -> str:
412
+ lowered = f"{path} {name} {docstring}".lower()
413
+ if any(term in lowered for term in ("rmse", "mae", "r2", "r squared", "metric", "prediction", "extrapolation")):
414
+ return "results"
415
+ if any(term in lowered for term in ("parameter", "option", "setting", "threshold", "pfi")):
416
+ return "parameter"
417
+ if any(term in lowered for term in ("error", "warning", "failed", "missing", "identical")):
418
+ return "diagnostic"
419
+ if any(term in lowered for term in ("report", "output", "pdf", "csv", "image")):
420
+ return "output"
421
+ return "concept"
422
+
423
+
424
+ def build_chunks_from_python_source(
425
+ text: str,
426
+ source_name: str,
427
+ source_file: str,
428
+ program: str,
429
+ ) -> list[dict[str, object]]:
430
+ try:
431
+ with warnings.catch_warnings():
432
+ warnings.simplefilter("ignore", SyntaxWarning)
433
+ tree = ast.parse(text)
434
+ except SyntaxError:
435
+ return []
436
+
437
+ chunks: list[dict[str, object]] = []
438
+ for identity, node in iter_documented_nodes(tree):
439
+ docstring = ast.get_docstring(node, clean=True)
440
+ name = identity.rsplit(".", 1)[-1]
441
+ if not docstring or not is_user_relevant_python_doc(source_file, name, docstring):
442
+ continue
443
+ kind = infer_kind_from_python_doc(source_file, name, docstring)
444
+ module = infer_module(source_file, name, program)
445
+ doc_text = clean_text(docstring)
446
+ keyword_terms = sorted(
447
+ term for term in CODE_RELEVANCE_TERMS
448
+ if term in f"{source_file} {name} {doc_text}".lower()
449
+ )
450
+ title = name.replace("_", " ").strip()
451
+ chunk_id = stable_chunk_id(source_name, source_file, identity)
452
+ chunks.append(
453
+ {
454
+ "id": chunk_id,
455
+ "source": source_name,
456
+ "source_file": source_file.replace("\\", "/"),
457
+ "program": program,
458
+ "module": module,
459
+ "kind": kind,
460
+ "topic": kind,
461
+ "tab": infer_tab(program, source_file, kind),
462
+ "title": title,
463
+ "question_patterns": build_question_patterns(title, module, kind),
464
+ "keywords": keyword_terms + [title, module.lower(), kind],
465
+ "text": doc_text,
466
+ "priority": 0.9 if kind in {"results", "parameter", "diagnostic"} else 0.7,
467
+ }
468
+ )
469
+ return chunks
470
+
471
+
472
+ def build_chunks_from_rst_text(
473
+ text: str,
474
+ source_name: str,
475
+ source_file: str,
476
+ program: str,
477
+ ) -> list[dict[str, object]]:
478
+ sections = split_rst_sections(text)
479
+ if not sections:
480
+ return []
481
+
482
+ fallback_module = infer_module(source_file, sections[0][0], program)
483
+ chunks: list[dict[str, object]] = []
484
+ title_occurrences: dict[str, int] = {}
485
+ for title, body in sections:
486
+ if should_skip_section(title, body):
487
+ continue
488
+ if not body:
489
+ continue
490
+ module = infer_module(source_file, title, program, fallback_module=fallback_module)
491
+ kind = infer_kind(source_file, title, body)
492
+ title_value = title if title.strip().lower() not in GENERIC_SECTION_TITLES else f"{module} {title}".strip()
493
+ canonical_title = re.sub(r"\s+", " ", title.strip()).casefold()
494
+ title_occurrences[canonical_title] = title_occurrences.get(canonical_title, 0) + 1
495
+ identity = f"{canonical_title}#{title_occurrences[canonical_title]}"
496
+ chunk_id = stable_chunk_id(source_name, source_file, identity)
497
+ chunks.append(
498
+ {
499
+ "id": chunk_id,
500
+ "source": source_name,
501
+ "source_file": source_file.replace("\\", "/"),
502
+ "program": program,
503
+ "module": module,
504
+ "kind": kind,
505
+ "topic": kind,
506
+ "tab": infer_tab(program, source_file, kind),
507
+ "title": title_value,
508
+ "question_patterns": build_question_patterns(title_value, module, kind),
509
+ "keywords": [module.lower(), kind, title_value.lower()],
510
+ "text": body,
511
+ "priority": infer_priority(source_file, kind),
512
+ }
513
+ )
514
+ return chunks
515
+
516
+
517
+ def iter_doc_files(base_dir: Path, include_prefixes: tuple[str, ...]) -> list[Path]:
518
+ files: list[Path] = []
519
+ for path in base_dir.rglob("*"):
520
+ if not path.is_file():
521
+ continue
522
+ if path.suffix.lower() not in {".rst", ".md"}:
523
+ continue
524
+ relative = path.relative_to(base_dir).as_posix()
525
+ if relative.startswith("API/") or relative.startswith("Misc/"):
526
+ continue
527
+ if include_prefixes and not any(relative.startswith(prefix) for prefix in include_prefixes):
528
+ continue
529
+ files.append(path)
530
+ return sorted(files)
531
+
532
+
533
+ def export_tree(base_dir: Path, source_name: str, program: str, include_prefixes: tuple[str, ...]) -> list[dict[str, object]]:
534
+ chunks: list[dict[str, object]] = []
535
+ for path in iter_doc_files(base_dir, include_prefixes):
536
+ text = path.read_text(encoding="utf-8", errors="ignore")
537
+ chunks.extend(
538
+ build_chunks_from_rst_text(
539
+ text=text,
540
+ source_name=source_name,
541
+ source_file=path.relative_to(base_dir).as_posix(),
542
+ program=program,
543
+ )
544
+ )
545
+ return chunks
546
+
547
+
548
+ def iter_python_files(base_dir: Path) -> list[Path]:
549
+ if not base_dir.exists():
550
+ return []
551
+ skipped_parts = {"__pycache__", ".git", ".pytest_cache", "tests", "docs", "knowledge"}
552
+ files: list[Path] = []
553
+ for path in base_dir.rglob("*.py"):
554
+ relative_parts = set(path.relative_to(base_dir).parts)
555
+ if relative_parts & skipped_parts:
556
+ continue
557
+ files.append(path)
558
+ return sorted(files)
559
+
560
+
561
+ def export_python_tree(base_dir: Path, source_name: str, program: str) -> list[dict[str, object]]:
562
+ chunks: list[dict[str, object]] = []
563
+ for path in iter_python_files(base_dir):
564
+ source_file = path.relative_to(base_dir).as_posix()
565
+ text = path.read_text(encoding="utf-8", errors="ignore")
566
+ chunks.extend(
567
+ build_chunks_from_python_source(
568
+ text=text,
569
+ source_name=source_name,
570
+ source_file=source_file,
571
+ program=program,
572
+ )
573
+ )
574
+ return chunks
575
+
576
+
577
+ def build_curated_overrides() -> list[dict[str, object]]:
578
+ return [
579
+ {
580
+ "id": "robert-overview-curated",
581
+ "source": "curated_overrides",
582
+ "source_file": "manual",
583
+ "program": "ROBERT",
584
+ "module": "ROBERT",
585
+ "kind": "concept",
586
+ "topic": "concept",
587
+ "tab": "ROBERT",
588
+ "title": "ROBERT overview",
589
+ "question_patterns": [
590
+ "what is robert",
591
+ "what does robert do",
592
+ "how does robert work",
593
+ ],
594
+ "keywords": ["robert", "machine learning", "workflow", "models", "curate", "generate", "predict"],
595
+ "text": "ROBERT is the main machine-learning workflow in easyROB. It is used to curate datasets, train and compare models, validate them, run predictions, and assemble result reports once the input data are ready.",
596
+ "priority": 1.0,
597
+ },
598
+ {
599
+ "id": "easyrob-robert-vs-aqme",
600
+ "source": "curated_overrides",
601
+ "source_file": "manual",
602
+ "program": "ROBERT",
603
+ "module": "FULL_WORKFLOW",
604
+ "kind": "concept",
605
+ "topic": "concept",
606
+ "tab": "ROBERT",
607
+ "title": "ROBERT versus AQME in easyROB",
608
+ "question_patterns": [
609
+ "what is the difference between robert and aqme",
610
+ "robert vs aqme",
611
+ "is aqme the same as robert",
612
+ ],
613
+ "keywords": ["robert", "aqme", "difference", "machine learning", "descriptors", "smiles"],
614
+ "text": "In easyROB, ROBERT is the main machine-learning workflow. It handles dataset curation, model generation, validation, prediction, and reporting. AQME is a separate chemistry workflow that is only needed when you want to generate descriptors from molecular structures such as SMILES before or during the ROBERT workflow.",
615
+ "priority": 1.0,
616
+ },
617
+ {
618
+ "id": "aqme-overview",
619
+ "source": "curated_overrides",
620
+ "source_file": "manual",
621
+ "program": "AQME",
622
+ "module": "AQME",
623
+ "kind": "concept",
624
+ "topic": "concept",
625
+ "tab": "AQME",
626
+ "title": "AQME overview",
627
+ "question_patterns": [
628
+ "what is aqme",
629
+ "what does aqme do",
630
+ "how does aqme work",
631
+ ],
632
+ "keywords": ["aqme", "descriptors", "smiles", "conformers", "qdescp", "workflow"],
633
+ "text": "AQME is the chemistry workflow used by easyROB to process molecular structures and generate descriptors when the dataset starts from structure information such as SMILES. In the easyROB GUI it is mainly used before ROBERT modelling so the machine-learning workflow has descriptor columns to train on.",
634
+ "priority": 1.0,
635
+ },
636
+ {
637
+ "id": "robert-curate-stage-overview",
638
+ "source": "curated_overrides",
639
+ "source_file": "manual",
640
+ "program": "ROBERT",
641
+ "module": "CURATE",
642
+ "kind": "concept",
643
+ "topic": "concept",
644
+ "tab": "ROBERT",
645
+ "title": "CURATE stage",
646
+ "question_patterns": ["what does curate do", "what is curate", "curate stage"],
647
+ "keywords": ["curate", "dataset", "prepares", "clean", "filter", "preprocessing"],
648
+ "text": "CURATE prepares the input dataset before model generation. It checks and cleans the data, handles columns that should not be model descriptors, and produces a curated dataset that later ROBERT stages can use more reliably.",
649
+ "priority": 1.0,
650
+ },
651
+ {
652
+ "id": "robert-generate-stage-overview",
653
+ "source": "curated_overrides",
654
+ "source_file": "manual",
655
+ "program": "ROBERT",
656
+ "module": "GENERATE",
657
+ "kind": "concept",
658
+ "topic": "concept",
659
+ "tab": "ROBERT",
660
+ "title": "GENERATE stage",
661
+ "question_patterns": ["what does generate do", "what is generate", "generate stage"],
662
+ "keywords": ["generate", "trains", "models", "machine learning", "pfi", "descriptors"],
663
+ "text": "GENERATE trains ROBERT machine-learning models from the curated dataset. This is where model candidates are built and compared, including workflows with descriptor reduction such as PFI.",
664
+ "priority": 1.0,
665
+ },
666
+ {
667
+ "id": "robert-predict-stage-overview",
668
+ "source": "curated_overrides",
669
+ "source_file": "manual",
670
+ "program": "ROBERT",
671
+ "module": "PREDICT",
672
+ "kind": "concept",
673
+ "topic": "concept",
674
+ "tab": "Predictions",
675
+ "title": "PREDICT stage",
676
+ "question_patterns": ["what does predict do", "what is predict", "predict stage"],
677
+ "keywords": ["predict", "external test", "inference", "predictions", "trained model"],
678
+ "text": "PREDICT applies a trained ROBERT model to a dataset for inference, typically an external test CSV. It uses the saved model outputs and generates predicted values, usually together with uncertainty information when available.",
679
+ "priority": 1.0,
680
+ },
681
+ {
682
+ "id": "robert-verify-stage-overview",
683
+ "source": "curated_overrides",
684
+ "source_file": "manual",
685
+ "program": "ROBERT",
686
+ "module": "VERIFY",
687
+ "kind": "concept",
688
+ "topic": "concept",
689
+ "tab": "ROBERT",
690
+ "title": "VERIFY stage",
691
+ "question_patterns": ["what does verify do", "what is verify", "verify stage"],
692
+ "keywords": ["verify", "validates", "checks", "model", "robustness", "quality"],
693
+ "text": "VERIFY validates and stress-checks the modelling results after model generation. It helps assess whether the selected models look reliable before the final report is interpreted.",
694
+ "priority": 1.0,
695
+ },
696
+ {
697
+ "id": "robert-report-stage-overview",
698
+ "source": "curated_overrides",
699
+ "source_file": "manual",
700
+ "program": "ROBERT",
701
+ "module": "REPORT",
702
+ "kind": "results",
703
+ "topic": "results",
704
+ "tab": "Reports",
705
+ "title": "REPORT stage",
706
+ "question_patterns": ["what does report do", "what is report", "report stage"],
707
+ "keywords": ["report", "pdf", "ROBERT_report.pdf", "metrics", "summary", "results"],
708
+ "text": "REPORT builds the final ROBERT PDF summary. The PDF brings together the workflow settings, selected models, metrics, validation information, warnings, plots, and result interpretation material generated by the run.",
709
+ "priority": 1.0,
710
+ },
711
+ {
712
+ "id": "robert-r2-overview",
713
+ "source": "curated_overrides",
714
+ "source_file": "manual",
715
+ "program": "ROBERT",
716
+ "module": "REPORT",
717
+ "kind": "results",
718
+ "topic": "results",
719
+ "tab": "Reports",
720
+ "title": "R2 or R squared",
721
+ "question_patterns": [
722
+ "what is r2",
723
+ "what is r squared",
724
+ "what does r2 mean",
725
+ "how should i interpret r squared",
726
+ ],
727
+ "keywords": ["r2", "r squared", "coefficient of determination", "variance", "metric", "report"],
728
+ "text": "R2, also called R squared, estimates how much variance in the target values is explained by the model. Higher R2 is generally better for regression, but it must be interpreted together with RMSE, MAE, validation behavior, outliers, and external-test performance.",
729
+ "priority": 1.0,
730
+ },
731
+ {
732
+ "id": "robert-mae-overview",
733
+ "source": "curated_overrides",
734
+ "source_file": "manual",
735
+ "program": "ROBERT",
736
+ "module": "REPORT",
737
+ "kind": "results",
738
+ "topic": "results",
739
+ "tab": "Reports",
740
+ "title": "MAE",
741
+ "question_patterns": [
742
+ "what is mae",
743
+ "what does mae mean",
744
+ "how should i interpret mae",
745
+ ],
746
+ "keywords": ["mae", "mean absolute error", "prediction error", "metric", "target", "report"],
747
+ "text": "MAE means Mean Absolute Error. It is the average absolute difference between predicted and observed target values, expressed in the same units as the target. Lower MAE means smaller typical prediction errors.",
748
+ "priority": 1.0,
749
+ },
750
+ {
751
+ "id": "robert-pfi-vs-no-pfi",
752
+ "source": "curated_overrides",
753
+ "source_file": "manual",
754
+ "program": "ROBERT",
755
+ "module": "PREDICT",
756
+ "kind": "results",
757
+ "topic": "results",
758
+ "tab": "Predictions",
759
+ "title": "PFI versus No_PFI predictions",
760
+ "question_patterns": [
761
+ "what is pfi vs no pfi",
762
+ "why are there pfi and no pfi results",
763
+ "what is no pfi",
764
+ ],
765
+ "keywords": ["pfi", "no_pfi", "predictions", "descriptor reduction", "feature importance"],
766
+ "text": "ROBERT can report two model families: PFI and No_PFI. PFI uses permutation feature importance to reduce descriptors to the most relevant variables, while No_PFI keeps the unreduced descriptor set. Comparing both helps detect whether descriptor reduction improves robustness or changes predictions strongly.",
767
+ "priority": 1.0,
768
+ },
769
+ {
770
+ "id": "robert-identical-predictions",
771
+ "source": "curated_overrides",
772
+ "source_file": "manual",
773
+ "program": "ROBERT",
774
+ "module": "PREDICT",
775
+ "kind": "results",
776
+ "topic": "results",
777
+ "tab": "Predictions",
778
+ "title": "Identical predictions",
779
+ "question_patterns": [
780
+ "why are all my predictions identical",
781
+ "why predictions are identical",
782
+ "all predictions identical",
783
+ ],
784
+ "keywords": ["identical predictions", "predictions", "model", "constant", "external test"],
785
+ "text": "If all predictions are identical or nearly identical, the model may be over-regularized, using uninformative descriptors, receiving mismatched external-test descriptors, or applying a model outside its reliable domain. Check PFI and No_PFI agreement, descriptor columns, extrapolation warnings, and whether the external CSV matches the training descriptor format.",
786
+ "priority": 1.0,
787
+ },
788
+ {
789
+ "id": "easyrob-enable-aqme-workflow",
790
+ "source": "curated_overrides",
791
+ "source_file": "manual",
792
+ "program": "ROBERT",
793
+ "module": "FULL_WORKFLOW",
794
+ "kind": "workflow",
795
+ "topic": "workflow",
796
+ "tab": "ROBERT",
797
+ "title": "Enable AQME Workflow",
798
+ "question_patterns": [
799
+ "should i use the enable aqme workflow",
800
+ "what does enable aqme workflow do",
801
+ "when do i need aqme workflow",
802
+ ],
803
+ "keywords": ["enable aqme workflow", "smiles", "descriptors", "optional", "robert", "aqme"],
804
+ "text": "Enable AQME Workflow only when your dataset starts from molecular structures such as SMILES and you need easyROB to generate descriptors automatically. If your CSV already contains descriptor columns, you usually do not need AQME and can run the ROBERT machine-learning workflow directly.",
805
+ "priority": 1.0,
806
+ },
807
+ {
808
+ "id": "easyrob-smiles-aqme-robert-path",
809
+ "source": "curated_overrides",
810
+ "source_file": "manual",
811
+ "program": "ROBERT",
812
+ "module": "FULL_WORKFLOW",
813
+ "kind": "workflow",
814
+ "topic": "workflow",
815
+ "tab": "ROBERT",
816
+ "title": "SMILES to descriptors to ROBERT workflow",
817
+ "question_patterns": [
818
+ "how do smiles work in easyrob",
819
+ "how do i go from smiles to a model",
820
+ "workflow from smiles to robert",
821
+ ],
822
+ "keywords": ["smiles", "aqme", "descriptors", "robert", "workflow", "target column"],
823
+ "text": "When the dataset contains SMILES instead of ready-made descriptors, the usual path is: load the CSV, choose the target column and prediction type in ROBERT, enable AQME Workflow so descriptors can be generated from SMILES, optionally tune AQME settings, and then run ROBERT so the descriptor-generation step feeds the machine-learning workflow.",
824
+ "priority": 1.0,
825
+ },
826
+ ]
827
+
828
+
829
+ def empty_context(domain: str) -> dict[str, object]:
830
+ return {
831
+ "schema_version": SCHEMA_VERSION,
832
+ "domain": domain,
833
+ "version": CONTEXT_VERSION,
834
+ "overview": {},
835
+ "workflows": [],
836
+ "modules": [],
837
+ "interface": [],
838
+ "parameters": [],
839
+ "concepts": [],
840
+ "inputs_outputs": [],
841
+ "tutorials": [],
842
+ "troubleshooting": [],
843
+ }
844
+
845
+
846
+ def add_entry(context: dict[str, object], section: str, entry: dict[str, object]) -> None:
847
+ section_entries = context[section]
848
+ assert isinstance(section_entries, list)
849
+ section_entries.append(entry)
850
+
851
+
852
+ def content_fingerprint(text: object) -> str:
853
+ normalized = " ".join(
854
+ unicodedata.normalize("NFKC", str(text or "")).casefold().split()
855
+ )
856
+ return hashlib.sha1(normalized.encode("utf-8")).hexdigest()
857
+
858
+
859
+ def deduplicate_contexts(
860
+ contexts: Mapping[str, Mapping[str, object]],
861
+ ) -> dict[str, dict[str, object]]:
862
+ """Keep one deterministic, user-preferred record for each rendered body."""
863
+ tier_order = {"curated": 0, "tutorial": 1, "reference": 2, "generated": 3}
864
+ candidates: dict[
865
+ str,
866
+ list[tuple[tuple[object, ...], tuple[str, str, int], dict[str, object]]],
867
+ ] = {}
868
+ copied: dict[str, dict[str, object]] = {}
869
+
870
+ for domain in sorted(contexts):
871
+ payload = contexts[domain]
872
+ copied[domain] = dict(payload)
873
+ for section in CONTEXT_SECTIONS:
874
+ records = payload[section]
875
+ assert isinstance(records, list)
876
+ copied[domain][section] = []
877
+ for index, record in enumerate(records):
878
+ assert isinstance(record, dict)
879
+ priority_value = record.get("priority")
880
+ priority = (
881
+ float(priority_value)
882
+ if isinstance(priority_value, (int, float))
883
+ and not isinstance(priority_value, bool)
884
+ and math.isfinite(float(priority_value))
885
+ else float("-inf")
886
+ )
887
+ record_id = str(record.get("id", ""))
888
+ rank = (
889
+ tier_order.get(str(record.get("source_tier", "")), len(tier_order)),
890
+ -priority,
891
+ record_id,
892
+ domain,
893
+ section,
894
+ index,
895
+ )
896
+ location = (domain, section, index)
897
+ fingerprint = content_fingerprint(record.get("text"))
898
+ candidates.setdefault(fingerprint, []).append(
899
+ (rank, location, record)
900
+ )
901
+
902
+ winners = {
903
+ min(group, key=lambda candidate: candidate[0])[1]
904
+ for group in candidates.values()
905
+ }
906
+ for domain in sorted(contexts):
907
+ payload = contexts[domain]
908
+ for section in CONTEXT_SECTIONS:
909
+ records = payload[section]
910
+ assert isinstance(records, list)
911
+ copied[domain][section] = [
912
+ record
913
+ for index, record in enumerate(records)
914
+ if (domain, section, index) in winners
915
+ ]
916
+ return copied
917
+
918
+
919
+ def overview_blocks() -> dict[str, dict[str, str]]:
920
+ return {
921
+ "robert": {
922
+ "title": "ROBERT overview",
923
+ "text": "ROBERT is the machine-learning workflow in easyROB for curation, model generation, validation, prediction, and reporting.",
924
+ },
925
+ "aqme": {
926
+ "title": "AQME overview",
927
+ "text": "AQME is the chemistry workflow used to turn molecular structure information such as SMILES into descriptors for downstream modeling.",
928
+ },
929
+ "ui": {
930
+ "title": "easyROB UI overview",
931
+ "text": "easyROB is the graphical interface that guides users through ROBERT, AQME, reporting, images, prediction, and tutorial-driven workflows.",
932
+ },
933
+ }
934
+
935
+
936
+ def load_tutorial_records(tutorials_dir: Path) -> list[dict[str, object]]:
937
+ records: list[dict[str, object]] = []
938
+ if not tutorials_dir.exists():
939
+ return records
940
+ for path in sorted(tutorials_dir.glob("*.md")):
941
+ raw_text = path.read_text(encoding="utf-8", errors="ignore")
942
+ blocks = [block.strip() for block in raw_text.split("---") if block.strip()]
943
+ for index, block in enumerate(blocks, start=1):
944
+ block_text = re.sub(r"<[^>]+>", " ", block)
945
+ text = clean_text(block_text)
946
+ if not text:
947
+ continue
948
+ title = text.split(".")[0].splitlines()[0][:120].strip() or path.stem.replace("_", " ")
949
+ records.append(
950
+ {
951
+ "id": f"tutorial-{path.stem}-{index}",
952
+ "source": f"tutorial:{path.name}",
953
+ "kind": "tutorial",
954
+ "topic": "tutorial",
955
+ "title": title,
956
+ "text": text,
957
+ "keywords": [path.stem.replace("_", " "), "tutorial"],
958
+ "source_file": path.name,
959
+ "tab": "ROBERT",
960
+ "program": "ROBERT",
961
+ "module": "TUTORIALS",
962
+ "priority": 0.95,
963
+ }
964
+ )
965
+ return records
966
+
967
+
968
+ def _validation_error(code: str, message: str, source: Path | str) -> KnowledgeValidationError:
969
+ return KnowledgeValidationError(
970
+ (KnowledgeLoadIssue(code=code, message=message, source=str(source)),)
971
+ )
972
+
973
+
974
+ def load_curated_guidance(
975
+ source_dir: Path,
976
+ ) -> tuple[list[dict[str, object]], dict[str, object]]:
977
+ filenames = {
978
+ "robert": "robert_user_guidance.json",
979
+ "aqme": "aqme_user_guidance.json",
980
+ "ui": "ui_user_guidance.json",
981
+ }
982
+ payloads: dict[str, object] = {}
983
+ manifest_path = source_dir / "coverage_manifest.json"
984
+ paths = [source_dir / filename for filename in filenames.values()] + [manifest_path]
985
+ for path in paths:
986
+ if not path.is_file():
987
+ raise _validation_error(
988
+ "missing_source",
989
+ f"Required curated guidance source is missing: {path}",
990
+ path,
991
+ )
992
+
993
+ try:
994
+ for domain, filename in filenames.items():
995
+ payloads[domain] = json.loads(
996
+ (source_dir / filename).read_text(encoding="utf-8")
997
+ )
998
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
999
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
1000
+ raise _validation_error(
1001
+ "invalid_source",
1002
+ f"Could not load curated guidance: {exc}",
1003
+ source_dir,
1004
+ ) from exc
1005
+
1006
+ issues = list(
1007
+ validate_guidance_source_set(
1008
+ payloads,
1009
+ manifest,
1010
+ source=str(source_dir),
1011
+ )
1012
+ )
1013
+ try:
1014
+ trusted_manifest = json.loads(
1015
+ TRUSTED_COVERAGE_MANIFEST.read_text(encoding="utf-8")
1016
+ )
1017
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
1018
+ raise _validation_error(
1019
+ "invalid_trusted_contract",
1020
+ f"Could not load the packaged curated coverage contract: {exc}",
1021
+ TRUSTED_COVERAGE_MANIFEST,
1022
+ ) from exc
1023
+
1024
+ required_entities = (
1025
+ manifest.get("required_entities") if isinstance(manifest, Mapping) else None
1026
+ )
1027
+ trusted_required = trusted_manifest.get("required_entities")
1028
+ if not isinstance(required_entities, Mapping) or not isinstance(
1029
+ trusted_required, Mapping
1030
+ ):
1031
+ issues.append(
1032
+ KnowledgeLoadIssue(
1033
+ code="curated_contract_mismatch",
1034
+ message="Curated required-entity coverage does not match the packaged contract.",
1035
+ source=str(source_dir),
1036
+ )
1037
+ )
1038
+ else:
1039
+ for domain in DOMAINS:
1040
+ injected_ids = required_entities.get(domain)
1041
+ packaged_ids = trusted_required.get(domain)
1042
+ if not isinstance(injected_ids, list) or not isinstance(packaged_ids, list):
1043
+ continue
1044
+ if set(injected_ids) != set(packaged_ids):
1045
+ issues.append(
1046
+ KnowledgeLoadIssue(
1047
+ code="curated_contract_mismatch",
1048
+ message=f"Curated entity coverage for '{domain}' does not match the packaged contract.",
1049
+ source=str(source_dir),
1050
+ )
1051
+ )
1052
+ payload = payloads.get(domain)
1053
+ records = payload.get("records") if isinstance(payload, Mapping) else None
1054
+ if isinstance(records, list):
1055
+ actual_ids = {
1056
+ record.get("entity_id")
1057
+ for record in records
1058
+ if isinstance(record, Mapping)
1059
+ and isinstance(record.get("entity_id"), str)
1060
+ }
1061
+ if actual_ids != set(packaged_ids):
1062
+ issues.append(
1063
+ KnowledgeLoadIssue(
1064
+ code="curated_contract_mismatch",
1065
+ message=f"Curated records for '{domain}' do not satisfy the packaged contract.",
1066
+ source=str(source_dir),
1067
+ )
1068
+ )
1069
+ for domain, filename in filenames.items():
1070
+ payload = payloads.get(domain)
1071
+ records = payload.get("records") if isinstance(payload, Mapping) else None
1072
+ if not isinstance(records, list):
1073
+ continue
1074
+ for record in records:
1075
+ if not isinstance(record, Mapping):
1076
+ continue
1077
+ if record.get("source_file") != filename:
1078
+ issues.append(
1079
+ KnowledgeLoadIssue(
1080
+ code="curated_domain_mismatch",
1081
+ message=(
1082
+ f"Curated record from '{domain}' must claim source_file "
1083
+ f"'{filename}'."
1084
+ ),
1085
+ source=str(source_dir / filename),
1086
+ record_id=str(record.get("id", "")),
1087
+ )
1088
+ )
1089
+ if issues:
1090
+ raise KnowledgeValidationError(issues)
1091
+
1092
+ records: list[dict[str, object]] = []
1093
+ for domain in DOMAINS:
1094
+ payload = payloads[domain]
1095
+ assert isinstance(payload, Mapping)
1096
+ domain_records = payload["records"]
1097
+ assert isinstance(domain_records, list)
1098
+ records.extend(dict(record) for record in domain_records)
1099
+ assert isinstance(manifest, dict)
1100
+ return records, manifest
1101
+
1102
+
1103
+ def render_user_guidance(record: Mapping[str, object]) -> str:
1104
+ guidance = record.get("user_guidance")
1105
+ if not isinstance(guidance, Mapping):
1106
+ raise _validation_error(
1107
+ "invalid_user_guidance",
1108
+ "Curated record user_guidance must be an object.",
1109
+ str(record.get("source_file", "curated guidance")),
1110
+ )
1111
+
1112
+ lines = [f"Purpose: {guidance['purpose']}"]
1113
+ list_fields = (
1114
+ ("when_to_use", "When to use", False),
1115
+ ("prerequisites", "Prerequisites", False),
1116
+ ("steps", "Steps", True),
1117
+ )
1118
+ for field, label, numbered in list_fields:
1119
+ values = guidance.get(field, [])
1120
+ if values:
1121
+ lines.append(f"{label}:")
1122
+ lines.extend(
1123
+ f"{index}. {value}" if numbered else f"- {value}"
1124
+ for index, value in enumerate(values, start=1)
1125
+ )
1126
+ lines.append(f"Expected result: {guidance['result']}")
1127
+ for field, label in (
1128
+ ("next_steps", "Next steps"),
1129
+ ("common_issues", "Common issues"),
1130
+ ):
1131
+ values = guidance.get(field, [])
1132
+ if values:
1133
+ lines.append(f"{label}:")
1134
+ lines.extend(f"- {value}" for value in values)
1135
+ return "\n".join(lines)
1136
+
1137
+
1138
+ def route_chunk(chunk: dict[str, object]) -> tuple[str, str]:
1139
+ program = str(chunk.get("program", "")).upper()
1140
+ source = str(chunk.get("source", ""))
1141
+ source_file = str(chunk.get("source_file", "")).replace("\\", "/")
1142
+ title = str(chunk.get("title", ""))
1143
+ text = str(chunk.get("text", ""))
1144
+ tab = str(chunk.get("tab", ""))
1145
+ kind = str(chunk.get("kind", "concept"))
1146
+ ui_signal = f"{title} {text}".lower()
1147
+
1148
+ aqme_like_module = str(chunk.get("module", "")).upper() in {"AQME", "QDESCP", "CSEARCH", "CMIN", "QCORR", "QPREP"}
1149
+
1150
+ if program == "AQME" or tab == "AQME":
1151
+ domain = "aqme"
1152
+ elif source == "robert_code_docstrings" and aqme_like_module:
1153
+ domain = "ui"
1154
+ elif (
1155
+ source == "easyrob_code_docstrings"
1156
+ or source_file.lower().startswith("tutorials/")
1157
+ or source_file.lower().endswith("readme.rst")
1158
+ or (tab in UI_TABS and any(term in ui_signal for term in (" tab", " button", "easyrob", "interface", "gui")))
1159
+ ):
1160
+ domain = "ui"
1161
+ else:
1162
+ domain = "robert"
1163
+
1164
+ if kind == "workflow":
1165
+ return domain, "workflows"
1166
+ if kind == "parameter":
1167
+ return domain, "parameters"
1168
+ if kind == "diagnostic":
1169
+ return domain, "troubleshooting"
1170
+ if kind == "output":
1171
+ return domain, "inputs_outputs"
1172
+ if kind == "tutorial":
1173
+ return domain, "tutorials"
1174
+ if kind == "results":
1175
+ return domain, "concepts"
1176
+ return domain, "modules"
1177
+
1178
+
1179
+ def chunk_to_context_entry(chunk: dict[str, object]) -> dict[str, object]:
1180
+ return {
1181
+ "id": str(chunk.get("id", "")),
1182
+ "source": str(chunk.get("source", "")),
1183
+ "kind": str(chunk.get("kind", "")),
1184
+ "topic": str(chunk.get("topic", "")),
1185
+ "title": str(chunk.get("title", "")),
1186
+ "text": str(chunk.get("text", "")),
1187
+ "keywords": list(chunk.get("keywords", [])),
1188
+ "question_patterns": list(chunk.get("question_patterns", [])),
1189
+ "source_file": str(chunk.get("source_file", "")),
1190
+ "tab": str(chunk.get("tab", "")),
1191
+ "program": str(chunk.get("program", "")),
1192
+ "module": str(chunk.get("module", "")),
1193
+ "priority": float(chunk.get("priority", 0.7)),
1194
+ }
1195
+
1196
+
1197
+ def write_context_json(path: Path, payload: dict[str, object]) -> None:
1198
+ path.parent.mkdir(parents=True, exist_ok=True)
1199
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=True), encoding="utf-8")
1200
+
1201
+
1202
+ def remove_legacy_knowledge_files(output_dir: Path) -> None:
1203
+ for filename in LEGACY_KNOWLEDGE_FILENAMES:
1204
+ legacy_path = output_dir / filename
1205
+ if legacy_path.exists():
1206
+ legacy_path.unlink()
1207
+
1208
+
1209
+ def _legacy_export_docs_knowledge(output_dir: Path = KNOWLEDGE_DIR) -> None:
1210
+ output_dir.mkdir(parents=True, exist_ok=True)
1211
+ robert_chunks = export_tree(
1212
+ ROBERT_DOCS_DIR,
1213
+ source_name="robert_docs",
1214
+ program="ROBERT",
1215
+ include_prefixes=("Modules/", "Report/", "Tutorials/", "Examples/", "Install/", "README.rst"),
1216
+ )
1217
+ aqme_chunks = export_tree(
1218
+ AQME_DOCS_DIR,
1219
+ source_name="aqme_docs",
1220
+ program="AQME",
1221
+ include_prefixes=("Quickstart/", "Examples/", "README.rst", "video_tutorials.rst"),
1222
+ )
1223
+ robert_code_chunks = export_python_tree(
1224
+ ROBERT_CODE_DIR,
1225
+ source_name="robert_code_docstrings",
1226
+ program="ROBERT",
1227
+ )
1228
+ easyrob_code_chunks = export_python_tree(
1229
+ EASYROB_CODE_DIR,
1230
+ source_name="easyrob_code_docstrings",
1231
+ program="ROBERT",
1232
+ )
1233
+ aqme_code_chunks = export_python_tree(
1234
+ AQME_CODE_DIR,
1235
+ source_name="aqme_code_docstrings",
1236
+ program="AQME",
1237
+ )
1238
+
1239
+ curated_overrides = build_curated_overrides() + [
1240
+ {
1241
+ "id": "easyrob-robert-run-prerequisites",
1242
+ "source": "curated_overrides",
1243
+ "source_file": "manual",
1244
+ "program": "ROBERT",
1245
+ "module": "FULL_WORKFLOW",
1246
+ "kind": "workflow",
1247
+ "topic": "workflow",
1248
+ "tab": "ROBERT",
1249
+ "title": "Before running ROBERT",
1250
+ "question_patterns": [
1251
+ "what do i need before running robert",
1252
+ "what do i need before starting robert",
1253
+ "how can i start a machine learning workflow",
1254
+ "what should i check before running robert"
1255
+ ],
1256
+ "keywords": ["robert", "run", "before", "main csv", "target", "prediction type", "workflow"],
1257
+ "text": "Before running ROBERT in easyROB, load the main CSV for the training dataset, choose the target column, choose the prediction type, and confirm the workflow you want to run. A separate test CSV is optional unless you are running PREDICT on an external dataset. Enable the AQME workflow only when you need descriptors generated from molecular structures such as SMILES.",
1258
+ "priority": 1.0,
1259
+ },
1260
+ {
1261
+ "id": "aqme-qdescp-overview",
1262
+ "source": "curated_overrides",
1263
+ "source_file": "manual",
1264
+ "program": "AQME",
1265
+ "module": "QDESCP",
1266
+ "kind": "concept",
1267
+ "topic": "concept",
1268
+ "tab": "AQME",
1269
+ "title": "What QDESCP does",
1270
+ "question_patterns": ["what is qdescp", "how does qdescp work"],
1271
+ "keywords": ["qdescp", "aqme", "descriptors"],
1272
+ "text": "QDESCP generates quantum mechanical descriptors in AQME so they can later be used in downstream workflows such as descriptor-based modeling.",
1273
+ "priority": 0.98,
1274
+ },
1275
+ {
1276
+ "id": "easyrob-advanced-options-tab",
1277
+ "source": "curated_overrides",
1278
+ "source_file": "manual",
1279
+ "program": "ROBERT",
1280
+ "module": "ADVANCED_OPTIONS",
1281
+ "kind": "concept",
1282
+ "topic": "concept",
1283
+ "tab": "Advanced Options",
1284
+ "title": "Advanced Options tab",
1285
+ "question_patterns": [
1286
+ "what is advanced options tab",
1287
+ "what is the advanced options tab",
1288
+ "advanced options tab",
1289
+ "which parameters can i use"
1290
+ ],
1291
+ "keywords": ["advanced options", "parameters", "general", "curate", "generate", "predict"],
1292
+ "text": "The Advanced Options tab contains detailed ROBERT workflow parameters grouped by GENERAL, CURATE, GENERATE, and PREDICT. Most users can keep the defaults, but this tab is where advanced users tune dataset curation, model generation, prediction settings, and general workflow behavior.",
1293
+ "priority": 1.0,
1294
+ },
1295
+ {
1296
+ "id": "easyrob-run-robert-button",
1297
+ "source": "curated_overrides",
1298
+ "source_file": "manual",
1299
+ "program": "ROBERT",
1300
+ "module": "FULL_WORKFLOW",
1301
+ "kind": "workflow",
1302
+ "topic": "workflow",
1303
+ "tab": "ROBERT",
1304
+ "title": "Run ROBERT button",
1305
+ "question_patterns": [
1306
+ "what is run robert button",
1307
+ "what does run robert do",
1308
+ "how do i run robert",
1309
+ "run robert button"
1310
+ ],
1311
+ "keywords": ["run robert", "button", "launch", "workflow", "configured"],
1312
+ "text": "The Run ROBERT button launches the selected ROBERT workflow using the inputs and options currently configured in the GUI. In Full Workflow it runs the automated pipeline; in individual modes it runs the selected ROBERT stage.",
1313
+ "priority": 1.0,
1314
+ },
1315
+ {
1316
+ "id": "robert-pfi-overview",
1317
+ "source": "curated_overrides",
1318
+ "source_file": "manual",
1319
+ "program": "ROBERT",
1320
+ "module": "GENERATE",
1321
+ "kind": "parameter",
1322
+ "topic": "parameter",
1323
+ "tab": "Advanced Options",
1324
+ "title": "PFI",
1325
+ "question_patterns": [
1326
+ "what is pfi",
1327
+ "what does pfi mean",
1328
+ "what is pfi in robert",
1329
+ "what is pfi filter"
1330
+ ],
1331
+ "keywords": ["pfi", "permutation feature importance", "descriptor", "feature selection", "generate"],
1332
+ "text": "PFI means Permutation Feature Importance. In ROBERT it estimates which descriptors contribute most to model predictions, and it can be used to build reduced models with only the most relevant descriptors.",
1333
+ "priority": 1.0,
1334
+ },
1335
+ {
1336
+ "id": "robert-rmse-overview",
1337
+ "source": "curated_overrides",
1338
+ "source_file": "manual",
1339
+ "program": "ROBERT",
1340
+ "module": "REPORT",
1341
+ "kind": "results",
1342
+ "topic": "results",
1343
+ "tab": "Reports",
1344
+ "title": "RMSE",
1345
+ "question_patterns": [
1346
+ "what is rmse",
1347
+ "what does rmse mean",
1348
+ "what is rmse in robert",
1349
+ "how should i interpret rmse"
1350
+ ],
1351
+ "keywords": ["rmse", "root mean squared error", "prediction error", "metric", "target"],
1352
+ "text": "RMSE means Root Mean Squared Error. It measures the typical prediction error magnitude in the same units as the target value; lower RMSE generally indicates more accurate predictions.",
1353
+ "priority": 1.0,
1354
+ },
1355
+ {
1356
+ "id": "robert-report-metrics-overview",
1357
+ "source": "curated_overrides",
1358
+ "source_file": "manual",
1359
+ "program": "ROBERT",
1360
+ "module": "REPORT",
1361
+ "kind": "results",
1362
+ "topic": "results",
1363
+ "tab": "Reports",
1364
+ "title": "How to interpret ROBERT metrics",
1365
+ "question_patterns": ["what does rmse mean", "how should i interpret r2"],
1366
+ "keywords": ["rmse", "r2", "report", "metrics"],
1367
+ "text": "ROBERT report metrics summarize model quality. RMSE reflects prediction error magnitude in the target units, while R2 reflects how much target variance the model explains.",
1368
+ "priority": 0.99,
1369
+ },
1370
+ ]
1371
+
1372
+ contexts = {
1373
+ "robert": empty_context("robert"),
1374
+ "aqme": empty_context("aqme"),
1375
+ "ui": empty_context("ui"),
1376
+ }
1377
+ for domain, overview in overview_blocks().items():
1378
+ contexts[domain]["overview"] = overview
1379
+
1380
+ all_chunks = (
1381
+ robert_chunks
1382
+ + aqme_chunks
1383
+ + robert_code_chunks
1384
+ + easyrob_code_chunks
1385
+ + aqme_code_chunks
1386
+ + curated_overrides
1387
+ )
1388
+ for chunk in all_chunks:
1389
+ domain, section = route_chunk(chunk)
1390
+ add_entry(contexts[domain], section, chunk_to_context_entry(chunk))
1391
+
1392
+ tutorials_dir = EASYROB_CODE_DIR / "tutorials"
1393
+ for tutorial_record in load_tutorial_records(tutorials_dir):
1394
+ add_entry(contexts["ui"], "tutorials", tutorial_record)
1395
+
1396
+ remove_legacy_knowledge_files(output_dir)
1397
+ write_context_json(output_dir / "robert_context.json", contexts["robert"])
1398
+ write_context_json(output_dir / "aqme_context.json", contexts["aqme"])
1399
+ write_context_json(output_dir / "ui_context.json", contexts["ui"])
1400
+
1401
+
1402
+ def _section_for_kind(kind: object) -> str:
1403
+ return {
1404
+ "workflow": "workflows",
1405
+ "module": "modules",
1406
+ "interface": "interface",
1407
+ "parameter": "parameters",
1408
+ "output": "inputs_outputs",
1409
+ "tutorial": "tutorials",
1410
+ "diagnostic": "troubleshooting",
1411
+ "results": "concepts",
1412
+ "concept": "concepts",
1413
+ }.get(str(kind), "concepts")
1414
+
1415
+
1416
+ def _generated_entry(
1417
+ chunk: Mapping[str, object],
1418
+ *,
1419
+ source_tier: str,
1420
+ audience: str,
1421
+ ) -> dict[str, object]:
1422
+ entry = chunk_to_context_entry(dict(chunk))
1423
+ entry["source_tier"] = source_tier
1424
+ entry["audience"] = audience
1425
+ return entry
1426
+
1427
+
1428
+ def build_contexts(sources: ExportSources) -> dict[str, dict[str, object]]:
1429
+ roots = {
1430
+ "robert_docs": sources.robert_docs,
1431
+ "aqme_docs": sources.aqme_docs,
1432
+ "robert_code": sources.robert_code,
1433
+ "easyrob_code": sources.easyrob_code,
1434
+ "aqme_code": sources.aqme_code,
1435
+ "tutorials": sources.tutorials,
1436
+ "user_guidance": sources.user_guidance,
1437
+ }
1438
+ root_issues = [
1439
+ KnowledgeLoadIssue(
1440
+ code="missing_source",
1441
+ message=f"Required export source root '{name}' is missing or not a directory.",
1442
+ source=str(path),
1443
+ )
1444
+ for name, path in roots.items()
1445
+ if not path.is_dir()
1446
+ ]
1447
+ if root_issues:
1448
+ raise KnowledgeValidationError(root_issues)
1449
+
1450
+ curated_records, manifest = load_curated_guidance(sources.user_guidance)
1451
+ tutorial_files = manifest.get("tutorial_files")
1452
+ assert isinstance(tutorial_files, Mapping)
1453
+ tutorial_root = sources.tutorials.resolve()
1454
+ tutorial_issues: list[KnowledgeLoadIssue] = []
1455
+ for entity_id, filename in tutorial_files.items():
1456
+ relative_path = Path(str(filename))
1457
+ candidate = (tutorial_root / relative_path).resolve()
1458
+ if relative_path.is_absolute() or not candidate.is_relative_to(tutorial_root):
1459
+ tutorial_issues.append(
1460
+ KnowledgeLoadIssue(
1461
+ code="unsafe_tutorial_path",
1462
+ message=f"Tutorial source '{filename}' escapes the tutorial root.",
1463
+ source=str(filename),
1464
+ record_id=str(entity_id),
1465
+ )
1466
+ )
1467
+ elif not candidate.is_file():
1468
+ tutorial_issues.append(
1469
+ KnowledgeLoadIssue(
1470
+ code="missing_tutorial_source",
1471
+ message=f"Required tutorial source '{filename}' is missing.",
1472
+ source=str(candidate),
1473
+ record_id=str(entity_id),
1474
+ )
1475
+ )
1476
+ if tutorial_issues:
1477
+ raise KnowledgeValidationError(tutorial_issues)
1478
+
1479
+ extracted = {
1480
+ "robert_docs": export_tree(
1481
+ sources.robert_docs,
1482
+ "robert_docs",
1483
+ "ROBERT",
1484
+ ("Modules/", "Report/", "Tutorials/", "Examples/", "Install/", "README.rst"),
1485
+ ),
1486
+ "aqme_docs": export_tree(
1487
+ sources.aqme_docs,
1488
+ "aqme_docs",
1489
+ "AQME",
1490
+ ("Quickstart/", "Examples/", "README.rst", "video_tutorials.rst"),
1491
+ ),
1492
+ "robert_code_docstrings": export_python_tree(
1493
+ sources.robert_code, "robert_code_docstrings", "ROBERT"
1494
+ ),
1495
+ "easyrob_code_docstrings": export_python_tree(
1496
+ sources.easyrob_code, "easyrob_code_docstrings", "ROBERT"
1497
+ ),
1498
+ "aqme_code_docstrings": export_python_tree(
1499
+ sources.aqme_code, "aqme_code_docstrings", "AQME"
1500
+ ),
1501
+ "tutorials": load_tutorial_records(sources.tutorials),
1502
+ }
1503
+ empty_categories = [
1504
+ KnowledgeLoadIssue(
1505
+ code="empty_source_category",
1506
+ message=f"Required export category '{name}' produced no records.",
1507
+ source=str(roots.get(name, sources.tutorials)),
1508
+ )
1509
+ for name, records in extracted.items()
1510
+ if not records
1511
+ ]
1512
+ if empty_categories:
1513
+ raise KnowledgeValidationError(empty_categories)
1514
+
1515
+ contexts = {domain: empty_context(domain) for domain in DOMAINS}
1516
+ for domain, overview in overview_blocks().items():
1517
+ contexts[domain]["overview"] = overview
1518
+ contexts[domain]["version"] = manifest["version"]
1519
+
1520
+ generated_metadata = {
1521
+ "robert_docs": ("reference", "advanced_user"),
1522
+ "aqme_docs": ("reference", "advanced_user"),
1523
+ "robert_code_docstrings": ("generated", "developer_reference"),
1524
+ "easyrob_code_docstrings": ("generated", "developer_reference"),
1525
+ "aqme_code_docstrings": ("generated", "developer_reference"),
1526
+ "tutorials": ("tutorial", "end_user"),
1527
+ }
1528
+ for category, chunks in extracted.items():
1529
+ tier, audience = generated_metadata[category]
1530
+ for chunk in chunks:
1531
+ domain, section = route_chunk(dict(chunk))
1532
+ if category == "tutorials":
1533
+ domain, section = "ui", "tutorials"
1534
+ add_entry(
1535
+ contexts[domain],
1536
+ section,
1537
+ _generated_entry(chunk, source_tier=tier, audience=audience),
1538
+ )
1539
+
1540
+ curated_domains = {
1541
+ "robert_user_guidance.json": "robert",
1542
+ "aqme_user_guidance.json": "aqme",
1543
+ "ui_user_guidance.json": "ui",
1544
+ }
1545
+ for record in curated_records:
1546
+ entry = dict(record)
1547
+ entry["text"] = render_user_guidance(entry)
1548
+ source_file = str(entry.get("source_file", ""))
1549
+ domain = curated_domains[source_file]
1550
+ add_entry(contexts[domain], _section_for_kind(entry.get("kind")), entry)
1551
+
1552
+ contexts = deduplicate_contexts(contexts)
1553
+
1554
+ for payload in contexts.values():
1555
+ for section in CONTEXT_SECTIONS:
1556
+ records = payload[section]
1557
+ assert isinstance(records, list)
1558
+ records.sort(key=lambda record: str(record["id"]))
1559
+
1560
+ validation_issues = validate_context_set(contexts)
1561
+ if validation_issues:
1562
+ raise KnowledgeValidationError(validation_issues)
1563
+ return contexts
1564
+
1565
+
1566
+ def export_docs_knowledge(
1567
+ output_dir: Path = KNOWLEDGE_DIR,
1568
+ sources: ExportSources = DEFAULT_EXPORT_SOURCES,
1569
+ ) -> tuple[Path, Path, Path]:
1570
+ contexts = build_contexts(sources)
1571
+ ordered_outputs = (
1572
+ ("robert", "robert_context.json"),
1573
+ ("aqme", "aqme_context.json"),
1574
+ ("ui", "ui_context.json"),
1575
+ )
1576
+ serialized = {
1577
+ filename: json.dumps(
1578
+ contexts[domain],
1579
+ sort_keys=True,
1580
+ indent=2,
1581
+ ensure_ascii=True,
1582
+ )
1583
+ + "\n"
1584
+ for domain, filename in ordered_outputs
1585
+ }
1586
+
1587
+ output_dir.mkdir(parents=True, exist_ok=True)
1588
+ original_finals: dict[str, bytes | None] = {}
1589
+ for _domain, filename in ordered_outputs:
1590
+ final_path = output_dir / filename
1591
+ original_finals[filename] = (
1592
+ final_path.read_bytes() if final_path.exists() else None
1593
+ )
1594
+
1595
+ temporary_paths: dict[str, Path] = {}
1596
+ try:
1597
+ for _domain, filename in ordered_outputs:
1598
+ with tempfile.NamedTemporaryFile(
1599
+ mode="w",
1600
+ encoding="utf-8",
1601
+ newline="\n",
1602
+ dir=output_dir,
1603
+ prefix=f".{filename}.",
1604
+ suffix=".tmp",
1605
+ delete=False,
1606
+ ) as handle:
1607
+ temporary_paths[filename] = Path(handle.name)
1608
+ handle.write(serialized[filename])
1609
+ try:
1610
+ for _domain, filename in ordered_outputs:
1611
+ temporary_paths[filename].replace(output_dir / filename)
1612
+ except BaseException:
1613
+ for _domain, filename in ordered_outputs:
1614
+ final_path = output_dir / filename
1615
+ original = original_finals[filename]
1616
+ if original is None:
1617
+ if final_path.exists():
1618
+ final_path.unlink()
1619
+ else:
1620
+ final_path.write_bytes(original)
1621
+ raise
1622
+ finally:
1623
+ for path in temporary_paths.values():
1624
+ if path.exists():
1625
+ path.unlink()
1626
+
1627
+ remove_legacy_knowledge_files(output_dir)
1628
+ return tuple(output_dir / filename for _domain, filename in ordered_outputs)
1629
+
1630
+
1631
+ if __name__ == "__main__":
1632
+ export_docs_knowledge()