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,859 @@
1
+ """Rule-based diagnosis and answer formatting for the EasyROB bot."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+ import re
8
+ import unicodedata
9
+ from typing import Sequence
10
+
11
+ from .bot_context import GuiSnapshot
12
+ from .error_parser import infer_target_column_failure_hint
13
+
14
+ __all__ = ["Diagnosis", "diagnose_snapshot", "format_heuristic_answer"]
15
+
16
+
17
+ FAILURE_MARKERS = {
18
+ "error",
19
+ "errors",
20
+ "failed",
21
+ "failure",
22
+ "warning",
23
+ "warnings",
24
+ "exception",
25
+ "traceback",
26
+ "cannot",
27
+ "blocked",
28
+ }
29
+
30
+ _WORKFLOWS_REQUIRING_MAIN_CSV = {"FULL WORKFLOW"}
31
+ _WORKFLOWS_REQUIRING_TEST_CSV = {"PREDICT"}
32
+ _WORKFLOWS_REQUIRING_CSV_CONTEXT = {"REPORT"}
33
+ _WORKFLOWS_NOT_REQUIRING_TARGET = {"PREDICT", "REPORT"}
34
+ _TAB_ALIASES = {
35
+ "interactive plots": "Interactive plots",
36
+ "interactive plot": "Interactive plots",
37
+ "aqme": "AQME",
38
+ "report": "Reports",
39
+ "reports": "Reports",
40
+ "result": "Results",
41
+ "results": "Results",
42
+ "images": "Images",
43
+ "image": "Images",
44
+ "prediction": "Predictions",
45
+ "predictions": "Predictions",
46
+ "molssi": "MolSSI Databases",
47
+ "robert": "ROBERT",
48
+ }
49
+ _POPUP_QUESTION_RE = re.compile(
50
+ r"\b(pop[- ]?up|dialog|warning|message box|message|alert|appeared|appears|window)\b",
51
+ re.IGNORECASE,
52
+ )
53
+ _CURRENT_CONTEXT_REFERENCE_RE = re.compile(
54
+ r"\b(this|that|it|current|currently|just|now|happened|failed|failure|error|warning)\b",
55
+ re.IGNORECASE,
56
+ )
57
+ _AQME_WORKFLOW_QUESTION_RE = re.compile(
58
+ r"\b(enable\s+aqme\s+workflow|aqme\s+workflow|aqme\s+checkbox)\b",
59
+ re.IGNORECASE,
60
+ )
61
+ _DESCRIPTOR_GENERATION_QUESTION_RE = re.compile(
62
+ r"(?:\b(?:need|generate|create|make|use|require)\b[^?.!]{0,80}\bdescriptors?\b|"
63
+ r"\bdescriptors?\b[^?.!]{0,80}\b(?:need|generate|create|make|use|require)\b)",
64
+ re.IGNORECASE,
65
+ )
66
+ _AQME_TAB_QUESTION_RE = re.compile(
67
+ r"\baqme\s+tab\b",
68
+ re.IGNORECASE,
69
+ )
70
+ _AQME_LIVE_CONTEXT_RE = re.compile(
71
+ r"\b(common substructure|fmcs|mcs|max(?:imum)? common substructure|smarts|selected atoms?|atomic descriptors?|aqme warning|aqme message|this aqme)\b",
72
+ re.IGNORECASE,
73
+ )
74
+ _DOCS_LABEL = "Documentation"
75
+ _AQME_ADVANCED_HINT_RE = re.compile(
76
+ r"\b(tab|fmcs|smarts|atomic|atom|descriptor level|denovo|interpret|full|chemdraw|parameter|setting|configure)\b",
77
+ re.IGNORECASE,
78
+ )
79
+ _TRACEBACK_LINE_RE = re.compile(r'File "([^"]+)", line (\d+), in ([^\n\r]+)', re.IGNORECASE)
80
+ _EXCEPTION_LINE_RE = re.compile(
81
+ r"(?P<name>[A-Za-z_][A-Za-z0-9_]*(?:Error|Exception)):\s*(?P<message>.+)",
82
+ re.IGNORECASE,
83
+ )
84
+
85
+
86
+ @dataclass(frozen=True, slots=True)
87
+ class Diagnosis:
88
+ summary: str
89
+ reason: str
90
+ next_step: str
91
+
92
+
93
+ def _has_failure_markers(snapshot: GuiSnapshot) -> bool:
94
+ if any(term in FAILURE_MARKERS for term in snapshot.console_terms):
95
+ return True
96
+ console = snapshot.recent_console.lower()
97
+ if "not found" in console:
98
+ return True
99
+ return any(marker in console for marker in FAILURE_MARKERS)
100
+
101
+
102
+ def _console_specific_diagnosis(snapshot: GuiSnapshot) -> Diagnosis | None:
103
+ console = snapshot.recent_console.strip()
104
+ lowered = console.lower()
105
+ if not lowered:
106
+ return None
107
+
108
+ report_match = re.search(r"\bROBERT_report(?:_[A-Za-z0-9_]+)?\.pdf\b", console, re.IGNORECASE)
109
+ if report_match and ("not found" in lowered or "filenotfounderror" in lowered):
110
+ report_name = report_match.group(0)
111
+ return Diagnosis(
112
+ summary=f"{report_name} was not found.",
113
+ reason="The report PDF is missing from the run directory, so the GUI cannot open or display the final ROBERT report.",
114
+ next_step=f"Run the REPORT step or Full Workflow again, then check that `{report_name}` was created in the same folder as the selected CSV.",
115
+ )
116
+
117
+ column_match = re.search(r"column missing:\s*([^\n\r.]+)", console, flags=re.IGNORECASE)
118
+ if column_match:
119
+ column_name = column_match.group(1).strip().strip("'\"")
120
+ return Diagnosis(
121
+ summary=f"The required `{column_name}` column is missing.",
122
+ reason="The current workflow expected that column in the loaded CSV or generated AQME table, but it was not present.",
123
+ next_step=f"Check the input table and add or map the `{column_name}` column before saving or running the workflow again.",
124
+ )
125
+
126
+ if "target column must be numeric" in lowered:
127
+ return Diagnosis(
128
+ summary="The target column must be numeric.",
129
+ reason="Regression workflows need numerical target values so ROBERT can train and evaluate the model.",
130
+ next_step="Edit the target column to contain only numeric values, then reload or save the CSV again.",
131
+ )
132
+
133
+ if "target column is empty" in lowered:
134
+ return Diagnosis(
135
+ summary="The target column is empty.",
136
+ reason="ROBERT needs target values for the rows used to train or validate the model.",
137
+ next_step="Fill the target column with the measured response values before saving or running the workflow.",
138
+ )
139
+
140
+ if "no valid molecules" in lowered:
141
+ return Diagnosis(
142
+ summary="No valid molecules were found in the input file.",
143
+ reason="AQME/easyROB could not read usable molecular structures from the selected file.",
144
+ next_step="Check that the structures are chemically valid, the file format is correct, and SMILES or ChemDraw entries are not empty.",
145
+ )
146
+
147
+ if "please select a csv file" in lowered:
148
+ return Diagnosis(
149
+ summary="No CSV file was selected.",
150
+ reason="The workflow needs a CSV path before it can load data or determine the run directory.",
151
+ next_step="Select the main CSV or the required test CSV, depending on the selected workflow.",
152
+ )
153
+
154
+ if "aqme" in lowered and "expected output csv" in lowered and ("not found" in lowered or "missing" in lowered):
155
+ return Diagnosis(
156
+ summary="The expected AQME output CSV was not found.",
157
+ reason="AQME appears to have finished, but easyROB could not locate the descriptor CSV needed for the ROBERT workflow.",
158
+ next_step="Check the AQME output folder and file names, then rerun AQME if the descriptor CSV was not created.",
159
+ )
160
+
161
+ if "could not delete folder" in lowered or ("permissionerror" in lowered and "folder" in lowered):
162
+ return Diagnosis(
163
+ summary="easyROB could not delete a previous output folder.",
164
+ reason="A previous run folder may be open in another program, locked by the operating system, or missing write permissions.",
165
+ next_step="Close files or folders from the previous run, then retry. If needed, remove the old output folder manually after checking you do not need its contents.",
166
+ )
167
+
168
+ return None
169
+
170
+
171
+ def _normalize_workflow(workflow: str) -> str:
172
+ return workflow.strip().upper()
173
+
174
+
175
+ def _has_csv_context(snapshot: GuiSnapshot) -> bool:
176
+ return bool(snapshot.main_csv_path.strip() or snapshot.test_csv_path.strip())
177
+
178
+
179
+ def _requires_target_column(workflow: str) -> bool:
180
+ normalized = _normalize_workflow(workflow)
181
+ return bool(normalized) and normalized not in _WORKFLOWS_NOT_REQUIRING_TARGET
182
+
183
+
184
+ def _mentioned_tab(question: str) -> str | None:
185
+ lowered = question.lower()
186
+ for token, tab_name in _TAB_ALIASES.items():
187
+ if re.search(rf"\b{re.escape(token)}\b", lowered):
188
+ return tab_name
189
+ return None
190
+
191
+
192
+ def _is_explicit_tab_question(question: str) -> bool:
193
+ lowered = question.lower()
194
+ return bool(re.search(r"\b(tab|view|enabled|disabled|blocked|locked|available|open|unlock|where)\b", lowered))
195
+
196
+
197
+ def _tab_gating_diagnosis(snapshot: GuiSnapshot, mentioned_tab: str) -> Diagnosis | None:
198
+ result_view = "Report" if mentioned_tab == "Reports" else mentioned_tab
199
+ if result_view in snapshot.result_disabled_views:
200
+ return Diagnosis(
201
+ summary=f"The {result_view} view in Results is unavailable for the selected model.",
202
+ reason=f"Results enables {result_view} only when its files exist for the selected model and variant.",
203
+ next_step="Check the selected model in Results and the files generated for this run, then refresh the result views.",
204
+ )
205
+ if result_view in snapshot.result_enabled_views:
206
+ selected_model = snapshot.result_model or "the current selection"
207
+ return Diagnosis(
208
+ summary=f"The {result_view} view in Results is available for {selected_model}.",
209
+ reason=f"The GUI detected matching {result_view} files for this selection.",
210
+ next_step=f"Open Results and select {result_view} to inspect the available outputs.",
211
+ )
212
+ if mentioned_tab not in snapshot.disabled_tabs:
213
+ return None
214
+
215
+ if mentioned_tab == "AQME":
216
+ if not snapshot.aqme_workflow_enabled:
217
+ return Diagnosis(
218
+ summary="The AQME tab is disabled because the AQME workflow path is not enabled.",
219
+ reason="AQME is optional in the GUI, so the tab stays gated until `Enable AQME Workflow` is checked.",
220
+ next_step="Check `Enable AQME Workflow`. If you then want to run AQME, load the main CSV and confirm the dataset includes structure information such as a SMILES column.",
221
+ )
222
+ if not snapshot.main_csv_path.strip():
223
+ return Diagnosis(
224
+ summary="The AQME workflow path is enabled, but AQME still cannot run without a main CSV.",
225
+ reason="AQME descriptor generation needs a dataset to process after the tab is unlocked.",
226
+ next_step="Load the main CSV first, then return to AQME and verify the structure columns needed for descriptor generation.",
227
+ )
228
+ return Diagnosis(
229
+ summary="The AQME tab is still unavailable even though the AQME workflow path is enabled.",
230
+ reason="That usually means the AQME branch is enabled but some required AQME-specific context is still missing.",
231
+ next_step="Check the loaded dataset, especially whether it includes the structure information AQME expects, such as a SMILES column.",
232
+ )
233
+
234
+ if mentioned_tab == "Results":
235
+ return Diagnosis(
236
+ summary="The Results tab is disabled because no report, prediction, or image output has been detected yet.",
237
+ reason="Results opens when at least one of its Report, Predictions, or Images views has output for this run.",
238
+ next_step="Run a workflow that creates a report, prediction CSV, or figures, then refresh the run context.",
239
+ )
240
+
241
+ if mentioned_tab == "Reports":
242
+ return Diagnosis(
243
+ summary="The Reports tab is disabled because no report output has been detected yet.",
244
+ reason="The Reports tab is unlocked by the generated ROBERT PDF rather than by selecting the workflow alone.",
245
+ next_step="Run the workflow until the reporting stage completes and confirm that a `ROBERT_report_*.pdf` file is created successfully.",
246
+ )
247
+
248
+ if mentioned_tab == "Images":
249
+ return Diagnosis(
250
+ summary="The Images tab is disabled because no image outputs have been detected yet.",
251
+ reason="The GUI enables Images only after workflow figure folders are generated and discovered.",
252
+ next_step="Complete a workflow step that writes figures, then refresh or reopen that run context.",
253
+ )
254
+
255
+ if mentioned_tab == "Predictions":
256
+ return Diagnosis(
257
+ summary="The Predictions tab is disabled because no prediction outputs are available yet.",
258
+ reason="That tab becomes relevant only after a run produces external-test prediction artifacts.",
259
+ next_step="Provide a test dataset if needed, run prediction, and then check whether the prediction outputs were generated.",
260
+ )
261
+
262
+ return None
263
+
264
+
265
+ def diagnose_snapshot(snapshot: GuiSnapshot, question: str) -> Diagnosis:
266
+ workflow = _normalize_workflow(snapshot.workflow)
267
+ mentioned_tab = _mentioned_tab(question)
268
+ if (mentioned_tab == "Results" and "Results" not in snapshot.enabled_tabs
269
+ and "Results" not in snapshot.disabled_tabs
270
+ and "Reports" in snapshot.disabled_tabs):
271
+ # Older snapshots expose the three result pages as separate top-level tabs.
272
+ mentioned_tab = "Reports"
273
+
274
+ if mentioned_tab and _is_explicit_tab_question(question):
275
+ tab_diagnosis = _tab_gating_diagnosis(snapshot, mentioned_tab)
276
+ if tab_diagnosis is not None:
277
+ return tab_diagnosis
278
+
279
+ if workflow in _WORKFLOWS_REQUIRING_MAIN_CSV and not snapshot.main_csv_path.strip():
280
+ return Diagnosis(
281
+ summary="The main CSV input is not set.",
282
+ reason="The workflow cannot start without the primary dataset path.",
283
+ next_step="Select the main CSV before running the workflow.",
284
+ )
285
+
286
+ if workflow in _WORKFLOWS_REQUIRING_TEST_CSV and not snapshot.test_csv_path.strip():
287
+ return Diagnosis(
288
+ summary="The test CSV input is not set.",
289
+ reason="The PREDICT workflow needs an external dataset to score.",
290
+ next_step="Select the test CSV before running prediction.",
291
+ )
292
+
293
+ if workflow in _WORKFLOWS_REQUIRING_CSV_CONTEXT and not _has_csv_context(snapshot):
294
+ return Diagnosis(
295
+ summary="No CSV context is available for the report workflow.",
296
+ reason="REPORT needs at least one loaded CSV path so the GUI can resolve the run directory.",
297
+ next_step="Load the training CSV or test CSV that belongs to the run you want to report.",
298
+ )
299
+
300
+ if _requires_target_column(workflow) and not snapshot.target_column.strip():
301
+ return Diagnosis(
302
+ summary="The target column is not selected.",
303
+ reason="This workflow needs an explicit target column before ROBERT can build the command.",
304
+ next_step="Choose the target column in the Y dropdown.",
305
+ )
306
+
307
+ if snapshot.process_running:
308
+ return Diagnosis(
309
+ summary="A process is already running.",
310
+ reason="EasyROB is already running a workflow and cannot start a second run yet.",
311
+ next_step="Wait for the current run to finish before starting another one.",
312
+ )
313
+
314
+ console_diagnosis = _console_specific_diagnosis(snapshot)
315
+ if console_diagnosis is not None:
316
+ return console_diagnosis
317
+
318
+ if _has_failure_markers(snapshot):
319
+ return Diagnosis(
320
+ summary="The console shows a failure marker.",
321
+ reason="The console text includes an error-like marker such as `failed`, `warning`, or `not found`.",
322
+ next_step="Inspect the console output for the first error or warning and fix that issue first.",
323
+ )
324
+
325
+ return Diagnosis(
326
+ summary="No specific block was detected from the GUI snapshot.",
327
+ reason="The current snapshot does not point to a single obvious missing input or active failure.",
328
+ next_step="Check the selected workflow, inputs, and console output, then retry.",
329
+ )
330
+
331
+
332
+ def _format_candidates(candidates: Sequence[object]) -> str:
333
+ if not candidates:
334
+ return ""
335
+
336
+ labels: list[str] = []
337
+ for candidate in candidates:
338
+ candidate_obj = getattr(candidate, "chunk", candidate)
339
+ for attr_name in ("id", "topic", "tab", "source"):
340
+ value = getattr(candidate_obj, attr_name, None)
341
+ if value:
342
+ label = str(value).strip()
343
+ if label and label not in labels:
344
+ labels.append(label)
345
+ break
346
+ if len(labels) == 1:
347
+ break
348
+
349
+ if labels:
350
+ return f"\nRelevant retrieval hints: {', '.join(labels)}."
351
+ return ""
352
+
353
+
354
+ def _best_chunk(candidates: Sequence[object]) -> object | None:
355
+ if not candidates:
356
+ return None
357
+ return getattr(candidates[0], "chunk", candidates[0])
358
+
359
+
360
+ def _clean_sentence(text: str) -> str:
361
+ cleaned = " ".join(str(text or "").split())
362
+ return cleaned.strip()
363
+
364
+
365
+ def _short_answer_text(text: str, limit: int = 420) -> str:
366
+ cleaned = _clean_sentence(text)
367
+ cleaned = re.sub(r"\.\.\s+[\w-]+(?:\s+\w+)?::\s*\S*", "", cleaned)
368
+ cleaned = re.sub(r"\.\.\s+[\w-]+(?:-start|-end)?", "", cleaned)
369
+ cleaned = re.sub(r"<[^>]+>", "", cleaned)
370
+ cleaned = _clean_sentence(cleaned)
371
+ sentences = [part.strip() for part in re.split(r"(?<=[.!?])\s+", cleaned) if part.strip()]
372
+ if sentences:
373
+ candidate = " ".join(sentences[:2]).strip()
374
+ else:
375
+ candidate = cleaned
376
+ if len(candidate) <= limit:
377
+ return candidate
378
+ return candidate[: limit - 3].rstrip() + "..."
379
+
380
+
381
+ def _title_prefixed_text(title: str, text: str, fallback: str) -> str:
382
+ clean_title = _clean_sentence(title)
383
+ clean_text = _clean_sentence(text)
384
+ if not clean_text:
385
+ return clean_title or fallback
386
+ if clean_title and clean_text.lower().startswith(clean_title.lower()):
387
+ return clean_text
388
+ if clean_title:
389
+ return f"{clean_title}: {clean_text}"
390
+ return clean_text or fallback
391
+
392
+
393
+ def _format_guidance_answer(
394
+ question: str,
395
+ snapshot: GuiSnapshot,
396
+ candidates: Sequence[object],
397
+ intent: str,
398
+ ) -> str:
399
+ best = _best_chunk(candidates)
400
+ if best is None:
401
+ fallback = "I cannot confirm a specific answer from the packaged EasyROB guidance."
402
+ if snapshot.active_tab:
403
+ fallback += (
404
+ f" The current tab is {snapshot.active_tab}, but I need the exact visible label, "
405
+ "error, or popup text to guide you."
406
+ )
407
+ else:
408
+ fallback += " Please share the exact visible label, error, or popup text."
409
+ return fallback
410
+
411
+ if str(getattr(best, "id", "")) == "robert-curated-results-robert-rmse":
412
+ normalized_question = str(question or "").casefold()
413
+ if re.search(r"\b(?:lower|higher|better|worse)\b", normalized_question):
414
+ return (
415
+ "For RMSE, lower means smaller prediction errors when comparing models "
416
+ "on the same target, units, and evaluation set. It is not always enough "
417
+ "to choose a model: compare the error with what is acceptable for your use."
418
+ )
419
+ if re.search(r"\b(?:example|ejemplo)\b", normalized_question):
420
+ return (
421
+ "For example, if the target is yield, an RMSE of 5 percentage points "
422
+ "suggests an error scale of about 5 points. It does not mean every "
423
+ "prediction is within 5 points; compare models on the same held-out data."
424
+ )
425
+
426
+ full_text = str(getattr(best, "text", "") or "")
427
+ text = _short_answer_text(full_text)
428
+ tab = str(getattr(best, "tab", "") or "").strip()
429
+ source = str(getattr(best, "source", "") or "").strip()
430
+ title = str(getattr(best, "title", "") or "").strip()
431
+ kind = str(getattr(best, "kind", "") or "").strip()
432
+
433
+ if intent == "parameter" or kind == "parameter":
434
+ parts = [_title_prefixed_text(title, text, "Parameter")]
435
+ if tab:
436
+ parts.append(f"You would normally adjust this in the {tab} tab.")
437
+ return " ".join(part for part in parts if part)
438
+
439
+ if intent == "results" or kind == "results":
440
+ parts = [_title_prefixed_text(title, text, "Result")]
441
+ if tab:
442
+ parts.append(f"This is usually interpreted in the {tab} tab.")
443
+ return " ".join(part for part in parts if part)
444
+
445
+ parts = [text]
446
+ if kind == "workflow" and str(getattr(best, "source_tier", "") or "").casefold() == "curated":
447
+ steps_match = re.search(
448
+ r"\bSteps:\s*(.*?)\s*Expected result:", full_text, re.IGNORECASE | re.DOTALL
449
+ )
450
+ if steps_match:
451
+ steps = _clean_sentence(steps_match.group(1))
452
+ if steps:
453
+ limited_steps = steps if len(steps) <= 320 else steps[:317].rstrip() + "..."
454
+ parts.append(f"Steps: {limited_steps}")
455
+ if source == "curated_overrides":
456
+ return " ".join(part for part in parts if part)
457
+ if intent == "tutorial":
458
+ if tab == "Advanced Options":
459
+ parts.append(
460
+ f"For a general explanation, start from the {_DOCS_LABEL} button or ReadTheDocs."
461
+ )
462
+ elif tab:
463
+ parts.append(f"This is mainly covered in the {tab} tab.")
464
+ elif intent == "results" and tab:
465
+ parts.append(f"This is mainly interpreted from the {tab} outputs.")
466
+ return " ".join(part for part in parts if part)
467
+
468
+
469
+ def _question_mentions_popup(question: str) -> bool:
470
+ return bool(_POPUP_QUESTION_RE.search(question or ""))
471
+
472
+
473
+ def _popup_is_relevant(question: str) -> bool:
474
+ if _question_mentions_popup(question):
475
+ return True
476
+ return bool(_CURRENT_CONTEXT_REFERENCE_RE.search(question or ""))
477
+
478
+
479
+ def _question_is_about_aqme_workflow(question: str) -> bool:
480
+ return bool(_AQME_WORKFLOW_QUESTION_RE.search(question or ""))
481
+
482
+
483
+ def _question_is_about_descriptor_generation(question: str) -> bool:
484
+ return bool(_DESCRIPTOR_GENERATION_QUESTION_RE.search(question or ""))
485
+
486
+
487
+ def _question_mentions_aqme_advanced_controls(question: str) -> bool:
488
+ return bool(_AQME_ADVANCED_HINT_RE.search(question or ""))
489
+
490
+
491
+ def _question_is_about_aqme_tab(question: str) -> bool:
492
+ return bool(_AQME_TAB_QUESTION_RE.search(question or ""))
493
+
494
+
495
+ def _question_is_about_aqme_live_context(
496
+ question: str,
497
+ snapshot: GuiSnapshot | None = None,
498
+ intent: str = "diagnostic",
499
+ ) -> bool:
500
+ if _AQME_LIVE_CONTEXT_RE.search(question or ""):
501
+ return True
502
+ return bool(
503
+ snapshot is not None
504
+ and snapshot.active_tab == "AQME"
505
+ and intent == "diagnostic"
506
+ and _CURRENT_CONTEXT_REFERENCE_RE.search(question or "")
507
+ )
508
+
509
+
510
+ def _format_aqme_workflow_answer(question: str) -> str:
511
+ if _question_mentions_aqme_advanced_controls(question):
512
+ return (
513
+ "The AQME tab is the advanced area for descriptor generation in easyROB. "
514
+ "After you enable `Enable AQME Workflow`, that tab lets you tune AQME settings, "
515
+ "inspect common-structure/FMCS detection, and optionally choose atom-based descriptors. "
516
+ "Most users do not need to change that tab unless they want to customize descriptor generation."
517
+ )
518
+ return (
519
+ "Use `Enable AQME Workflow` when easyROB needs to generate descriptors from molecular structures "
520
+ "such as SMILES. For the common case, checking that option is enough and you do not need to open "
521
+ "the AQME tab unless you want to tune descriptor settings, inspect FMCS/common-structure detection, "
522
+ "or choose atomic descriptors. If your CSV already contains the descriptors you want to model, AQME "
523
+ "is usually not required."
524
+ )
525
+
526
+
527
+ def _format_descriptor_generation_options() -> str:
528
+ return (
529
+ "If your CSV already contains useful molecular descriptor columns for the model, AQME is not needed. "
530
+ "If it contains SMILES but lacks model-relevant descriptors, choose between two paths: press `Run AQME` "
531
+ "to generate descriptor CSV files only, or check `Enable AQME Workflow` and press `Run ROBERT` to generate "
532
+ "descriptors automatically and train the model in one run. The AQME tab is optional and mainly for advanced "
533
+ "settings such as atom-specific descriptors from a common substructure."
534
+ )
535
+
536
+
537
+ def _format_aqme_tab_answer() -> str:
538
+ return (
539
+ "The AQME tab is the advanced area for structure-based preprocessing and descriptor generation in easyROB. "
540
+ "After `Enable AQME Workflow` is checked, that tab lets you configure AQME, inspect common-structure/FMCS "
541
+ "detection, and optionally choose atom-based descriptors. Most users only need to enable AQME when they want "
542
+ "descriptors from SMILES or other structures; opening the AQME tab is mainly for advanced customization."
543
+ )
544
+
545
+
546
+ def _format_aqme_live_context_answer(snapshot: GuiSnapshot) -> str | None:
547
+ if snapshot.aqme_message_text:
548
+ parts = [f"In the AQME tab, the current message is: {snapshot.aqme_message_text}"]
549
+ if snapshot.aqme_info_text:
550
+ parts.append(snapshot.aqme_info_text)
551
+ if snapshot.aqme_multiple_matches_detected:
552
+ parts.append(
553
+ "This means the detected common substructure matches more than one place in at least one molecule, "
554
+ "so atom-specific selection can become ambiguous."
555
+ )
556
+ elif snapshot.aqme_smarts_pattern:
557
+ parts.append(
558
+ f"The current common substructure/FMCS pattern is `{snapshot.aqme_smarts_pattern}`."
559
+ )
560
+ return " ".join(part for part in parts if part)
561
+
562
+ if snapshot.aqme_smarts_pattern:
563
+ parts = [
564
+ f"The AQME tab currently detected the common substructure/FMCS pattern `{snapshot.aqme_smarts_pattern}`."
565
+ ]
566
+ if snapshot.aqme_info_text:
567
+ parts.append(snapshot.aqme_info_text)
568
+ if snapshot.aqme_selected_atoms:
569
+ parts.append(
570
+ f"Selected atom positions in that pattern: {', '.join(str(idx) for idx in snapshot.aqme_selected_atoms)}."
571
+ )
572
+ if snapshot.aqme_descriptor_level:
573
+ parts.append(f"Descriptor level: {snapshot.aqme_descriptor_level}.")
574
+ return " ".join(part for part in parts if part)
575
+
576
+ return None
577
+
578
+
579
+ def _normalized_question(question: str) -> str:
580
+ value = unicodedata.normalize("NFKD", str(question or "").casefold())
581
+ return " ".join(
582
+ "".join(character for character in value if not unicodedata.combining(character)).split()
583
+ )
584
+
585
+
586
+ def _format_live_gui_state_answer(question: str, snapshot: GuiSnapshot) -> str | None:
587
+ """Answer explicit questions about the current GUI without retrieval guesses."""
588
+ normalized = _normalized_question(question)
589
+ spanish = bool(re.search(r"\b(que|cual|tengo|esta|ahora|pestana|seleccionad[oa])\b", normalized))
590
+ current_hint = bool(re.search(
591
+ r"\b(current|currently|now|right now|selected|active|open|loaded|running|"
592
+ r"actual|ahora|seleccionad[oa]|activa|abierta|cargad[oa]|ejecutando|tengo)\b",
593
+ normalized,
594
+ ))
595
+
596
+ if re.search(r"\b(tab|pestana)\b", normalized) and (
597
+ current_hint or re.search(r"\b(am i in|donde estoy|which tab|what tab)\b", normalized)
598
+ ):
599
+ value = snapshot.active_tab or "unknown"
600
+ return f"La pestaña activa es **{value}**." if spanish else f"The active tab is **{value}**."
601
+
602
+ stage_status_hint = current_hint or bool(re.search(
603
+ r"\b(va|vamos|fallo|failed|finished|completad[oa])\b", normalized,
604
+ ))
605
+ if stage_status_hint and re.search(r"\b(stage|step|etapa|paso|fase)\b", normalized) and snapshot.workflow_stage_states:
606
+ active = [stage for stage, state in snapshot.workflow_stage_states if state == "active"]
607
+ failed = [stage for stage, state in snapshot.workflow_stage_states if state == "failed"]
608
+ completed = [stage for stage, state in snapshot.workflow_stage_states if state == "done"]
609
+ if failed:
610
+ stage = failed[0]
611
+ return f"La etapa **{stage}** ha fallado." if spanish else f"**{stage}** has failed."
612
+ if active:
613
+ stage = active[0]
614
+ return f"La etapa activa es **{stage}**." if spanish else f"The active stage is **{stage}**."
615
+ if completed:
616
+ stage = completed[-1]
617
+ return f"La última etapa completada es **{stage}**." if spanish else f"The last completed stage is **{stage}**."
618
+
619
+ if current_hint and re.search(r"\b(model|modelo)\b", normalized):
620
+ if snapshot.active_tab == "Results" and snapshot.result_model:
621
+ model = snapshot.result_model
622
+ variants = "; ".join(
623
+ f"{variant}: {name}" for variant, name in snapshot.result_selected_variants
624
+ )
625
+ detail = f" ({variants})" if variants else ""
626
+ return f"En Results está seleccionado **{model}**{detail}." if spanish else f"Results has **{model}** selected{detail}."
627
+ if snapshot.active_tab == "CheckML" and snapshot.checkml_model_source:
628
+ model = snapshot.checkml_model_name or snapshot.checkml_model_source
629
+ return f"En CheckML está seleccionado **{model}**." if spanish else f"CheckML has **{model}** selected."
630
+
631
+ if "workflow" in normalized and current_hint:
632
+ value = snapshot.workflow or "unknown"
633
+ return (
634
+ f"El workflow seleccionado es **{value}**."
635
+ if spanish else f"The selected workflow is **{value}**."
636
+ )
637
+
638
+ if re.search(r"\b(what is running|what's running|que se esta ejecutando|que esta corriendo)\b", normalized):
639
+ if snapshot.process_running:
640
+ value = snapshot.active_process or "A workflow"
641
+ return f"**{value}** se está ejecutando ahora." if spanish else f"**{value} is running** now."
642
+ return "No hay ningún proceso ejecutándose ahora." if spanish else "No process is running now."
643
+
644
+ if re.search(r"\b(columns?|columnas?)\b", normalized) and current_hint:
645
+ parts = []
646
+ if snapshot.target_column:
647
+ parts.append(f"target={snapshot.target_column}")
648
+ if snapshot.name_column:
649
+ parts.append(f"names={snapshot.name_column}")
650
+ if snapshot.ignored_columns:
651
+ parts.append(f"ignored={', '.join(snapshot.ignored_columns)}")
652
+ values = "; ".join(parts) or "none"
653
+ return f"Columnas seleccionadas: **{values}**." if spanish else f"Selected columns: **{values}**."
654
+
655
+ if re.search(r"\b(files?|csv|archivos?)\b", normalized) and current_hint:
656
+ main_name = os.path.basename(snapshot.main_csv_path.replace("\\", "/")) if snapshot.main_csv_path else "none"
657
+ test_name = os.path.basename(snapshot.test_csv_path.replace("\\", "/")) if snapshot.test_csv_path else "none"
658
+ if spanish:
659
+ return f"CSV principal: **{main_name}**. CSV de test: **{test_name}**."
660
+ return f"Main CSV: **{main_name}**. Test CSV: **{test_name}**."
661
+
662
+ if re.search(r"\b(advanced settings|advanced options|ajustes avanzados|opciones avanzadas)\b", normalized) and current_hint:
663
+ if not snapshot.advanced_settings:
664
+ return "No se detectaron ajustes avanzados." if spanish else "No advanced settings were detected."
665
+ group_by_name = {
666
+ "auto_type": "General", "seed": "General", "kfold": "General",
667
+ "repeat_kfolds": "General", "split": "General",
668
+ "categorical": "CURATE", "corr_filter_x": "CURATE", "corr_filter_y": "CURATE",
669
+ "desc_thres": "CURATE", "thres_x": "CURATE", "thres_y": "CURATE",
670
+ "models": "GENERATE", "error_type": "GENERATE", "init_points": "GENERATE",
671
+ "n_iter": "GENERATE", "expect_improv": "GENERATE", "pfi_filter": "GENERATE",
672
+ "pfi_epochs": "GENERATE", "pfi_threshold": "GENERATE", "pfi_max": "GENERATE",
673
+ "auto_test": "GENERATE", "test_set": "GENERATE",
674
+ "t_value": "PREDICT", "shap_show": "PREDICT", "pfi_show": "PREDICT",
675
+ }
676
+ grouped: dict[str, list[str]] = {}
677
+ for setting in snapshot.advanced_settings:
678
+ name = setting.partition("=")[0]
679
+ grouped.setdefault(group_by_name.get(name, "Other"), []).append(setting)
680
+ heading = "Ajustes actuales de Advanced Options:" if spanish else "Current Advanced Options:"
681
+ order = ("General", "CURATE", "GENERATE", "PREDICT", "Other")
682
+ lines = [f"- {group}: {', '.join(grouped[group])}" for group in order if group in grouped]
683
+ return f"{heading}\n\n" + "\n".join(lines)
684
+
685
+ return None
686
+
687
+
688
+ def _popup_context(snapshot: GuiSnapshot, question: str) -> dict[str, object] | None:
689
+ if snapshot.popup_text.strip():
690
+ return {
691
+ "title": snapshot.popup_title,
692
+ "text": snapshot.popup_text,
693
+ "buttons": snapshot.popup_buttons,
694
+ "kind": snapshot.popup_kind,
695
+ "source": snapshot.popup_source,
696
+ "active": bool(snapshot.popup_active),
697
+ "recent": not bool(snapshot.popup_active),
698
+ "age_seconds": snapshot.popup_age_seconds,
699
+ }
700
+ return None
701
+
702
+
703
+ def _format_popup_answer(popup: dict[str, object]) -> str:
704
+ title = _clean_sentence(str(popup.get("title", "") or "Popup"))
705
+ text = _clean_sentence(str(popup.get("text", "") or ""))
706
+ buttons = [str(button) for button in popup.get("buttons", []) or []]
707
+ lowered = text.lower()
708
+
709
+ parts = [f"{title}: {text}" if title else text]
710
+ age_seconds = popup.get("age_seconds")
711
+ if popup.get("recent") and isinstance(age_seconds, (int, float)):
712
+ parts.insert(0, f"This popup appeared about {age_seconds:.1f} seconds ago.")
713
+ if {"Yes", "No"}.issubset(set(buttons)) and any(term in lowered for term in ("delete", "overwritten", "overwrite")):
714
+ parts.append(
715
+ "`Yes` continues and allows easyROB to delete or overwrite those previous-run folders. "
716
+ "`No` cancels that action so you can keep or inspect the old outputs first."
717
+ )
718
+ elif buttons:
719
+ parts.append(f"Available choices: {', '.join(buttons)}.")
720
+ return " ".join(part for part in parts if part)
721
+
722
+
723
+ def _extract_console_failure_detail(console_text: str) -> str:
724
+ text = str(console_text or "").strip()
725
+ if not text:
726
+ return ""
727
+
728
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
729
+ exception_line = ""
730
+ traceback_line = ""
731
+ for line in reversed(lines):
732
+ if not exception_line and _EXCEPTION_LINE_RE.search(line):
733
+ exception_line = line
734
+ if not traceback_line:
735
+ match = _TRACEBACK_LINE_RE.search(line)
736
+ if match:
737
+ traceback_line = f'{match.group(1)}, line {match.group(2)}, in {match.group(3).strip()}'
738
+ if exception_line and traceback_line:
739
+ break
740
+
741
+ if exception_line and traceback_line:
742
+ return f"{exception_line}. It appears around {traceback_line}."
743
+ if exception_line:
744
+ return exception_line
745
+ if traceback_line:
746
+ return f"The traceback points to {traceback_line}."
747
+ return ""
748
+
749
+
750
+ def _format_process_failure_popup_answer(snapshot: GuiSnapshot, popup: dict[str, object]) -> str:
751
+ title = _clean_sentence(str(popup.get("title", "") or "WARNING!"))
752
+ text = _clean_sentence(str(popup.get("text", "") or ""))
753
+ failure_detail = _extract_console_failure_detail(snapshot.recent_console)
754
+
755
+ if failure_detail:
756
+ return (
757
+ f"{title}: {text} "
758
+ f"The concrete error in the console is: {failure_detail} "
759
+ "This is the detail to diagnose, not just the popup itself."
760
+ )
761
+
762
+ return _format_popup_answer(popup)
763
+
764
+
765
+ def _structured_failure_answer(snapshot: GuiSnapshot, popup: dict[str, object]) -> str:
766
+ if not snapshot.failure_type and not snapshot.failure_message:
767
+ return ""
768
+
769
+ parts = [
770
+ f"{popup.get('title', 'WARNING!')}: {popup.get('text', '')}".strip(),
771
+ (
772
+ f"The concrete error is {snapshot.failure_type}: {snapshot.failure_message}."
773
+ if snapshot.failure_type and snapshot.failure_message
774
+ else ""
775
+ ),
776
+ (
777
+ f"It happens around {snapshot.failure_location} in {snapshot.failure_function}."
778
+ if snapshot.failure_location and snapshot.failure_function
779
+ else ""
780
+ ),
781
+ (
782
+ f"The failing operation is `{snapshot.failure_operation}`."
783
+ if snapshot.failure_operation
784
+ else ""
785
+ ),
786
+ (
787
+ f"Most likely cause: {snapshot.likely_cause}."
788
+ if snapshot.likely_cause
789
+ else ""
790
+ ),
791
+ infer_target_column_failure_hint(
792
+ snapshot.target_column,
793
+ snapshot.prediction_type,
794
+ snapshot.failure_type,
795
+ snapshot.failure_operation,
796
+ snapshot.likely_cause,
797
+ ),
798
+ ]
799
+ return " ".join(part for part in parts if part)
800
+
801
+
802
+ def format_heuristic_answer(
803
+ question: str,
804
+ snapshot: GuiSnapshot,
805
+ diagnosis: Diagnosis,
806
+ candidates: Sequence[object],
807
+ intent: str = "diagnostic",
808
+ ) -> str:
809
+ live_state_answer = _format_live_gui_state_answer(question, snapshot)
810
+ if live_state_answer:
811
+ return live_state_answer
812
+
813
+ popup = _popup_context(snapshot, question)
814
+ if popup is not None and (
815
+ _popup_is_relevant(question)
816
+ ):
817
+ if str(popup.get("source", "") or "").endswith("_finish_failure"):
818
+ structured = _structured_failure_answer(snapshot, popup)
819
+ if structured:
820
+ return structured
821
+ return _format_process_failure_popup_answer(snapshot, popup)
822
+ return _format_popup_answer(popup)
823
+
824
+ if (snapshot.workflow.strip().upper() == "CHECKML"
825
+ and re.search(r"\bverify\b", question, re.IGNORECASE)
826
+ and re.search(r"\b(?:here|this workflow|aqui|aquí|este workflow|este flujo)\b", question, re.IGNORECASE)):
827
+ if re.search(r"[¿¡áéíóúñ]|\b(?:que|como|aqui|este)\b", question, re.IGNORECASE):
828
+ return (
829
+ "En CheckML, VERIFY evalúa el modelo seleccionado con las pruebas de validación de ROBERT "
830
+ "y registra las comprobaciones fallidas o inciertas. CheckML no realiza la búsqueda de modelos "
831
+ "de GENERATE. Revisa esos resultados en Results > Report antes de usar las predicciones."
832
+ )
833
+ return (
834
+ "In CheckML, VERIFY evaluates the selected model with ROBERT's validation tests and records "
835
+ "failed or unclear checks. CheckML does not run GENERATE's model search. Review these findings "
836
+ "in Results > Report before relying on predictions."
837
+ )
838
+
839
+ if _question_is_about_aqme_live_context(question, snapshot, intent):
840
+ aqme_answer = _format_aqme_live_context_answer(snapshot)
841
+ if aqme_answer:
842
+ return aqme_answer
843
+
844
+ if intent != "diagnostic":
845
+ if _question_is_about_aqme_tab(question):
846
+ return _format_aqme_tab_answer()
847
+ if _question_is_about_aqme_workflow(question):
848
+ return _format_aqme_workflow_answer(question)
849
+ if _question_is_about_descriptor_generation(question):
850
+ return _format_descriptor_generation_options()
851
+ return _format_guidance_answer(question, snapshot, candidates, intent)
852
+
853
+ parts = [
854
+ f"What is happening: {diagnosis.summary}",
855
+ f"Why: {diagnosis.reason}",
856
+ f"What to check next: {diagnosis.next_step}",
857
+ ]
858
+
859
+ return "\n".join(parts)