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.
- robert/__init__.py +9 -0
- robert/__main__.py +20 -0
- robert/_version.py +3 -0
- robert/api.py +646 -0
- robert/aqme.py +280 -0
- robert/argument_parser.py +98 -0
- robert/checkml.py +433 -0
- robert/checkml_score.py +50 -0
- robert/curate.py +217 -0
- robert/evaluate_bot_retrieval.py +125 -0
- robert/evaluate_bot_support.py +102 -0
- robert/evaluate_workflow_summaries.py +87 -0
- robert/export_bot_docs_knowledge.py +1632 -0
- robert/generate.py +249 -0
- robert/generate_utils.py +311 -0
- robert/gui_easyrob/__init__.py +0 -0
- robert/gui_easyrob/assets/gif_easyrob.gif +0 -0
- robert/gui_easyrob/bot/__init__.py +47 -0
- robert/gui_easyrob/bot/answer_metadata.py +198 -0
- robert/gui_easyrob/bot/bot_context.py +679 -0
- robert/gui_easyrob/bot/bot_engine.py +1100 -0
- robert/gui_easyrob/bot/bot_panel.py +1231 -0
- robert/gui_easyrob/bot/bot_rag.py +1178 -0
- robert/gui_easyrob/bot/bot_window.py +39 -0
- robert/gui_easyrob/bot/bot_worker.py +149 -0
- robert/gui_easyrob/bot/credential_store.py +143 -0
- robert/gui_easyrob/bot/error_parser.py +105 -0
- robert/gui_easyrob/bot/evidence_policy.py +164 -0
- robert/gui_easyrob/bot/heuristics.py +859 -0
- robert/gui_easyrob/bot/icons.py +56 -0
- robert/gui_easyrob/bot/input_csv_audit.py +212 -0
- robert/gui_easyrob/bot/knowledge/aqme_context.json +5907 -0
- robert/gui_easyrob/bot/knowledge/robert_context.json +4817 -0
- robert/gui_easyrob/bot/knowledge/ui_context.json +8293 -0
- robert/gui_easyrob/bot/knowledge_schema.py +1252 -0
- robert/gui_easyrob/bot/knowledge_sources/aqme_user_guidance.json +442 -0
- robert/gui_easyrob/bot/knowledge_sources/coverage_manifest.json +95 -0
- robert/gui_easyrob/bot/knowledge_sources/robert_user_guidance.json +471 -0
- robert/gui_easyrob/bot/knowledge_sources/ui_user_guidance.json +1312 -0
- robert/gui_easyrob/bot/llm_providers.py +1573 -0
- robert/gui_easyrob/bot/online_docs.py +105 -0
- robert/gui_easyrob/bot/prompt_policy.py +575 -0
- robert/gui_easyrob/bot/question_intent.py +562 -0
- robert/gui_easyrob/bot/response_quality.py +104 -0
- robert/gui_easyrob/bot/result_insights.py +225 -0
- robert/gui_easyrob/bot/token_usage.py +75 -0
- robert/gui_easyrob/bot/workflow_results.py +1396 -0
- robert/gui_easyrob/checkml_launcher.py +15 -0
- robert/gui_easyrob/easyrob.py +29 -0
- robert/gui_easyrob/easyrob_launcher.py +113 -0
- robert/gui_easyrob/main/__init__.py +9 -0
- robert/gui_easyrob/main/window.py +5152 -0
- robert/gui_easyrob/result_navigation.py +14 -0
- robert/gui_easyrob/tabs/__init__.py +23 -0
- robert/gui_easyrob/tabs/advanced_options.py +370 -0
- robert/gui_easyrob/tabs/aqme.py +1234 -0
- robert/gui_easyrob/tabs/checkml.py +898 -0
- robert/gui_easyrob/tabs/images.py +427 -0
- robert/gui_easyrob/tabs/interactive_predictions.py +555 -0
- robert/gui_easyrob/tabs/molssi.py +447 -0
- robert/gui_easyrob/tabs/predictions.py +484 -0
- robert/gui_easyrob/tabs/result_catalog.py +170 -0
- robert/gui_easyrob/tabs/results.py +490 -0
- robert/gui_easyrob/tabs/results_workspace.py +120 -0
- robert/gui_easyrob/test_bot_input_csv_audit.py +152 -0
- robert/gui_easyrob/test_bot_question_routing.py +383 -0
- robert/gui_easyrob/test_bot_result_analysis.py +356 -0
- robert/gui_easyrob/test_bot_retrieval_evaluation.py +110 -0
- robert/gui_easyrob/test_bot_ui_integration.py +278 -0
- robert/gui_easyrob/test_checkml_app_mode.py +124 -0
- robert/gui_easyrob/test_checkml_completion.py +57 -0
- robert/gui_easyrob/test_checkml_defaults.py +37 -0
- robert/gui_easyrob/test_checkml_result_summary.py +113 -0
- robert/gui_easyrob/test_checkml_web_mode.py +57 -0
- robert/gui_easyrob/test_dialog_layout.py +33 -0
- robert/gui_easyrob/test_gui_bot_regressions.py +320 -0
- robert/gui_easyrob/test_molssi_auto.py +569 -0
- robert/gui_easyrob/test_tutorial_view.py +215 -0
- robert/gui_easyrob/tutorials/check_model.md +25 -0
- robert/gui_easyrob/tutorials/chemdraw.md +49 -0
- robert/gui_easyrob/tutorials/csv.md +53 -0
- robert/gui_easyrob/tutorials/descriptors.md +21 -0
- robert/gui_easyrob/tutorials/overview.md +65 -0
- robert/gui_easyrob/tutorials/predictions.md +25 -0
- robert/gui_easyrob/tutorials/robbot.md +29 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_10.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_11.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_12.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_13.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_9.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_9.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_8.png +0 -0
- robert/gui_easyrob/utils/__init__.py +0 -0
- robert/gui_easyrob/utils/aqme_utils.py +238 -0
- robert/gui_easyrob/utils/molssi_utils.py +584 -0
- robert/gui_easyrob/utils/predictions_utils.py +985 -0
- robert/gui_easyrob/utils/utils_gui.py +738 -0
- robert/gui_easyrob/version.py +68 -0
- robert/gui_easyrob/web/app.css +484 -0
- robert/gui_easyrob/web/app.html +134 -0
- robert/gui_easyrob/web/app.js +764 -0
- robert/gui_easyrob/web/checkml_brand.png +0 -0
- robert/gui_easyrob/web/easyrob_background.gif +0 -0
- robert/gui_easyrob/web/easyrob_background.png +0 -0
- robert/gui_easyrob/web/images.css +89 -0
- robert/gui_easyrob/web/images.html +39 -0
- robert/gui_easyrob/web/images.js +101 -0
- robert/gui_easyrob/web/results.js +499 -0
- robert/gui_easyrob/web/robert_brand.png +0 -0
- robert/gui_easyrob/web_dialogs.py +64 -0
- robert/gui_easyrob/web_results.py +253 -0
- robert/gui_easyrob/web_shell.py +684 -0
- robert/gui_easyrob/workflow_progress.py +89 -0
- robert/gui_easyrob/workflow_run_lock.py +27 -0
- robert/icons/CheckML_icon.png +0 -0
- robert/icons/Robert_icon.png +0 -0
- robert/icons/Robert_logo.jpg +0 -0
- robert/icons/Robert_logo_transparent.png +0 -0
- robert/icons/documentation_icon.png +0 -0
- robert/icons/info_icon.png +0 -0
- robert/icons/pdf_icon.png +0 -0
- robert/icons/play_icon.png +0 -0
- robert/icons/stop_icon.png +0 -0
- robert/icons/youtube_icon.ico +0 -0
- robert/predict.py +193 -0
- robert/predict_utils.py +410 -0
- robert/report/CheckML_logo.jpg +0 -0
- robert/report/GENERATE.png +0 -0
- robert/report/Robert_icon.ico +0 -0
- robert/report/Robert_logo.jpg +0 -0
- robert/report/Robert_logo1.jpg +0 -0
- robert/report/abbrev.png +0 -0
- robert/report/adv_anal.png +0 -0
- robert/report/checkml_pass.svg +3 -0
- robert/report/checkml_unclear.svg +3 -0
- robert/report/checkml_warning.svg +3 -0
- robert/report/features.png +0 -0
- robert/report/outliers.png +0 -0
- robert/report/pred.png +0 -0
- robert/report/repro.png +0 -0
- robert/report/robust_x.png +0 -0
- robert/report/robust_y_high.png +0 -0
- robert/report/robust_y_low.png +0 -0
- robert/report/score.png +0 -0
- robert/report/score_0.jpg +0 -0
- robert/report/score_1.jpg +0 -0
- robert/report/score_10.jpg +0 -0
- robert/report/score_2.jpg +0 -0
- robert/report/score_3.jpg +0 -0
- robert/report/score_4.jpg +0 -0
- robert/report/score_5.jpg +0 -0
- robert/report/score_6.jpg +0 -0
- robert/report/score_7.jpg +0 -0
- robert/report/score_8.jpg +0 -0
- robert/report/score_9.jpg +0 -0
- robert/report/score_gray_0.jpg +0 -0
- robert/report/score_gray_1.jpg +0 -0
- robert/report/score_gray_10.jpg +0 -0
- robert/report/score_gray_2.jpg +0 -0
- robert/report/score_gray_3.jpg +0 -0
- robert/report/score_gray_4.jpg +0 -0
- robert/report/score_gray_5.jpg +0 -0
- robert/report/score_gray_6.jpg +0 -0
- robert/report/score_gray_7.jpg +0 -0
- robert/report/score_gray_8.jpg +0 -0
- robert/report/score_gray_9.jpg +0 -0
- robert/report/score_w_1_0.jpg +0 -0
- robert/report/score_w_1_1.jpg +0 -0
- robert/report/score_w_2_0.jpg +0 -0
- robert/report/score_w_2_1.jpg +0 -0
- robert/report/score_w_2_2.jpg +0 -0
- robert/report/score_w_2_gray_0.jpg +0 -0
- robert/report/score_w_2_gray_1.jpg +0 -0
- robert/report/score_w_2_gray_2.jpg +0 -0
- robert/report/score_w_3_0.jpg +0 -0
- robert/report/score_w_3_1.jpg +0 -0
- robert/report/score_w_3_2.jpg +0 -0
- robert/report/score_w_3_3.jpg +0 -0
- robert/report/score_w_4_0.jpg +0 -0
- robert/report/score_w_4_1.JPG +0 -0
- robert/report/score_w_4_2.jpg +0 -0
- robert/report/score_w_4_3.jpg +0 -0
- robert/report/score_w_4_4.jpg +0 -0
- robert/report/transpa.png +0 -0
- robert/report/y_distrib.png +0 -0
- robert/report.py +2880 -0
- robert/report_utils.py +2270 -0
- robert/robert.py +181 -0
- robert/utils.py +4763 -0
- robert/verify.py +606 -0
- robert-2.2.0.dist-info/METADATA +55 -0
- robert-2.2.0.dist-info/RECORD +261 -0
- robert-2.2.0.dist-info/WHEEL +5 -0
- robert-2.2.0.dist-info/entry_points.txt +3 -0
- robert-2.2.0.dist-info/licenses/LICENSE +21 -0
- robert-2.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1178 @@
|
|
|
1
|
+
"""Lexical knowledge base loading and ranking for the EasyROB bot."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
import unicodedata
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Iterable, Mapping, Sequence
|
|
14
|
+
|
|
15
|
+
from .knowledge_schema import (
|
|
16
|
+
CONTEXT_SECTIONS,
|
|
17
|
+
DOMAINS,
|
|
18
|
+
KnowledgeLoadIssue,
|
|
19
|
+
KnowledgeValidationError,
|
|
20
|
+
validate_context_payload,
|
|
21
|
+
validate_context_set,
|
|
22
|
+
)
|
|
23
|
+
from .question_intent import classify_question_intent
|
|
24
|
+
|
|
25
|
+
__all__ = ["KnowledgeBase", "KnowledgeChunk", "SearchResult", "normalize_terms"]
|
|
26
|
+
|
|
27
|
+
FIELD_WEIGHTS = {
|
|
28
|
+
"question_patterns": 4.0,
|
|
29
|
+
"title": 3.5,
|
|
30
|
+
"keywords": 3.0,
|
|
31
|
+
"aliases": 3.0,
|
|
32
|
+
"tab": 2.5,
|
|
33
|
+
"module": 2.5,
|
|
34
|
+
"program": 2.5,
|
|
35
|
+
"entity_type": 2.0,
|
|
36
|
+
"topic": 1.5,
|
|
37
|
+
"kind": 1.5,
|
|
38
|
+
"text": 1.0,
|
|
39
|
+
}
|
|
40
|
+
BM25_K1 = 1.2
|
|
41
|
+
BM25_B = 0.75
|
|
42
|
+
MIN_RELEVANCE_SCORE = 1.0
|
|
43
|
+
|
|
44
|
+
_FINAL_CONTEXT_FILENAMES = (
|
|
45
|
+
"robert_context.json",
|
|
46
|
+
"aqme_context.json",
|
|
47
|
+
"ui_context.json",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_TOKEN_RE = re.compile(r"[a-z0-9_]+")
|
|
52
|
+
_HTML_TAG_RE = re.compile(r"<[^>]+>")
|
|
53
|
+
_MULTISPACE_RE = re.compile(r"\s+")
|
|
54
|
+
_TUTORIAL_TAB_HINTS = (
|
|
55
|
+
("Workflow", ("workflow page", "workflow tab", "main workflow")),
|
|
56
|
+
("AQME descriptors", ("aqme descriptors", "descriptor settings")),
|
|
57
|
+
("Advanced options", ("advanced options page", "advanced settings")),
|
|
58
|
+
("MolSSI Databases", ("molssi databases", "descriptor libraries", "molssi")),
|
|
59
|
+
("Advanced Options", ("advanced options", "general", "curate", "generate", "predict settings")),
|
|
60
|
+
("Results", ("results tab", "results view", "result views")),
|
|
61
|
+
("CheckML", ("check model tab", "checkml tab", "evaluate my model")),
|
|
62
|
+
("Predictions", ("predictions tab", "prediction results", "predict workflow", "external test")),
|
|
63
|
+
("Images", ("images tab", "generated figures", "browse these figures")),
|
|
64
|
+
("Reports", ("reports tab", "pdf report", "report summarizes")),
|
|
65
|
+
("AQME", ("aqme tab", "aqme workflow", "run aqme", "descriptors")),
|
|
66
|
+
("ROBERT", ("robert tab", "run robert", "full workflow", "machine learning workflow")),
|
|
67
|
+
)
|
|
68
|
+
_AQME_MODULES = {"AQME", "QDESCP", "CSEARCH", "CMIN", "QCORR", "QPREP"}
|
|
69
|
+
_ROBERT_ML_MODULES = {"ROBERT", "CURATE", "GENERATE", "VERIFY", "PREDICT", "REPORT", "FULL_WORKFLOW"}
|
|
70
|
+
_UI_TAB_NAMES = {"Workflow", "ROBERT", "AQME descriptors", "AQME", "Advanced options", "Advanced Options", "Results", "Reports", "Predictions", "Images", "MolSSI databases", "MolSSI Databases", "CheckML"}
|
|
71
|
+
_LOW_SIGNAL_TITLES = {"overview", "developement", "reference", "module", "main"}
|
|
72
|
+
_STOP_WORDS = {
|
|
73
|
+
"a", "about", "an", "and", "are", "do", "does", "for", "how", "i", "in",
|
|
74
|
+
"is", "it", "me", "of", "on", "please", "something", "tell", "the", "this",
|
|
75
|
+
"to", "what", "when", "where", "which", "why", "with", "you",
|
|
76
|
+
"como", "cual", "de", "el", "es", "esta", "explica", "explicas", "funciona",
|
|
77
|
+
"la", "las", "lo", "los", "mi", "necesito", "para", "por", "que", "son",
|
|
78
|
+
"un", "una",
|
|
79
|
+
}
|
|
80
|
+
_TERM_ALIASES = (
|
|
81
|
+
(re.compile(r"\bflujo\s+de\s+trabajo\b"), "workflow"),
|
|
82
|
+
(re.compile(r"\bdescriptores?\b"), "descriptors"),
|
|
83
|
+
(re.compile(r"\bcalcul(?:a|as|an|amos|ar|ando|ado|o)\b"), "calculate"),
|
|
84
|
+
(re.compile(r"\bmodelos?\b"), "model"),
|
|
85
|
+
(re.compile(r"\b(?:prediccion|predicciones)\b"), "predictions"),
|
|
86
|
+
(re.compile(r"\bregresi[oó]n\b"), "regression"),
|
|
87
|
+
(re.compile(r"\bclasificaci[oó]n\b"), "classification"),
|
|
88
|
+
(re.compile(r"\binformes?\b"), "reports"),
|
|
89
|
+
(re.compile(r"\br\s*(?:squared|2)\b"), "r2"),
|
|
90
|
+
(re.compile(r"\bno[\s_-]+pfi\b"), "no_pfi"),
|
|
91
|
+
(re.compile(r"\btarget\s+column\b"), "target_column"),
|
|
92
|
+
(re.compile(r"\bcolumna\s+objetivo\b"), "target_column"),
|
|
93
|
+
(re.compile(r"\badvanced\s+options\b"), "advanced_options"),
|
|
94
|
+
(re.compile(r"\bfull\s+workflow\b"), "full_workflow"),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def normalize_terms(value: object) -> tuple[str, ...]:
|
|
99
|
+
"""Return English lexical terms after stable Unicode and declared alias normalization."""
|
|
100
|
+
if value is None:
|
|
101
|
+
return ()
|
|
102
|
+
if isinstance(value, (list, tuple, set)):
|
|
103
|
+
return tuple(term for item in value for term in normalize_terms(item))
|
|
104
|
+
normalized = unicodedata.normalize("NFKD", str(value)).casefold()
|
|
105
|
+
normalized = "".join(
|
|
106
|
+
character for character in normalized if not unicodedata.combining(character)
|
|
107
|
+
)
|
|
108
|
+
for pattern, replacement in _TERM_ALIASES:
|
|
109
|
+
normalized = pattern.sub(replacement, normalized)
|
|
110
|
+
return tuple(
|
|
111
|
+
term for term in _TOKEN_RE.findall(normalized)
|
|
112
|
+
if term not in _STOP_WORDS
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _canonical_question_pattern(value: object) -> tuple[str, ...]:
|
|
117
|
+
"""Canonicalize exact patterns without collapsing interrogative intent."""
|
|
118
|
+
normalized = unicodedata.normalize("NFKD", str(value or "")).casefold()
|
|
119
|
+
normalized = "".join(
|
|
120
|
+
character for character in normalized if not unicodedata.combining(character)
|
|
121
|
+
)
|
|
122
|
+
for pattern, replacement in _TERM_ALIASES:
|
|
123
|
+
normalized = pattern.sub(replacement, normalized)
|
|
124
|
+
interrogatives = {"what", "when", "where", "which", "who", "why", "how"}
|
|
125
|
+
return tuple(
|
|
126
|
+
term for term in _TOKEN_RE.findall(normalized)
|
|
127
|
+
if term in interrogatives or term not in _STOP_WORDS
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _tokenize(value: object) -> set[str]:
|
|
132
|
+
if value is None:
|
|
133
|
+
return set()
|
|
134
|
+
if isinstance(value, (list, tuple, set)):
|
|
135
|
+
tokens: set[str] = set()
|
|
136
|
+
for item in value:
|
|
137
|
+
tokens.update(_tokenize(item))
|
|
138
|
+
return tokens
|
|
139
|
+
return set(_TOKEN_RE.findall(str(value).lower()))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _ensure_sequence(value: object) -> list[object]:
|
|
143
|
+
if value is None:
|
|
144
|
+
return []
|
|
145
|
+
if isinstance(value, list):
|
|
146
|
+
return value
|
|
147
|
+
if isinstance(value, tuple):
|
|
148
|
+
return list(value)
|
|
149
|
+
return [value]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _clean_tutorial_text(text: str) -> str:
|
|
153
|
+
cleaned = text.replace("<br>", "\n").replace("<br/>", "\n").replace("<br />", "\n")
|
|
154
|
+
cleaned = _HTML_TAG_RE.sub("", cleaned)
|
|
155
|
+
cleaned = cleaned.replace(" ", " ").replace("\r", "\n")
|
|
156
|
+
cleaned = _MULTISPACE_RE.sub(" ", cleaned)
|
|
157
|
+
return cleaned.strip()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _infer_tutorial_tab(stem: str, text: str) -> str:
|
|
161
|
+
lowered = f"{stem} {text}".lower()
|
|
162
|
+
for tab_name, hints in _TUTORIAL_TAB_HINTS:
|
|
163
|
+
if any(hint in lowered for hint in hints):
|
|
164
|
+
return tab_name
|
|
165
|
+
return "ROBERT"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _tutorial_keywords(stem: str, tab: str, text: str) -> tuple[str, ...]:
|
|
169
|
+
stem_label = stem.replace("_", " ").replace("-", " ").strip()
|
|
170
|
+
keywords = [stem_label, tab]
|
|
171
|
+
sentences = [part.strip() for part in re.split(r"[.!?]", text) if part.strip()]
|
|
172
|
+
if sentences:
|
|
173
|
+
keywords.append(sentences[0])
|
|
174
|
+
return tuple(keyword for keyword in keywords if keyword)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _default_title(text: str, chunk_id: str) -> str:
|
|
178
|
+
sentences = [part.strip() for part in re.split(r"[.!?]", text) if part.strip()]
|
|
179
|
+
if sentences:
|
|
180
|
+
return sentences[0][:120]
|
|
181
|
+
return chunk_id
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _coerce_priority(value: object, default: float = 0.5) -> float:
|
|
185
|
+
try:
|
|
186
|
+
return float(value)
|
|
187
|
+
except (TypeError, ValueError):
|
|
188
|
+
return default
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _normalize_text(value: object) -> str:
|
|
192
|
+
return " ".join(str(value or "").strip().lower().split())
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass(frozen=True, slots=True)
|
|
196
|
+
class KnowledgeChunk:
|
|
197
|
+
id: str
|
|
198
|
+
source: str
|
|
199
|
+
topic: str
|
|
200
|
+
tab: str
|
|
201
|
+
keywords: tuple[str, ...]
|
|
202
|
+
text: str
|
|
203
|
+
source_file: str = ""
|
|
204
|
+
program: str = ""
|
|
205
|
+
module: str = ""
|
|
206
|
+
kind: str = "concept"
|
|
207
|
+
title: str = ""
|
|
208
|
+
question_patterns: tuple[str, ...] = ()
|
|
209
|
+
priority: float = 0.5
|
|
210
|
+
audience: str = ""
|
|
211
|
+
source_tier: str = ""
|
|
212
|
+
entity_type: str = ""
|
|
213
|
+
entity_id: str = ""
|
|
214
|
+
aliases: tuple[str, ...] = ()
|
|
215
|
+
related_ids: tuple[str, ...] = ()
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@dataclass(frozen=True, slots=True)
|
|
219
|
+
class SearchResult:
|
|
220
|
+
chunk: KnowledgeChunk
|
|
221
|
+
score: float
|
|
222
|
+
matched_terms: tuple[str, ...] = ()
|
|
223
|
+
query_terms: tuple[str, ...] = ()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
@dataclass(frozen=True, slots=True)
|
|
227
|
+
class IndexedChunk:
|
|
228
|
+
chunk: KnowledgeChunk
|
|
229
|
+
field_counters: Mapping[str, Counter[str]]
|
|
230
|
+
body_length: int
|
|
231
|
+
content_fingerprint: str
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _build_indexed_chunk(chunk: KnowledgeChunk) -> IndexedChunk:
|
|
235
|
+
counters = {
|
|
236
|
+
field: Counter(normalize_terms(getattr(chunk, field)))
|
|
237
|
+
for field in FIELD_WEIGHTS
|
|
238
|
+
}
|
|
239
|
+
normalized_content = " ".join(
|
|
240
|
+
unicodedata.normalize("NFKC", chunk.text).casefold().split()
|
|
241
|
+
)
|
|
242
|
+
fingerprint = hashlib.sha1(normalized_content.encode("utf-8")).hexdigest()
|
|
243
|
+
return IndexedChunk(
|
|
244
|
+
chunk=chunk,
|
|
245
|
+
field_counters=counters,
|
|
246
|
+
body_length=sum(counters["text"].values()),
|
|
247
|
+
content_fingerprint=fingerprint,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class KnowledgeBase:
|
|
252
|
+
def __init__(
|
|
253
|
+
self,
|
|
254
|
+
chunks: Sequence[KnowledgeChunk],
|
|
255
|
+
issues: Sequence[KnowledgeLoadIssue] = (),
|
|
256
|
+
):
|
|
257
|
+
self._chunks = list(chunks)
|
|
258
|
+
self._issues = tuple(issues)
|
|
259
|
+
self._index = tuple(_build_indexed_chunk(chunk) for chunk in self._chunks)
|
|
260
|
+
self._document_count = len(self._index)
|
|
261
|
+
self._average_body_length = (
|
|
262
|
+
sum(item.body_length for item in self._index) / self._document_count
|
|
263
|
+
if self._document_count else 0.0
|
|
264
|
+
)
|
|
265
|
+
document_frequencies: Counter[str] = Counter()
|
|
266
|
+
for item in self._index:
|
|
267
|
+
document_frequencies.update(
|
|
268
|
+
set().union(*(counter.keys() for counter in item.field_counters.values()))
|
|
269
|
+
)
|
|
270
|
+
self._document_frequencies = document_frequencies
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def issues(self) -> tuple[KnowledgeLoadIssue, ...]:
|
|
274
|
+
return self._issues
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def is_degraded(self) -> bool:
|
|
278
|
+
return bool(self._issues)
|
|
279
|
+
|
|
280
|
+
def chunks_for_source(self, source: str) -> list[KnowledgeChunk]:
|
|
281
|
+
normalized = _normalize_text(source)
|
|
282
|
+
if not normalized:
|
|
283
|
+
return []
|
|
284
|
+
return [chunk for chunk in self._chunks if _normalize_text(chunk.source) == normalized]
|
|
285
|
+
|
|
286
|
+
@classmethod
|
|
287
|
+
def from_records(cls, records: Iterable[dict[str, object]]) -> "KnowledgeBase":
|
|
288
|
+
chunks = [cls._record_to_chunk(record, source_fallback="memory") for record in records]
|
|
289
|
+
return cls(chunks)
|
|
290
|
+
|
|
291
|
+
@staticmethod
|
|
292
|
+
def _with_json_path(
|
|
293
|
+
issue: KnowledgeLoadIssue,
|
|
294
|
+
json_path: str,
|
|
295
|
+
) -> KnowledgeLoadIssue:
|
|
296
|
+
return KnowledgeLoadIssue(
|
|
297
|
+
code=issue.code,
|
|
298
|
+
message=f"{json_path}: {issue.message}",
|
|
299
|
+
source=Path(issue.source).name,
|
|
300
|
+
record_id=issue.record_id,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
@classmethod
|
|
304
|
+
def _validated_context_payloads(
|
|
305
|
+
cls,
|
|
306
|
+
payloads: Mapping[str, object],
|
|
307
|
+
*,
|
|
308
|
+
include_missing_domains: bool,
|
|
309
|
+
) -> tuple[dict[str, object], list[KnowledgeLoadIssue]]:
|
|
310
|
+
sanitized: dict[str, object] = {}
|
|
311
|
+
issues: list[KnowledgeLoadIssue] = []
|
|
312
|
+
|
|
313
|
+
if not isinstance(payloads, Mapping):
|
|
314
|
+
return {}, [
|
|
315
|
+
KnowledgeLoadIssue(
|
|
316
|
+
"invalid_context_set",
|
|
317
|
+
"$: Knowledge contexts must be supplied as a domain mapping.",
|
|
318
|
+
"context set",
|
|
319
|
+
)
|
|
320
|
+
]
|
|
321
|
+
|
|
322
|
+
for domain in DOMAINS:
|
|
323
|
+
if domain not in payloads:
|
|
324
|
+
if include_missing_domains:
|
|
325
|
+
issues.append(
|
|
326
|
+
KnowledgeLoadIssue(
|
|
327
|
+
"missing_context_domain",
|
|
328
|
+
f"$: Context set is missing domain '{domain}'.",
|
|
329
|
+
"context set",
|
|
330
|
+
)
|
|
331
|
+
)
|
|
332
|
+
continue
|
|
333
|
+
|
|
334
|
+
payload = payloads[domain]
|
|
335
|
+
source = f"{domain}_context.json"
|
|
336
|
+
if not isinstance(payload, Mapping):
|
|
337
|
+
issues.extend(
|
|
338
|
+
cls._with_json_path(issue, "$")
|
|
339
|
+
for issue in validate_context_payload(payload, domain, source)
|
|
340
|
+
)
|
|
341
|
+
continue
|
|
342
|
+
|
|
343
|
+
structural_payload = dict(payload)
|
|
344
|
+
for section in CONTEXT_SECTIONS:
|
|
345
|
+
if isinstance(structural_payload.get(section), list):
|
|
346
|
+
structural_payload[section] = []
|
|
347
|
+
file_issues = validate_context_payload(
|
|
348
|
+
structural_payload,
|
|
349
|
+
expected_domain=domain,
|
|
350
|
+
source=source,
|
|
351
|
+
)
|
|
352
|
+
if file_issues:
|
|
353
|
+
issues.extend(cls._with_json_path(issue, "$") for issue in file_issues)
|
|
354
|
+
continue
|
|
355
|
+
|
|
356
|
+
clean_payload = dict(payload)
|
|
357
|
+
for section in CONTEXT_SECTIONS:
|
|
358
|
+
clean_records: list[object] = []
|
|
359
|
+
section_records = payload[section]
|
|
360
|
+
for index, record in enumerate(section_records):
|
|
361
|
+
json_path = f"$.{section}[{index}]"
|
|
362
|
+
if not isinstance(record, Mapping):
|
|
363
|
+
issues.append(
|
|
364
|
+
KnowledgeLoadIssue(
|
|
365
|
+
"invalid_record",
|
|
366
|
+
f"{json_path}: Context record must be an object.",
|
|
367
|
+
source,
|
|
368
|
+
)
|
|
369
|
+
)
|
|
370
|
+
continue
|
|
371
|
+
probe = dict(structural_payload)
|
|
372
|
+
probe[section] = [record]
|
|
373
|
+
record_issues = validate_context_payload(
|
|
374
|
+
probe,
|
|
375
|
+
expected_domain=domain,
|
|
376
|
+
source=source,
|
|
377
|
+
)
|
|
378
|
+
if record_issues:
|
|
379
|
+
issues.extend(
|
|
380
|
+
cls._with_json_path(issue, json_path)
|
|
381
|
+
for issue in record_issues
|
|
382
|
+
)
|
|
383
|
+
continue
|
|
384
|
+
clean_records.append(dict(record))
|
|
385
|
+
clean_payload[section] = clean_records
|
|
386
|
+
sanitized[domain] = clean_payload
|
|
387
|
+
|
|
388
|
+
unexpected_domains = sorted(
|
|
389
|
+
(domain for domain in payloads if domain not in DOMAINS),
|
|
390
|
+
key=str,
|
|
391
|
+
)
|
|
392
|
+
for domain in unexpected_domains:
|
|
393
|
+
issues.append(
|
|
394
|
+
KnowledgeLoadIssue(
|
|
395
|
+
"unexpected_context_domain",
|
|
396
|
+
f"$: Context set contains unexpected domain {domain!r}.",
|
|
397
|
+
"context set",
|
|
398
|
+
)
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
cross_issue_codes = {
|
|
402
|
+
"schema_version_mismatch",
|
|
403
|
+
"version_mismatch",
|
|
404
|
+
"duplicate_id",
|
|
405
|
+
"duplicate_entity_id",
|
|
406
|
+
"unresolved_related_id",
|
|
407
|
+
}
|
|
408
|
+
issues.extend(
|
|
409
|
+
cls._with_json_path(issue, "$")
|
|
410
|
+
for issue in validate_context_set(sanitized)
|
|
411
|
+
if issue.code in cross_issue_codes
|
|
412
|
+
)
|
|
413
|
+
return sanitized, issues
|
|
414
|
+
|
|
415
|
+
@classmethod
|
|
416
|
+
def _from_payloads(
|
|
417
|
+
cls,
|
|
418
|
+
payloads: Mapping[str, object],
|
|
419
|
+
*,
|
|
420
|
+
strict: bool,
|
|
421
|
+
initial_issues: Sequence[KnowledgeLoadIssue] = (),
|
|
422
|
+
include_missing_domains: bool,
|
|
423
|
+
) -> "KnowledgeBase":
|
|
424
|
+
sanitized, validation_issues = cls._validated_context_payloads(
|
|
425
|
+
payloads,
|
|
426
|
+
include_missing_domains=include_missing_domains,
|
|
427
|
+
)
|
|
428
|
+
issues = [*initial_issues, *validation_issues]
|
|
429
|
+
chunks: list[KnowledgeChunk] = []
|
|
430
|
+
for domain in DOMAINS:
|
|
431
|
+
payload = sanitized.get(domain)
|
|
432
|
+
if isinstance(payload, dict):
|
|
433
|
+
chunks.extend(
|
|
434
|
+
cls._context_object_to_chunks(
|
|
435
|
+
payload,
|
|
436
|
+
source_fallback=f"{domain}_context.json",
|
|
437
|
+
)
|
|
438
|
+
)
|
|
439
|
+
if strict and issues:
|
|
440
|
+
raise KnowledgeValidationError(issues)
|
|
441
|
+
return cls(chunks, issues)
|
|
442
|
+
|
|
443
|
+
@classmethod
|
|
444
|
+
def from_payloads(
|
|
445
|
+
cls,
|
|
446
|
+
payloads: Mapping[str, object],
|
|
447
|
+
strict: bool = True,
|
|
448
|
+
) -> "KnowledgeBase":
|
|
449
|
+
return cls._from_payloads(
|
|
450
|
+
payloads,
|
|
451
|
+
strict=strict,
|
|
452
|
+
include_missing_domains=True,
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
@staticmethod
|
|
456
|
+
def _exact_final_paths(base_dir: Path) -> dict[str, Path]:
|
|
457
|
+
try:
|
|
458
|
+
entries_by_name = {
|
|
459
|
+
entry.name: entry
|
|
460
|
+
for entry in base_dir.iterdir()
|
|
461
|
+
if entry.is_file() and entry.name in _FINAL_CONTEXT_FILENAMES
|
|
462
|
+
}
|
|
463
|
+
except OSError:
|
|
464
|
+
return {}
|
|
465
|
+
return {
|
|
466
|
+
name: entries_by_name[name]
|
|
467
|
+
for name in _FINAL_CONTEXT_FILENAMES
|
|
468
|
+
if name in entries_by_name
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
@classmethod
|
|
472
|
+
def from_directory(
|
|
473
|
+
cls,
|
|
474
|
+
directory: str | Path | None = None,
|
|
475
|
+
tutorials_dir: str | Path | None = None,
|
|
476
|
+
strict: bool = True,
|
|
477
|
+
allow_generic_json: bool = False,
|
|
478
|
+
) -> "KnowledgeBase":
|
|
479
|
+
root_dir = Path(__file__).resolve().parent
|
|
480
|
+
base_dir = Path(directory) if directory is not None else root_dir / "knowledge"
|
|
481
|
+
tutorials_path = Path(tutorials_dir) if tutorials_dir is not None else None
|
|
482
|
+
final_paths = cls._exact_final_paths(base_dir)
|
|
483
|
+
if final_paths:
|
|
484
|
+
issues: list[KnowledgeLoadIssue] = []
|
|
485
|
+
payloads: dict[str, object] = {}
|
|
486
|
+
for name in _FINAL_CONTEXT_FILENAMES:
|
|
487
|
+
domain = name.removesuffix("_context.json")
|
|
488
|
+
path = final_paths.get(name)
|
|
489
|
+
if path is None:
|
|
490
|
+
issues.append(
|
|
491
|
+
KnowledgeLoadIssue(
|
|
492
|
+
"missing_final_context",
|
|
493
|
+
f"$: Required final context '{name}' is missing.",
|
|
494
|
+
name,
|
|
495
|
+
)
|
|
496
|
+
)
|
|
497
|
+
continue
|
|
498
|
+
try:
|
|
499
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
500
|
+
payloads[domain] = json.load(handle)
|
|
501
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
502
|
+
issues.append(
|
|
503
|
+
KnowledgeLoadIssue(
|
|
504
|
+
"invalid_json",
|
|
505
|
+
f"$: Could not read valid JSON ({type(exc).__name__}).",
|
|
506
|
+
path.name,
|
|
507
|
+
)
|
|
508
|
+
)
|
|
509
|
+
knowledge_base = cls._from_payloads(
|
|
510
|
+
payloads,
|
|
511
|
+
strict=False,
|
|
512
|
+
initial_issues=issues,
|
|
513
|
+
include_missing_domains=False,
|
|
514
|
+
)
|
|
515
|
+
chunks = list(knowledge_base._chunks)
|
|
516
|
+
issues = list(knowledge_base.issues)
|
|
517
|
+
if not strict and directory is None:
|
|
518
|
+
for domain in DOMAINS:
|
|
519
|
+
payload = payloads.get(domain)
|
|
520
|
+
if isinstance(payload, dict) and "schema_version" not in payload:
|
|
521
|
+
try:
|
|
522
|
+
chunks.extend(
|
|
523
|
+
cls._context_object_to_chunks(
|
|
524
|
+
payload,
|
|
525
|
+
source_fallback=f"{domain}_context.json",
|
|
526
|
+
)
|
|
527
|
+
)
|
|
528
|
+
except (TypeError, ValueError):
|
|
529
|
+
pass
|
|
530
|
+
elif directory is not None and allow_generic_json:
|
|
531
|
+
chunks, issues = cls._load_generic_json(base_dir)
|
|
532
|
+
else:
|
|
533
|
+
chunks = []
|
|
534
|
+
issues = [
|
|
535
|
+
KnowledgeLoadIssue(
|
|
536
|
+
"missing_final_context",
|
|
537
|
+
f"$: Required final context '{name}' is missing.",
|
|
538
|
+
name,
|
|
539
|
+
)
|
|
540
|
+
for name in _FINAL_CONTEXT_FILENAMES
|
|
541
|
+
]
|
|
542
|
+
|
|
543
|
+
if tutorials_path is not None:
|
|
544
|
+
try:
|
|
545
|
+
chunks.extend(cls._load_tutorial_chunks(tutorials_path))
|
|
546
|
+
except (OSError, UnicodeError) as exc:
|
|
547
|
+
issues.append(
|
|
548
|
+
KnowledgeLoadIssue(
|
|
549
|
+
"invalid_tutorial",
|
|
550
|
+
f"$: Could not load tutorial markdown ({type(exc).__name__}).",
|
|
551
|
+
tutorials_path.name,
|
|
552
|
+
)
|
|
553
|
+
)
|
|
554
|
+
if strict and issues:
|
|
555
|
+
raise KnowledgeValidationError(issues)
|
|
556
|
+
return cls(chunks, issues)
|
|
557
|
+
|
|
558
|
+
@classmethod
|
|
559
|
+
def _load_generic_json(
|
|
560
|
+
cls,
|
|
561
|
+
base_dir: Path,
|
|
562
|
+
) -> tuple[list[KnowledgeChunk], list[KnowledgeLoadIssue]]:
|
|
563
|
+
chunks: list[KnowledgeChunk] = []
|
|
564
|
+
issues: list[KnowledgeLoadIssue] = []
|
|
565
|
+
json_paths = sorted(base_dir.glob("*.json"))
|
|
566
|
+
for path in json_paths:
|
|
567
|
+
try:
|
|
568
|
+
with path.open("r", encoding="utf-8") as handle:
|
|
569
|
+
payload = json.load(handle)
|
|
570
|
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
|
571
|
+
issues.append(
|
|
572
|
+
KnowledgeLoadIssue(
|
|
573
|
+
"invalid_json",
|
|
574
|
+
f"{path.name}: invalid JSON at $ ({type(exc).__name__}).",
|
|
575
|
+
path.name,
|
|
576
|
+
)
|
|
577
|
+
)
|
|
578
|
+
continue
|
|
579
|
+
if isinstance(payload, dict):
|
|
580
|
+
try:
|
|
581
|
+
chunks.extend(cls._context_object_to_chunks(payload, source_fallback=path.name))
|
|
582
|
+
except (TypeError, ValueError) as exc:
|
|
583
|
+
issues.append(
|
|
584
|
+
KnowledgeLoadIssue(
|
|
585
|
+
"invalid_payload",
|
|
586
|
+
f"{path.name}: {exc} at $.",
|
|
587
|
+
path.name,
|
|
588
|
+
)
|
|
589
|
+
)
|
|
590
|
+
continue
|
|
591
|
+
if not isinstance(payload, list):
|
|
592
|
+
issues.append(
|
|
593
|
+
KnowledgeLoadIssue(
|
|
594
|
+
"invalid_payload",
|
|
595
|
+
f"{path.name}: expected JSON object or array payload at $.",
|
|
596
|
+
path.name,
|
|
597
|
+
)
|
|
598
|
+
)
|
|
599
|
+
continue
|
|
600
|
+
for index, record in enumerate(payload):
|
|
601
|
+
if not isinstance(record, dict):
|
|
602
|
+
issues.append(
|
|
603
|
+
KnowledgeLoadIssue(
|
|
604
|
+
"invalid_record",
|
|
605
|
+
f"{path.name}: record {index} must be an object, got "
|
|
606
|
+
f"{type(record).__name__} at $[{index}].",
|
|
607
|
+
path.name,
|
|
608
|
+
)
|
|
609
|
+
)
|
|
610
|
+
continue
|
|
611
|
+
try:
|
|
612
|
+
chunks.append(cls._record_to_chunk(record, source_fallback=path.name))
|
|
613
|
+
except (TypeError, ValueError) as exc:
|
|
614
|
+
issues.append(
|
|
615
|
+
KnowledgeLoadIssue(
|
|
616
|
+
"invalid_record",
|
|
617
|
+
f"{path.name}: {exc} at $[{index}].",
|
|
618
|
+
path.name,
|
|
619
|
+
str(record.get("id", "")),
|
|
620
|
+
)
|
|
621
|
+
)
|
|
622
|
+
return chunks, issues
|
|
623
|
+
|
|
624
|
+
@classmethod
|
|
625
|
+
def _context_object_to_chunks(
|
|
626
|
+
cls,
|
|
627
|
+
payload: dict[str, object],
|
|
628
|
+
source_fallback: str,
|
|
629
|
+
) -> list[KnowledgeChunk]:
|
|
630
|
+
domain = str(payload.get("domain", "")).strip()
|
|
631
|
+
version = str(payload.get("version", "")).strip()
|
|
632
|
+
chunks: list[KnowledgeChunk] = []
|
|
633
|
+
|
|
634
|
+
overview = payload.get("overview") or {}
|
|
635
|
+
if isinstance(overview, dict) and overview.get("text"):
|
|
636
|
+
overview_program = "AQME" if domain == "aqme" else domain.upper() or "ROBERT"
|
|
637
|
+
overview_tab = "AQME" if domain == "aqme" else "ROBERT"
|
|
638
|
+
chunks.append(
|
|
639
|
+
cls._record_to_chunk(
|
|
640
|
+
{
|
|
641
|
+
"id": f"{domain or 'knowledge'}-overview",
|
|
642
|
+
"source": source_fallback,
|
|
643
|
+
"topic": "overview",
|
|
644
|
+
"tab": overview.get("tab", overview_tab),
|
|
645
|
+
"program": overview.get("program", overview_program),
|
|
646
|
+
"module": overview.get("module", "OVERVIEW"),
|
|
647
|
+
"kind": overview.get("kind", "concept"),
|
|
648
|
+
"title": overview.get("title", f"{domain.title()} overview".strip()),
|
|
649
|
+
"keywords": [domain, version, "overview"],
|
|
650
|
+
"text": overview["text"],
|
|
651
|
+
"priority": overview.get("priority", 1.0),
|
|
652
|
+
},
|
|
653
|
+
source_fallback=source_fallback,
|
|
654
|
+
)
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
section_kinds = {
|
|
658
|
+
"workflows": "workflow",
|
|
659
|
+
"modules": "module",
|
|
660
|
+
"interface": "interface",
|
|
661
|
+
"parameters": "parameter",
|
|
662
|
+
"concepts": "concept",
|
|
663
|
+
"inputs_outputs": "output",
|
|
664
|
+
"tutorials": "tutorial",
|
|
665
|
+
"troubleshooting": "diagnostic",
|
|
666
|
+
}
|
|
667
|
+
for section_name, default_kind in section_kinds.items():
|
|
668
|
+
section_records = payload.get(section_name) or []
|
|
669
|
+
if not isinstance(section_records, list):
|
|
670
|
+
raise ValueError(f"{source_fallback}: section {section_name} must be a list")
|
|
671
|
+
for index, section_record in enumerate(section_records):
|
|
672
|
+
if not isinstance(section_record, dict):
|
|
673
|
+
raise ValueError(
|
|
674
|
+
f"{source_fallback}: section {section_name} record {index} must be an object"
|
|
675
|
+
)
|
|
676
|
+
chunks.append(
|
|
677
|
+
cls._record_to_chunk(
|
|
678
|
+
{
|
|
679
|
+
"id": section_record.get("id")
|
|
680
|
+
or f"{domain or 'knowledge'}-{section_name}-{index + 1}",
|
|
681
|
+
"source": section_record.get("source", source_fallback),
|
|
682
|
+
"topic": section_record.get("topic", section_name),
|
|
683
|
+
"kind": section_record.get("kind", default_kind),
|
|
684
|
+
"tab": section_record.get("tab", ""),
|
|
685
|
+
"program": section_record.get("program", domain.upper()),
|
|
686
|
+
"module": section_record.get("module", section_name.upper()),
|
|
687
|
+
"title": section_record.get("title", ""),
|
|
688
|
+
"keywords": section_record.get("keywords", []),
|
|
689
|
+
"question_patterns": section_record.get("question_patterns", []),
|
|
690
|
+
"text": section_record.get("text", ""),
|
|
691
|
+
"priority": section_record.get("priority", 0.7),
|
|
692
|
+
"source_file": section_record.get("source_file", ""),
|
|
693
|
+
"audience": section_record.get("audience", ""),
|
|
694
|
+
"source_tier": section_record.get("source_tier", ""),
|
|
695
|
+
"entity_type": section_record.get("entity_type", ""),
|
|
696
|
+
"entity_id": section_record.get("entity_id", ""),
|
|
697
|
+
"aliases": section_record.get("aliases", []),
|
|
698
|
+
"related_ids": section_record.get("related_ids", []),
|
|
699
|
+
},
|
|
700
|
+
source_fallback=source_fallback,
|
|
701
|
+
)
|
|
702
|
+
)
|
|
703
|
+
return chunks
|
|
704
|
+
|
|
705
|
+
@classmethod
|
|
706
|
+
def _load_tutorial_chunks(cls, tutorials_dir: Path) -> list[KnowledgeChunk]:
|
|
707
|
+
if not tutorials_dir.exists():
|
|
708
|
+
return []
|
|
709
|
+
|
|
710
|
+
chunks: list[KnowledgeChunk] = []
|
|
711
|
+
for path in sorted(tutorials_dir.glob("*.md")):
|
|
712
|
+
raw_text = path.read_text(encoding="utf-8")
|
|
713
|
+
blocks = [block.strip() for block in raw_text.split("---") if block.strip()]
|
|
714
|
+
for index, block in enumerate(blocks, start=1):
|
|
715
|
+
text = _clean_tutorial_text(block)
|
|
716
|
+
if not text:
|
|
717
|
+
continue
|
|
718
|
+
tab = _infer_tutorial_tab(path.stem, text)
|
|
719
|
+
chunk_id = f"tutorial-{path.stem}-{index}"
|
|
720
|
+
chunks.append(
|
|
721
|
+
KnowledgeChunk(
|
|
722
|
+
id=chunk_id,
|
|
723
|
+
source=f"tutorial:{path.name}",
|
|
724
|
+
topic="tutorial",
|
|
725
|
+
tab=tab,
|
|
726
|
+
keywords=_tutorial_keywords(path.stem, tab, text),
|
|
727
|
+
text=text,
|
|
728
|
+
source_file=path.name,
|
|
729
|
+
program="ROBERT",
|
|
730
|
+
module=tab.upper().replace(" ", "_"),
|
|
731
|
+
kind="tutorial",
|
|
732
|
+
title=_default_title(text, chunk_id),
|
|
733
|
+
question_patterns=(path.stem.replace("_", " ").replace("-", " "), tab),
|
|
734
|
+
priority=0.65,
|
|
735
|
+
)
|
|
736
|
+
)
|
|
737
|
+
return chunks
|
|
738
|
+
|
|
739
|
+
@staticmethod
|
|
740
|
+
def _record_to_chunk(record: dict[str, object], source_fallback: str) -> KnowledgeChunk:
|
|
741
|
+
chunk_id = str(record.get("id", "")).strip()
|
|
742
|
+
text = str(record.get("text", "")).strip()
|
|
743
|
+
if not chunk_id:
|
|
744
|
+
raise ValueError("knowledge record is missing required field: id")
|
|
745
|
+
if not text:
|
|
746
|
+
raise ValueError("knowledge record is missing required field: text")
|
|
747
|
+
|
|
748
|
+
keywords = tuple(str(keyword) for keyword in _ensure_sequence(record.get("keywords")))
|
|
749
|
+
question_patterns = tuple(
|
|
750
|
+
str(pattern) for pattern in _ensure_sequence(record.get("question_patterns"))
|
|
751
|
+
)
|
|
752
|
+
aliases = tuple(str(alias) for alias in _ensure_sequence(record.get("aliases")))
|
|
753
|
+
related_ids = tuple(
|
|
754
|
+
str(related_id) for related_id in _ensure_sequence(record.get("related_ids"))
|
|
755
|
+
)
|
|
756
|
+
source = str(record.get("source") or source_fallback)
|
|
757
|
+
kind = str(record.get("kind") or record.get("topic") or "concept")
|
|
758
|
+
return KnowledgeChunk(
|
|
759
|
+
id=chunk_id,
|
|
760
|
+
source=source,
|
|
761
|
+
topic=str(record.get("topic") or kind),
|
|
762
|
+
tab=str(record.get("tab", "")),
|
|
763
|
+
keywords=keywords,
|
|
764
|
+
text=text,
|
|
765
|
+
source_file=str(record.get("source_file", "")),
|
|
766
|
+
program=str(record.get("program", "")),
|
|
767
|
+
module=str(record.get("module", "")),
|
|
768
|
+
kind=kind,
|
|
769
|
+
title=str(record.get("title") or "").strip() or _default_title(text, chunk_id),
|
|
770
|
+
question_patterns=question_patterns,
|
|
771
|
+
priority=_coerce_priority(record.get("priority"), default=0.5),
|
|
772
|
+
audience=str(record.get("audience", "")),
|
|
773
|
+
source_tier=str(record.get("source_tier", "")),
|
|
774
|
+
entity_type=str(record.get("entity_type", "")),
|
|
775
|
+
entity_id=str(record.get("entity_id", "")),
|
|
776
|
+
aliases=aliases,
|
|
777
|
+
related_ids=related_ids,
|
|
778
|
+
)
|
|
779
|
+
|
|
780
|
+
@staticmethod
|
|
781
|
+
def _is_aqme_related(chunk: KnowledgeChunk) -> bool:
|
|
782
|
+
module = str(chunk.module or "").upper()
|
|
783
|
+
text = f"{chunk.title} {chunk.text} {' '.join(chunk.keywords)} {chunk.question_patterns}".lower()
|
|
784
|
+
return (
|
|
785
|
+
module in _AQME_MODULES
|
|
786
|
+
or str(chunk.tab or "") == "AQME"
|
|
787
|
+
or str(chunk.program or "").upper() == "AQME"
|
|
788
|
+
or any(term in text for term in ("aqme", "smiles", "qdescp", "chemdraw", "descriptor generation"))
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
@staticmethod
|
|
792
|
+
def _is_robert_related(chunk: KnowledgeChunk) -> bool:
|
|
793
|
+
module = str(chunk.module or "").upper()
|
|
794
|
+
text = f"{chunk.title} {chunk.text} {' '.join(chunk.keywords)} {chunk.question_patterns}".lower()
|
|
795
|
+
return (
|
|
796
|
+
module in _ROBERT_ML_MODULES
|
|
797
|
+
or str(chunk.program or "").upper() == "ROBERT"
|
|
798
|
+
or str(chunk.tab or "") in {"ROBERT", "Advanced Options", "Reports", "Predictions", "Images"}
|
|
799
|
+
or any(term in text for term in ("machine learning", "model", "curate", "generate", "verify", "predict", "report"))
|
|
800
|
+
)
|
|
801
|
+
|
|
802
|
+
@staticmethod
|
|
803
|
+
def _is_ui_related(chunk: KnowledgeChunk) -> bool:
|
|
804
|
+
source = str(chunk.source or "")
|
|
805
|
+
text = f"{chunk.title} {chunk.text} {' '.join(chunk.keywords)} {chunk.question_patterns}".lower()
|
|
806
|
+
return (
|
|
807
|
+
source.startswith("tutorial:")
|
|
808
|
+
or source == "easyrob_code_docstrings"
|
|
809
|
+
or str(chunk.tab or "") in _UI_TAB_NAMES
|
|
810
|
+
and any(term in text for term in (" tab", " button", "gui", "interface", "settings", "popup", "window"))
|
|
811
|
+
)
|
|
812
|
+
|
|
813
|
+
@staticmethod
|
|
814
|
+
def _lexical_score(
|
|
815
|
+
chunk: KnowledgeChunk,
|
|
816
|
+
question_terms: set[str],
|
|
817
|
+
workflow_terms: set[str],
|
|
818
|
+
console_terms: set[str],
|
|
819
|
+
) -> float:
|
|
820
|
+
chunk_terms = _tokenize(
|
|
821
|
+
(
|
|
822
|
+
chunk.topic,
|
|
823
|
+
chunk.tab,
|
|
824
|
+
chunk.text,
|
|
825
|
+
chunk.keywords,
|
|
826
|
+
chunk.title,
|
|
827
|
+
chunk.module,
|
|
828
|
+
chunk.program,
|
|
829
|
+
chunk.kind,
|
|
830
|
+
chunk.question_patterns,
|
|
831
|
+
)
|
|
832
|
+
)
|
|
833
|
+
keyword_terms = _tokenize(chunk.keywords)
|
|
834
|
+
topic_terms = _tokenize((chunk.topic, chunk.tab))
|
|
835
|
+
text_terms = _tokenize(chunk.text)
|
|
836
|
+
|
|
837
|
+
question_overlap = len(question_terms & chunk_terms)
|
|
838
|
+
keyword_overlap = len(question_terms & keyword_terms)
|
|
839
|
+
workflow_overlap = len(workflow_terms & (chunk_terms | keyword_terms | topic_terms))
|
|
840
|
+
console_overlap = len(console_terms & (chunk_terms | text_terms | topic_terms))
|
|
841
|
+
|
|
842
|
+
return (
|
|
843
|
+
question_overlap * 1.0
|
|
844
|
+
+ keyword_overlap * 2.0
|
|
845
|
+
+ workflow_overlap * 2.5
|
|
846
|
+
+ console_overlap * 1.5
|
|
847
|
+
)
|
|
848
|
+
|
|
849
|
+
@staticmethod
|
|
850
|
+
def _metadata_score(chunk: KnowledgeChunk, question_terms: set[str]) -> float:
|
|
851
|
+
title_terms = _tokenize(chunk.title)
|
|
852
|
+
module_terms = _tokenize((chunk.module, chunk.program))
|
|
853
|
+
pattern_terms = _tokenize(chunk.question_patterns)
|
|
854
|
+
return (
|
|
855
|
+
len(question_terms & title_terms) * 2.0
|
|
856
|
+
+ len(question_terms & module_terms) * 2.0
|
|
857
|
+
+ len(question_terms & pattern_terms) * 3.0
|
|
858
|
+
+ chunk.priority
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
@staticmethod
|
|
862
|
+
def _pattern_phrase_bonus(chunk: KnowledgeChunk, question: str) -> float:
|
|
863
|
+
normalized_question = _normalize_text(question)
|
|
864
|
+
if not normalized_question:
|
|
865
|
+
return 0.0
|
|
866
|
+
bonus = 0.0
|
|
867
|
+
for pattern in chunk.question_patterns:
|
|
868
|
+
normalized_pattern = _normalize_text(pattern)
|
|
869
|
+
if not normalized_pattern:
|
|
870
|
+
continue
|
|
871
|
+
if normalized_question == normalized_pattern:
|
|
872
|
+
bonus = max(bonus, 6.0)
|
|
873
|
+
elif normalized_pattern in normalized_question:
|
|
874
|
+
bonus = max(bonus, 3.0)
|
|
875
|
+
return bonus
|
|
876
|
+
|
|
877
|
+
@staticmethod
|
|
878
|
+
def _question_specific_penalty(chunk: KnowledgeChunk, question: str) -> float:
|
|
879
|
+
normalized_question = _normalize_text(question)
|
|
880
|
+
title_text = _normalize_text(f"{chunk.title} {chunk.text}")
|
|
881
|
+
penalty = 0.0
|
|
882
|
+
if "button" in title_text and "button" not in normalized_question:
|
|
883
|
+
penalty -= 3.5
|
|
884
|
+
if "tab" in title_text and "tab" not in normalized_question:
|
|
885
|
+
penalty -= 1.5
|
|
886
|
+
return penalty
|
|
887
|
+
|
|
888
|
+
@staticmethod
|
|
889
|
+
def _contextual_bonus(chunk: KnowledgeChunk, active_tab: str | None) -> float:
|
|
890
|
+
active_terms = _tokenize(active_tab)
|
|
891
|
+
tab_terms = _tokenize(chunk.tab)
|
|
892
|
+
return 4.0 if active_terms and active_terms <= tab_terms else 0.0
|
|
893
|
+
|
|
894
|
+
@staticmethod
|
|
895
|
+
def _question_tab_bonus(chunk: KnowledgeChunk, question_terms: set[str]) -> float:
|
|
896
|
+
tab_terms = _tokenize(chunk.tab)
|
|
897
|
+
if not tab_terms:
|
|
898
|
+
return 0.0
|
|
899
|
+
overlap = question_terms & tab_terms
|
|
900
|
+
if not overlap:
|
|
901
|
+
return 0.0
|
|
902
|
+
return 5.0 + float(len(overlap) - 1)
|
|
903
|
+
|
|
904
|
+
@staticmethod
|
|
905
|
+
def _kind_bonus(chunk: KnowledgeChunk, question_intent: str) -> float:
|
|
906
|
+
kind_weights = {
|
|
907
|
+
"diagnostic": {"diagnostic": 4.0, "workflow": 2.0, "output": 1.0},
|
|
908
|
+
"tutorial": {"tutorial": 4.0, "concept": 2.0, "workflow": 1.5},
|
|
909
|
+
"results": {"results": 4.0, "output": 2.5, "concept": 1.5},
|
|
910
|
+
"parameter": {"parameter": 4.5, "tutorial": 1.5, "concept": 1.0},
|
|
911
|
+
"module-explanation": {"concept": 4.0, "tutorial": 2.0},
|
|
912
|
+
}
|
|
913
|
+
return kind_weights.get(question_intent, {}).get(chunk.kind, 0.0)
|
|
914
|
+
|
|
915
|
+
@staticmethod
|
|
916
|
+
def _program_bonus(chunk: KnowledgeChunk, question_terms: set[str]) -> float:
|
|
917
|
+
program_terms = _tokenize(chunk.program)
|
|
918
|
+
if program_terms and question_terms & program_terms:
|
|
919
|
+
return 2.0
|
|
920
|
+
return 0.0
|
|
921
|
+
|
|
922
|
+
@staticmethod
|
|
923
|
+
def _source_bonus(chunk: KnowledgeChunk, question_intent: str) -> float:
|
|
924
|
+
if chunk.source.startswith("tutorial:"):
|
|
925
|
+
return 3.0 if question_intent == "tutorial" else -0.25
|
|
926
|
+
if chunk.source == "curated_overrides":
|
|
927
|
+
return 3.0
|
|
928
|
+
if chunk.source in {"robert_docs", "aqme_docs"}:
|
|
929
|
+
return 0.4
|
|
930
|
+
return 0.0
|
|
931
|
+
|
|
932
|
+
@staticmethod
|
|
933
|
+
def _quality_penalty(chunk: KnowledgeChunk) -> float:
|
|
934
|
+
penalty = 0.0
|
|
935
|
+
text = chunk.text or ""
|
|
936
|
+
lowered = text.lower()
|
|
937
|
+
if len(text) > 1800:
|
|
938
|
+
penalty -= 1.5
|
|
939
|
+
if any(marker in lowered for marker in (".. ", "image::", "raw::", "<div", "code::")):
|
|
940
|
+
penalty -= 2.0
|
|
941
|
+
if any(marker in lowered for marker in ("<input", "circleci", "codecov", "downloads", "robert_banner", "aqme_banner", ":local:")):
|
|
942
|
+
penalty -= 5.0
|
|
943
|
+
if len(text.strip()) < 18:
|
|
944
|
+
penalty -= 3.0
|
|
945
|
+
if str(chunk.title or "").strip().lower() in _LOW_SIGNAL_TITLES:
|
|
946
|
+
penalty -= 1.5
|
|
947
|
+
if chunk.source in {"robert_code_docstrings", "aqme_code_docstrings"} and str(chunk.title or "").strip().lower() in {"module", "main"}:
|
|
948
|
+
penalty -= 2.5
|
|
949
|
+
return penalty
|
|
950
|
+
|
|
951
|
+
@classmethod
|
|
952
|
+
def _focus_bonus(cls, chunk: KnowledgeChunk, focus_tags: set[str]) -> float:
|
|
953
|
+
if not focus_tags:
|
|
954
|
+
return 0.0
|
|
955
|
+
|
|
956
|
+
aqme_related = cls._is_aqme_related(chunk)
|
|
957
|
+
robert_related = cls._is_robert_related(chunk)
|
|
958
|
+
ui_related = cls._is_ui_related(chunk)
|
|
959
|
+
bonus = 0.0
|
|
960
|
+
|
|
961
|
+
if "aqme" in focus_tags:
|
|
962
|
+
if aqme_related:
|
|
963
|
+
bonus += 3.5
|
|
964
|
+
elif robert_related and "robert" not in focus_tags:
|
|
965
|
+
bonus -= 2.5
|
|
966
|
+
if "robert" in focus_tags:
|
|
967
|
+
if robert_related:
|
|
968
|
+
bonus += 3.5
|
|
969
|
+
elif aqme_related and "aqme" not in focus_tags:
|
|
970
|
+
bonus -= 2.5
|
|
971
|
+
if "ui" in focus_tags:
|
|
972
|
+
if ui_related:
|
|
973
|
+
bonus += 2.0
|
|
974
|
+
elif focus_tags == {"ui"}:
|
|
975
|
+
bonus -= 0.5
|
|
976
|
+
return bonus
|
|
977
|
+
|
|
978
|
+
def _bm25_score(self, item: IndexedChunk, query_terms: tuple[str, ...]) -> float:
|
|
979
|
+
if not self._document_count:
|
|
980
|
+
return 0.0
|
|
981
|
+
length_ratio = (
|
|
982
|
+
item.body_length / self._average_body_length
|
|
983
|
+
if self._average_body_length > 0.0 else 1.0
|
|
984
|
+
)
|
|
985
|
+
score = 0.0
|
|
986
|
+
for term in set(query_terms):
|
|
987
|
+
frequency = self._document_frequencies.get(term, 0)
|
|
988
|
+
if not frequency:
|
|
989
|
+
continue
|
|
990
|
+
idf = math.log(
|
|
991
|
+
1.0 + (self._document_count - frequency + 0.5) / (frequency + 0.5)
|
|
992
|
+
)
|
|
993
|
+
for field, weight in FIELD_WEIGHTS.items():
|
|
994
|
+
term_frequency = item.field_counters[field].get(term, 0)
|
|
995
|
+
if not term_frequency:
|
|
996
|
+
continue
|
|
997
|
+
normalization = (
|
|
998
|
+
1.0 - BM25_B + BM25_B * length_ratio
|
|
999
|
+
if field == "text" else 1.0
|
|
1000
|
+
)
|
|
1001
|
+
saturation = (
|
|
1002
|
+
term_frequency * (BM25_K1 + 1.0)
|
|
1003
|
+
/ (term_frequency + BM25_K1 * normalization)
|
|
1004
|
+
)
|
|
1005
|
+
score += weight * idf * saturation
|
|
1006
|
+
return score
|
|
1007
|
+
|
|
1008
|
+
@staticmethod
|
|
1009
|
+
def _bounded_metadata_score(
|
|
1010
|
+
item: IndexedChunk,
|
|
1011
|
+
question_terms: tuple[str, ...],
|
|
1012
|
+
active_tab_terms: set[str],
|
|
1013
|
+
workflow_terms: set[str],
|
|
1014
|
+
console_terms: set[str],
|
|
1015
|
+
intent: str,
|
|
1016
|
+
focus_tags: set[str],
|
|
1017
|
+
) -> float:
|
|
1018
|
+
chunk = item.chunk
|
|
1019
|
+
term_set = set(question_terms)
|
|
1020
|
+
tab_terms = set(item.field_counters["tab"])
|
|
1021
|
+
program_terms = set(item.field_counters["program"])
|
|
1022
|
+
module_terms = set(item.field_counters["module"])
|
|
1023
|
+
explicit_tab = bool(tab_terms & term_set)
|
|
1024
|
+
active_tab_match = bool(tab_terms) and tab_terms <= active_tab_terms
|
|
1025
|
+
|
|
1026
|
+
metadata = 0.0
|
|
1027
|
+
if explicit_tab:
|
|
1028
|
+
metadata += 2.0
|
|
1029
|
+
elif active_tab_match:
|
|
1030
|
+
metadata += 1.0
|
|
1031
|
+
|
|
1032
|
+
intent_weights = {
|
|
1033
|
+
"diagnostic": {"diagnostic": 2.0, "workflow": 1.0},
|
|
1034
|
+
"tutorial": {"tutorial": 1.5, "concept": 0.75, "workflow": 0.5},
|
|
1035
|
+
"results": {"results": 2.0, "output": 1.25},
|
|
1036
|
+
"parameter": {"parameter": 2.25, "tutorial": 0.5},
|
|
1037
|
+
"module-explanation": {"concept": 2.0, "tutorial": 0.75},
|
|
1038
|
+
}
|
|
1039
|
+
metadata += intent_weights.get(intent, {}).get(chunk.kind.casefold(), 0.0)
|
|
1040
|
+
|
|
1041
|
+
tier = chunk.source_tier.casefold()
|
|
1042
|
+
ui_workflow_focus = (
|
|
1043
|
+
intent == "tutorial"
|
|
1044
|
+
or chunk.kind.casefold() in {"interface", "tutorial", "workflow"}
|
|
1045
|
+
or bool(term_set & {"button", "tab", "workflow", "full_workflow"})
|
|
1046
|
+
or "ui" in focus_tags
|
|
1047
|
+
)
|
|
1048
|
+
if tier == "curated" and ui_workflow_focus:
|
|
1049
|
+
metadata += 3.0
|
|
1050
|
+
elif tier == "tutorial" and intent == "tutorial":
|
|
1051
|
+
metadata += 1.5
|
|
1052
|
+
elif tier == "reference":
|
|
1053
|
+
metadata += 0.25
|
|
1054
|
+
|
|
1055
|
+
if program_terms & term_set:
|
|
1056
|
+
metadata += 1.0
|
|
1057
|
+
if workflow_terms & (program_terms | module_terms | tab_terms):
|
|
1058
|
+
metadata += 0.75
|
|
1059
|
+
indexed_terms = set().union(
|
|
1060
|
+
*(counter.keys() for counter in item.field_counters.values())
|
|
1061
|
+
)
|
|
1062
|
+
if intent == "diagnostic" and console_terms & indexed_terms:
|
|
1063
|
+
metadata += 0.75
|
|
1064
|
+
title_terms = set(item.field_counters["title"])
|
|
1065
|
+
if term_set and term_set <= title_terms:
|
|
1066
|
+
metadata += 3.0 / (1.0 + len(title_terms - term_set))
|
|
1067
|
+
# K5 records used this source marker before source_tier was introduced.
|
|
1068
|
+
if chunk.source == "curated_overrides":
|
|
1069
|
+
metadata += 2.0
|
|
1070
|
+
elif chunk.source.endswith("_code_docstrings"):
|
|
1071
|
+
metadata -= 3.0
|
|
1072
|
+
if focus_tags:
|
|
1073
|
+
related = set(item.field_counters["program"]) | set(item.field_counters["tab"])
|
|
1074
|
+
for tag in focus_tags:
|
|
1075
|
+
if tag in related and tag not in term_set:
|
|
1076
|
+
metadata += 1.0
|
|
1077
|
+
elif tag in {"aqme", "robert"}:
|
|
1078
|
+
metadata -= 0.75
|
|
1079
|
+
|
|
1080
|
+
metadata = max(-3.0, min(6.0, metadata))
|
|
1081
|
+
priority = chunk.priority
|
|
1082
|
+
if not math.isfinite(priority):
|
|
1083
|
+
return math.nan
|
|
1084
|
+
return metadata + max(0.0, min(0.5, priority))
|
|
1085
|
+
|
|
1086
|
+
def search(
|
|
1087
|
+
self,
|
|
1088
|
+
question: str,
|
|
1089
|
+
active_tab: str | None = None,
|
|
1090
|
+
workflow: str | None = None,
|
|
1091
|
+
console_terms: Iterable[str] | None = None,
|
|
1092
|
+
limit: int = 5,
|
|
1093
|
+
question_intent: str | None = None,
|
|
1094
|
+
focus_tags: Iterable[str] | None = None,
|
|
1095
|
+
) -> list[SearchResult]:
|
|
1096
|
+
if limit <= 0:
|
|
1097
|
+
return []
|
|
1098
|
+
|
|
1099
|
+
question_terms = normalize_terms(question)
|
|
1100
|
+
if not question_terms:
|
|
1101
|
+
return []
|
|
1102
|
+
question_pattern = _canonical_question_pattern(question)
|
|
1103
|
+
person_query = bool(question_pattern and question_pattern[0] == "who")
|
|
1104
|
+
# Workflow/console context must never flood the explicit-question BM25 query.
|
|
1105
|
+
retrieval_terms = question_terms
|
|
1106
|
+
active_tab_terms = set(normalize_terms(active_tab)) if active_tab else set()
|
|
1107
|
+
workflow_terms = set(normalize_terms(workflow)) if workflow else set()
|
|
1108
|
+
console_term_values = tuple(console_terms) if console_terms is not None else ()
|
|
1109
|
+
console_query_terms = (
|
|
1110
|
+
set(normalize_terms(console_term_values))
|
|
1111
|
+
if console_term_values else set()
|
|
1112
|
+
)
|
|
1113
|
+
intent = str(question_intent or classify_question_intent(question)).strip() or "tutorial"
|
|
1114
|
+
focus_tag_set = {str(tag).strip().lower() for tag in (focus_tags or []) if str(tag).strip()}
|
|
1115
|
+
|
|
1116
|
+
scored: list[SearchResult] = []
|
|
1117
|
+
for item in self._index:
|
|
1118
|
+
if person_query and not any(
|
|
1119
|
+
item.field_counters[field].get("who", 0)
|
|
1120
|
+
for field in ("question_patterns", "title", "keywords", "aliases")
|
|
1121
|
+
):
|
|
1122
|
+
continue
|
|
1123
|
+
lexical_score = self._bm25_score(item, retrieval_terms)
|
|
1124
|
+
if lexical_score <= 0.0:
|
|
1125
|
+
continue
|
|
1126
|
+
metadata_score = self._bounded_metadata_score(
|
|
1127
|
+
item,
|
|
1128
|
+
question_terms,
|
|
1129
|
+
active_tab_terms,
|
|
1130
|
+
workflow_terms,
|
|
1131
|
+
console_query_terms,
|
|
1132
|
+
intent,
|
|
1133
|
+
focus_tag_set,
|
|
1134
|
+
)
|
|
1135
|
+
score = lexical_score + metadata_score
|
|
1136
|
+
if not math.isfinite(score) or score < MIN_RELEVANCE_SCORE:
|
|
1137
|
+
continue
|
|
1138
|
+
indexed_terms = {
|
|
1139
|
+
term
|
|
1140
|
+
for counter in item.field_counters.values()
|
|
1141
|
+
for term in counter
|
|
1142
|
+
}
|
|
1143
|
+
matched_terms = tuple(sorted(set(question_terms) & indexed_terms))
|
|
1144
|
+
scored.append(
|
|
1145
|
+
SearchResult(
|
|
1146
|
+
chunk=item.chunk,
|
|
1147
|
+
score=score,
|
|
1148
|
+
matched_terms=matched_terms,
|
|
1149
|
+
query_terms=tuple(sorted(set(question_terms))),
|
|
1150
|
+
)
|
|
1151
|
+
)
|
|
1152
|
+
query_signature = question_pattern
|
|
1153
|
+
|
|
1154
|
+
def ranking_key(result: SearchResult) -> tuple[bool, float, str]:
|
|
1155
|
+
exact_curated_pattern = (
|
|
1156
|
+
result.chunk.source_tier.casefold() == "curated"
|
|
1157
|
+
and any(
|
|
1158
|
+
_canonical_question_pattern(pattern) == query_signature
|
|
1159
|
+
for pattern in result.chunk.question_patterns
|
|
1160
|
+
)
|
|
1161
|
+
)
|
|
1162
|
+
return (not exact_curated_pattern, -result.score, result.chunk.id)
|
|
1163
|
+
|
|
1164
|
+
scored.sort(key=ranking_key)
|
|
1165
|
+
unique: list[SearchResult] = []
|
|
1166
|
+
seen_ids: set[str] = set()
|
|
1167
|
+
seen_content: set[str] = set()
|
|
1168
|
+
fingerprints = {id(item.chunk): item.content_fingerprint for item in self._index}
|
|
1169
|
+
for result in scored:
|
|
1170
|
+
fingerprint = fingerprints[id(result.chunk)]
|
|
1171
|
+
if result.chunk.id in seen_ids or fingerprint in seen_content:
|
|
1172
|
+
continue
|
|
1173
|
+
seen_ids.add(result.chunk.id)
|
|
1174
|
+
seen_content.add(fingerprint)
|
|
1175
|
+
unique.append(result)
|
|
1176
|
+
if len(unique) >= limit:
|
|
1177
|
+
break
|
|
1178
|
+
return unique
|