edsl 0.1.33__py3-none-any.whl → 0.1.33.dev1__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.
- edsl/Base.py +3 -9
- edsl/__init__.py +3 -8
- edsl/__version__.py +1 -1
- edsl/agents/Agent.py +8 -40
- edsl/agents/AgentList.py +0 -43
- edsl/agents/Invigilator.py +219 -135
- edsl/agents/InvigilatorBase.py +59 -148
- edsl/agents/{PromptConstructor.py → PromptConstructionMixin.py} +89 -138
- edsl/agents/__init__.py +0 -1
- edsl/config.py +56 -47
- edsl/coop/coop.py +7 -50
- edsl/data/Cache.py +1 -35
- edsl/data_transfer_models.py +38 -73
- edsl/enums.py +0 -4
- edsl/exceptions/language_models.py +1 -25
- edsl/exceptions/questions.py +5 -62
- edsl/exceptions/results.py +0 -4
- edsl/inference_services/AnthropicService.py +11 -13
- edsl/inference_services/AwsBedrock.py +17 -19
- edsl/inference_services/AzureAI.py +20 -37
- edsl/inference_services/GoogleService.py +12 -16
- edsl/inference_services/GroqService.py +0 -2
- edsl/inference_services/InferenceServiceABC.py +3 -58
- edsl/inference_services/OpenAIService.py +54 -48
- edsl/inference_services/models_available_cache.py +6 -0
- edsl/inference_services/registry.py +0 -6
- edsl/jobs/Answers.py +12 -10
- edsl/jobs/Jobs.py +21 -36
- edsl/jobs/buckets/BucketCollection.py +15 -24
- edsl/jobs/buckets/TokenBucket.py +14 -93
- edsl/jobs/interviews/Interview.py +78 -366
- edsl/jobs/interviews/InterviewExceptionEntry.py +19 -85
- edsl/jobs/interviews/InterviewTaskBuildingMixin.py +286 -0
- edsl/jobs/interviews/{InterviewExceptionCollection.py → interview_exception_tracking.py} +68 -14
- edsl/jobs/interviews/retry_management.py +37 -0
- edsl/jobs/runners/JobsRunnerAsyncio.py +175 -146
- edsl/jobs/runners/JobsRunnerStatusMixin.py +333 -0
- edsl/jobs/tasks/QuestionTaskCreator.py +23 -30
- edsl/jobs/tasks/TaskHistory.py +213 -148
- edsl/language_models/LanguageModel.py +156 -261
- edsl/language_models/ModelList.py +2 -2
- edsl/language_models/RegisterLanguageModelsMeta.py +29 -14
- edsl/language_models/registry.py +6 -23
- edsl/language_models/repair.py +19 -0
- edsl/prompts/Prompt.py +2 -52
- edsl/questions/AnswerValidatorMixin.py +26 -23
- edsl/questions/QuestionBase.py +249 -329
- edsl/questions/QuestionBudget.py +41 -99
- edsl/questions/QuestionCheckBox.py +35 -227
- edsl/questions/QuestionExtract.py +27 -98
- edsl/questions/QuestionFreeText.py +29 -52
- edsl/questions/QuestionFunctional.py +0 -7
- edsl/questions/QuestionList.py +22 -141
- edsl/questions/QuestionMultipleChoice.py +65 -159
- edsl/questions/QuestionNumerical.py +46 -88
- edsl/questions/QuestionRank.py +24 -182
- edsl/questions/RegisterQuestionsMeta.py +12 -31
- edsl/questions/__init__.py +4 -3
- edsl/questions/derived/QuestionLikertFive.py +5 -10
- edsl/questions/derived/QuestionLinearScale.py +2 -15
- edsl/questions/derived/QuestionTopK.py +1 -10
- edsl/questions/derived/QuestionYesNo.py +3 -24
- edsl/questions/descriptors.py +7 -43
- edsl/questions/question_registry.py +2 -6
- edsl/results/Dataset.py +0 -20
- edsl/results/DatasetExportMixin.py +48 -46
- edsl/results/Result.py +5 -32
- edsl/results/Results.py +46 -135
- edsl/results/ResultsDBMixin.py +3 -3
- edsl/scenarios/FileStore.py +10 -71
- edsl/scenarios/Scenario.py +25 -96
- edsl/scenarios/ScenarioImageMixin.py +2 -2
- edsl/scenarios/ScenarioList.py +39 -361
- edsl/scenarios/ScenarioListExportMixin.py +0 -9
- edsl/scenarios/ScenarioListPdfMixin.py +4 -150
- edsl/study/SnapShot.py +1 -8
- edsl/study/Study.py +0 -32
- edsl/surveys/Rule.py +1 -10
- edsl/surveys/RuleCollection.py +5 -21
- edsl/surveys/Survey.py +310 -636
- edsl/surveys/SurveyExportMixin.py +9 -71
- edsl/surveys/SurveyFlowVisualizationMixin.py +1 -2
- edsl/surveys/SurveyQualtricsImport.py +4 -75
- edsl/utilities/gcp_bucket/simple_example.py +9 -0
- edsl/utilities/utilities.py +1 -9
- {edsl-0.1.33.dist-info → edsl-0.1.33.dev1.dist-info}/METADATA +2 -5
- edsl-0.1.33.dev1.dist-info/RECORD +209 -0
- edsl/TemplateLoader.py +0 -24
- edsl/auto/AutoStudy.py +0 -117
- edsl/auto/StageBase.py +0 -230
- edsl/auto/StageGenerateSurvey.py +0 -178
- edsl/auto/StageLabelQuestions.py +0 -125
- edsl/auto/StagePersona.py +0 -61
- edsl/auto/StagePersonaDimensionValueRanges.py +0 -88
- edsl/auto/StagePersonaDimensionValues.py +0 -74
- edsl/auto/StagePersonaDimensions.py +0 -69
- edsl/auto/StageQuestions.py +0 -73
- edsl/auto/SurveyCreatorPipeline.py +0 -21
- edsl/auto/utilities.py +0 -224
- edsl/coop/PriceFetcher.py +0 -58
- edsl/inference_services/MistralAIService.py +0 -120
- edsl/inference_services/TestService.py +0 -80
- edsl/inference_services/TogetherAIService.py +0 -170
- edsl/jobs/FailedQuestion.py +0 -78
- edsl/jobs/runners/JobsRunnerStatus.py +0 -331
- edsl/language_models/fake_openai_call.py +0 -15
- edsl/language_models/fake_openai_service.py +0 -61
- edsl/language_models/utilities.py +0 -61
- edsl/questions/QuestionBaseGenMixin.py +0 -133
- edsl/questions/QuestionBasePromptsMixin.py +0 -266
- edsl/questions/Quick.py +0 -41
- edsl/questions/ResponseValidatorABC.py +0 -170
- edsl/questions/decorators.py +0 -21
- edsl/questions/prompt_templates/question_budget.jinja +0 -13
- edsl/questions/prompt_templates/question_checkbox.jinja +0 -32
- edsl/questions/prompt_templates/question_extract.jinja +0 -11
- edsl/questions/prompt_templates/question_free_text.jinja +0 -3
- edsl/questions/prompt_templates/question_linear_scale.jinja +0 -11
- edsl/questions/prompt_templates/question_list.jinja +0 -17
- edsl/questions/prompt_templates/question_multiple_choice.jinja +0 -33
- edsl/questions/prompt_templates/question_numerical.jinja +0 -37
- edsl/questions/templates/__init__.py +0 -0
- edsl/questions/templates/budget/__init__.py +0 -0
- edsl/questions/templates/budget/answering_instructions.jinja +0 -7
- edsl/questions/templates/budget/question_presentation.jinja +0 -7
- edsl/questions/templates/checkbox/__init__.py +0 -0
- edsl/questions/templates/checkbox/answering_instructions.jinja +0 -10
- edsl/questions/templates/checkbox/question_presentation.jinja +0 -22
- edsl/questions/templates/extract/__init__.py +0 -0
- edsl/questions/templates/extract/answering_instructions.jinja +0 -7
- edsl/questions/templates/extract/question_presentation.jinja +0 -1
- edsl/questions/templates/free_text/__init__.py +0 -0
- edsl/questions/templates/free_text/answering_instructions.jinja +0 -0
- edsl/questions/templates/free_text/question_presentation.jinja +0 -1
- edsl/questions/templates/likert_five/__init__.py +0 -0
- edsl/questions/templates/likert_five/answering_instructions.jinja +0 -10
- edsl/questions/templates/likert_five/question_presentation.jinja +0 -12
- edsl/questions/templates/linear_scale/__init__.py +0 -0
- edsl/questions/templates/linear_scale/answering_instructions.jinja +0 -5
- edsl/questions/templates/linear_scale/question_presentation.jinja +0 -5
- edsl/questions/templates/list/__init__.py +0 -0
- edsl/questions/templates/list/answering_instructions.jinja +0 -4
- edsl/questions/templates/list/question_presentation.jinja +0 -5
- edsl/questions/templates/multiple_choice/__init__.py +0 -0
- edsl/questions/templates/multiple_choice/answering_instructions.jinja +0 -9
- edsl/questions/templates/multiple_choice/html.jinja +0 -0
- edsl/questions/templates/multiple_choice/question_presentation.jinja +0 -12
- edsl/questions/templates/numerical/__init__.py +0 -0
- edsl/questions/templates/numerical/answering_instructions.jinja +0 -8
- edsl/questions/templates/numerical/question_presentation.jinja +0 -7
- edsl/questions/templates/rank/__init__.py +0 -0
- edsl/questions/templates/rank/answering_instructions.jinja +0 -11
- edsl/questions/templates/rank/question_presentation.jinja +0 -15
- edsl/questions/templates/top_k/__init__.py +0 -0
- edsl/questions/templates/top_k/answering_instructions.jinja +0 -8
- edsl/questions/templates/top_k/question_presentation.jinja +0 -22
- edsl/questions/templates/yes_no/__init__.py +0 -0
- edsl/questions/templates/yes_no/answering_instructions.jinja +0 -6
- edsl/questions/templates/yes_no/question_presentation.jinja +0 -12
- edsl/results/DatasetTree.py +0 -145
- edsl/results/Selector.py +0 -118
- edsl/results/tree_explore.py +0 -115
- edsl/surveys/instructions/ChangeInstruction.py +0 -47
- edsl/surveys/instructions/Instruction.py +0 -34
- edsl/surveys/instructions/InstructionCollection.py +0 -77
- edsl/surveys/instructions/__init__.py +0 -0
- edsl/templates/error_reporting/base.html +0 -24
- edsl/templates/error_reporting/exceptions_by_model.html +0 -35
- edsl/templates/error_reporting/exceptions_by_question_name.html +0 -17
- edsl/templates/error_reporting/exceptions_by_type.html +0 -17
- edsl/templates/error_reporting/interview_details.html +0 -116
- edsl/templates/error_reporting/interviews.html +0 -10
- edsl/templates/error_reporting/overview.html +0 -5
- edsl/templates/error_reporting/performance_plot.html +0 -2
- edsl/templates/error_reporting/report.css +0 -74
- edsl/templates/error_reporting/report.html +0 -118
- edsl/templates/error_reporting/report.js +0 -25
- edsl-0.1.33.dist-info/RECORD +0 -295
- {edsl-0.1.33.dist-info → edsl-0.1.33.dev1.dist-info}/LICENSE +0 -0
- {edsl-0.1.33.dist-info → edsl-0.1.33.dev1.dist-info}/WHEEL +0 -0
edsl/results/DatasetTree.py
DELETED
@@ -1,145 +0,0 @@
|
|
1
|
-
from typing import Dict, List, Any, Optional
|
2
|
-
from docx import Document
|
3
|
-
from docx.shared import Inches, Pt
|
4
|
-
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
5
|
-
from docx.enum.style import WD_STYLE_TYPE
|
6
|
-
|
7
|
-
|
8
|
-
class TreeNode:
|
9
|
-
def __init__(self, key=None, value=None):
|
10
|
-
self.key = key
|
11
|
-
self.value = value
|
12
|
-
self.children = {}
|
13
|
-
|
14
|
-
|
15
|
-
class Tree:
|
16
|
-
def __init__(self, data: "Dataset"):
|
17
|
-
d = {}
|
18
|
-
for entry in data:
|
19
|
-
d.update(entry)
|
20
|
-
self.data = d
|
21
|
-
self.root = None
|
22
|
-
|
23
|
-
def unique_values_by_keys(self) -> dict:
|
24
|
-
unique_values = {}
|
25
|
-
for key, values in self.data.items():
|
26
|
-
unique_values[key] = list(set(values))
|
27
|
-
return unique_values
|
28
|
-
|
29
|
-
def construct_tree(self, node_order: Optional[List[str]] = None):
|
30
|
-
# Validate node_order
|
31
|
-
if node_order is None:
|
32
|
-
unique_values = self.unique_values_by_keys()
|
33
|
-
# Sort keys by number of unique values
|
34
|
-
node_order = sorted(
|
35
|
-
unique_values, key=lambda k: len(unique_values[k]), reverse=True
|
36
|
-
)
|
37
|
-
else:
|
38
|
-
if not set(node_order).issubset(set(self.data.keys())):
|
39
|
-
invalid_keys = set(node_order) - set(self.data.keys())
|
40
|
-
raise ValueError(f"Invalid keys in node_order: {invalid_keys}")
|
41
|
-
|
42
|
-
self.root = TreeNode()
|
43
|
-
|
44
|
-
for i in range(len(self.data[node_order[0]])):
|
45
|
-
current = self.root
|
46
|
-
for level in node_order[:-1]:
|
47
|
-
value = self.data[level][i]
|
48
|
-
if value not in current.children:
|
49
|
-
current.children[value] = TreeNode(key=level, value=value)
|
50
|
-
current = current.children[value]
|
51
|
-
|
52
|
-
leaf_key = node_order[-1]
|
53
|
-
leaf_value = self.data[leaf_key][i]
|
54
|
-
if leaf_value not in current.children:
|
55
|
-
current.children[leaf_value] = TreeNode(key=leaf_key, value=leaf_value)
|
56
|
-
|
57
|
-
def print_tree(
|
58
|
-
self, node: Optional[TreeNode] = None, level: int = 0, print_keys: bool = False
|
59
|
-
):
|
60
|
-
if node is None:
|
61
|
-
node = self.root
|
62
|
-
if node is None:
|
63
|
-
print("Tree has not been constructed yet.")
|
64
|
-
return
|
65
|
-
|
66
|
-
if node.value is not None:
|
67
|
-
if print_keys and node.key is not None:
|
68
|
-
print(" " * level + f"{node.key}: {node.value}")
|
69
|
-
else:
|
70
|
-
print(" " * level + str(node.value))
|
71
|
-
for child in node.children.values():
|
72
|
-
self.print_tree(child, level + 1, print_keys)
|
73
|
-
|
74
|
-
def to_docx(self, filename: str):
|
75
|
-
doc = Document()
|
76
|
-
|
77
|
-
# Create styles for headings
|
78
|
-
for i in range(1, 10): # Up to 9 levels of headings
|
79
|
-
style_name = f"Heading {i}"
|
80
|
-
if style_name not in doc.styles:
|
81
|
-
doc.styles.add_style(style_name, WD_STYLE_TYPE.PARAGRAPH)
|
82
|
-
|
83
|
-
# Get or create the 'Body Text' style
|
84
|
-
if "Body Text" not in doc.styles:
|
85
|
-
body_style = doc.styles.add_style("Body Text", WD_STYLE_TYPE.PARAGRAPH)
|
86
|
-
else:
|
87
|
-
body_style = doc.styles["Body Text"]
|
88
|
-
|
89
|
-
body_style.font.size = Pt(11)
|
90
|
-
|
91
|
-
self._add_to_docx(doc, self.root, 0)
|
92
|
-
doc.save(filename)
|
93
|
-
|
94
|
-
def _add_to_docx(self, doc, node: TreeNode, level: int):
|
95
|
-
if node.value is not None:
|
96
|
-
if level == 0:
|
97
|
-
doc.add_heading(str(node.value), level=level + 1)
|
98
|
-
elif node.children: # If the node has children, it's not the last level
|
99
|
-
para = doc.add_paragraph(str(node.value))
|
100
|
-
para.style = f"Heading {level+1}"
|
101
|
-
else: # If the node has no children, it's the last level (body text)
|
102
|
-
para = doc.add_paragraph(str(node.value))
|
103
|
-
para.style = "Body Text"
|
104
|
-
|
105
|
-
# Process child nodes (moved outside the if block)
|
106
|
-
for child in node.children.values():
|
107
|
-
self._add_to_docx(doc, child, level + 1)
|
108
|
-
|
109
|
-
|
110
|
-
# Example usage (commented out)
|
111
|
-
"""
|
112
|
-
from edsl.results.Dataset import Dataset
|
113
|
-
|
114
|
-
data = Dataset(
|
115
|
-
[
|
116
|
-
{"continent": ["North America", "Asia", "Europe", "North America", "Asia"]},
|
117
|
-
{"country": ["US", "China", "France", "Canada", "Japan"]},
|
118
|
-
{"city": ["New York", "Beijing", "Paris", "Toronto", "Tokyo"]},
|
119
|
-
{"population": [8419000, 21540000, 2161000, 2930000, 13960000]},
|
120
|
-
]
|
121
|
-
)
|
122
|
-
|
123
|
-
tree = Tree(data)
|
124
|
-
|
125
|
-
try:
|
126
|
-
tree.construct_tree(["continent", "country", "city", "population"])
|
127
|
-
print("Tree without key names:")
|
128
|
-
tree.print_tree()
|
129
|
-
print("\nTree with key names:")
|
130
|
-
tree.print_tree(print_keys=True)
|
131
|
-
except ValueError as e:
|
132
|
-
print(f"Error: {e}")
|
133
|
-
|
134
|
-
# Demonstrating validation
|
135
|
-
try:
|
136
|
-
tree.construct_tree(["continent", "country", "invalid_key"])
|
137
|
-
except ValueError as e:
|
138
|
-
print(f"\nValidation Error: {e}")
|
139
|
-
|
140
|
-
tree = Tree(data)
|
141
|
-
tree.construct_tree(["continent", "country", "city", "population"])
|
142
|
-
tree.print_tree(print_keys=True)
|
143
|
-
tree.to_docx("tree_structure.docx")
|
144
|
-
print("DocX file 'tree_structure.docx' has been created.")
|
145
|
-
"""
|
edsl/results/Selector.py
DELETED
@@ -1,118 +0,0 @@
|
|
1
|
-
from typing import Union, List, Dict, Any
|
2
|
-
from collections import defaultdict
|
3
|
-
from edsl.results.Dataset import Dataset
|
4
|
-
|
5
|
-
|
6
|
-
class Selector:
|
7
|
-
def __init__(
|
8
|
-
self,
|
9
|
-
known_data_types: List[str],
|
10
|
-
data_type_to_keys: Dict[str, List[str]],
|
11
|
-
key_to_data_type: Dict[str, str],
|
12
|
-
fetch_list_func,
|
13
|
-
columns: List[str],
|
14
|
-
):
|
15
|
-
self.known_data_types = known_data_types
|
16
|
-
self._data_type_to_keys = data_type_to_keys
|
17
|
-
self._key_to_data_type = key_to_data_type
|
18
|
-
self._fetch_list = fetch_list_func
|
19
|
-
self.columns = columns
|
20
|
-
|
21
|
-
def select(self, *columns: Union[str, List[str]]) -> "Dataset":
|
22
|
-
columns = self._normalize_columns(columns)
|
23
|
-
to_fetch = self._get_columns_to_fetch(columns)
|
24
|
-
new_data = self._fetch_data(to_fetch)
|
25
|
-
return Dataset(new_data)
|
26
|
-
|
27
|
-
def _normalize_columns(self, columns: Union[str, List[str]]) -> tuple:
|
28
|
-
if not columns or columns == ("*",) or columns == (None,):
|
29
|
-
return ("*.*",)
|
30
|
-
if isinstance(columns[0], list):
|
31
|
-
return tuple(columns[0])
|
32
|
-
return columns
|
33
|
-
|
34
|
-
def _get_columns_to_fetch(self, columns: tuple) -> Dict[str, List[str]]:
|
35
|
-
to_fetch = defaultdict(list)
|
36
|
-
self.items_in_order = []
|
37
|
-
|
38
|
-
for column in columns:
|
39
|
-
matches = self._find_matching_columns(column)
|
40
|
-
self._validate_matches(column, matches)
|
41
|
-
|
42
|
-
if len(matches) == 1:
|
43
|
-
column = matches[0]
|
44
|
-
|
45
|
-
data_type, key = self._parse_column(column)
|
46
|
-
self._process_column(data_type, key, to_fetch)
|
47
|
-
|
48
|
-
return to_fetch
|
49
|
-
|
50
|
-
def _find_matching_columns(self, partial_name: str) -> list[str]:
|
51
|
-
if "." in partial_name:
|
52
|
-
search_in_list = self.columns
|
53
|
-
else:
|
54
|
-
search_in_list = [s.split(".")[1] for s in self.columns]
|
55
|
-
|
56
|
-
matches = [s for s in search_in_list if s.startswith(partial_name)]
|
57
|
-
return [partial_name] if partial_name in matches else matches
|
58
|
-
|
59
|
-
def _validate_matches(self, column: str, matches: List[str]):
|
60
|
-
if len(matches) > 1:
|
61
|
-
raise ValueError(
|
62
|
-
f"Column '{column}' is ambiguous. Did you mean one of {matches}?"
|
63
|
-
)
|
64
|
-
if len(matches) == 0 and ".*" not in column:
|
65
|
-
raise ValueError(f"Column '{column}' not found in data.")
|
66
|
-
|
67
|
-
def _parse_column(self, column: str) -> tuple[str, str]:
|
68
|
-
if "." in column:
|
69
|
-
return column.split(".")
|
70
|
-
try:
|
71
|
-
return self._key_to_data_type[column], column
|
72
|
-
except KeyError:
|
73
|
-
self._raise_key_error(column)
|
74
|
-
|
75
|
-
def _raise_key_error(self, column: str):
|
76
|
-
import difflib
|
77
|
-
|
78
|
-
close_matches = difflib.get_close_matches(column, self._key_to_data_type.keys())
|
79
|
-
if close_matches:
|
80
|
-
suggestions = ", ".join(close_matches)
|
81
|
-
raise KeyError(
|
82
|
-
f"Column '{column}' not found in data. Did you mean: {suggestions}?"
|
83
|
-
)
|
84
|
-
else:
|
85
|
-
raise KeyError(f"Column {column} not found in data")
|
86
|
-
|
87
|
-
def _process_column(self, data_type: str, key: str, to_fetch: Dict[str, List[str]]):
|
88
|
-
data_types = self._get_data_types_to_return(data_type)
|
89
|
-
found_once = False
|
90
|
-
|
91
|
-
for dt in data_types:
|
92
|
-
relevant_keys = self._data_type_to_keys[dt]
|
93
|
-
for k in relevant_keys:
|
94
|
-
if k == key or key == "*":
|
95
|
-
found_once = True
|
96
|
-
to_fetch[dt].append(k)
|
97
|
-
self.items_in_order.append(f"{dt}.{k}")
|
98
|
-
|
99
|
-
if not found_once:
|
100
|
-
raise ValueError(f"Key {key} not found in data.")
|
101
|
-
|
102
|
-
def _get_data_types_to_return(self, parsed_data_type: str) -> List[str]:
|
103
|
-
if parsed_data_type == "*":
|
104
|
-
return self.known_data_types
|
105
|
-
if parsed_data_type not in self.known_data_types:
|
106
|
-
raise ValueError(
|
107
|
-
f"Data type {parsed_data_type} not found in data. Did you mean one of {self.known_data_types}"
|
108
|
-
)
|
109
|
-
return [parsed_data_type]
|
110
|
-
|
111
|
-
def _fetch_data(self, to_fetch: Dict[str, List[str]]) -> List[Dict[str, Any]]:
|
112
|
-
new_data = []
|
113
|
-
for data_type, keys in to_fetch.items():
|
114
|
-
for key in keys:
|
115
|
-
entries = self._fetch_list(data_type, key)
|
116
|
-
new_data.append({f"{data_type}.{key}": entries})
|
117
|
-
|
118
|
-
return [d for key in self.items_in_order for d in new_data if key in d]
|
edsl/results/tree_explore.py
DELETED
@@ -1,115 +0,0 @@
|
|
1
|
-
from collections import defaultdict
|
2
|
-
from typing import List, Dict, Any
|
3
|
-
import json
|
4
|
-
|
5
|
-
|
6
|
-
class FoldableHTMLTableGenerator:
|
7
|
-
def __init__(self, data: List[Dict[str, Any]]):
|
8
|
-
self.data = data
|
9
|
-
|
10
|
-
def tree(self, fold_attributes: List[str], drop: List[str] = None) -> Dict:
|
11
|
-
def nested_dict():
|
12
|
-
return defaultdict(nested_dict)
|
13
|
-
|
14
|
-
result = nested_dict()
|
15
|
-
drop = drop or [] # Use an empty list if drop is None
|
16
|
-
|
17
|
-
for item in self.data:
|
18
|
-
current = result
|
19
|
-
for attr in fold_attributes:
|
20
|
-
current = current[item[attr]]
|
21
|
-
|
22
|
-
row = {
|
23
|
-
k: v
|
24
|
-
for k, v in item.items()
|
25
|
-
if k not in fold_attributes and k not in drop
|
26
|
-
}
|
27
|
-
if "_rows" not in current:
|
28
|
-
current["_rows"] = []
|
29
|
-
current["_rows"].append(row)
|
30
|
-
|
31
|
-
return result
|
32
|
-
|
33
|
-
def generate_html(self, tree, fold_attributes: List[str]) -> str:
|
34
|
-
html_content = """
|
35
|
-
<!DOCTYPE html>
|
36
|
-
<html lang="en">
|
37
|
-
<head>
|
38
|
-
<meta charset="UTF-8">
|
39
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
40
|
-
<title>Foldable Nested Table</title>
|
41
|
-
<style>
|
42
|
-
.folding-section { margin-left: 20px; }
|
43
|
-
.fold-button { cursor: pointer; margin: 5px 0; }
|
44
|
-
table { border-collapse: collapse; margin-top: 10px; }
|
45
|
-
th, td { border: 1px solid black; padding: 5px; }
|
46
|
-
.attribute-label { font-weight: bold; }
|
47
|
-
</style>
|
48
|
-
</head>
|
49
|
-
<body>
|
50
|
-
<div id="root"></div>
|
51
|
-
<script>
|
52
|
-
function toggleFold(id) {
|
53
|
-
const element = document.getElementById(id);
|
54
|
-
element.style.display = element.style.display === 'none' ? 'block' : 'none';
|
55
|
-
}
|
56
|
-
|
57
|
-
function createFoldableSection(data, path = [], attributes = %s) {
|
58
|
-
const container = document.createElement('div');
|
59
|
-
container.className = 'folding-section';
|
60
|
-
|
61
|
-
for (const [key, value] of Object.entries(data)) {
|
62
|
-
if (key === '_rows') {
|
63
|
-
const table = document.createElement('table');
|
64
|
-
const headerRow = table.insertRow();
|
65
|
-
const headers = Object.keys(value[0]);
|
66
|
-
headers.forEach(header => {
|
67
|
-
const th = document.createElement('th');
|
68
|
-
th.textContent = header;
|
69
|
-
headerRow.appendChild(th);
|
70
|
-
});
|
71
|
-
value.forEach(row => {
|
72
|
-
const tableRow = table.insertRow();
|
73
|
-
headers.forEach(header => {
|
74
|
-
const cell = tableRow.insertCell();
|
75
|
-
cell.textContent = row[header];
|
76
|
-
});
|
77
|
-
});
|
78
|
-
container.appendChild(table);
|
79
|
-
} else {
|
80
|
-
const button = document.createElement('button');
|
81
|
-
const attributeType = attributes[path.length];
|
82
|
-
button.innerHTML = `<span class="attribute-label">${attributeType}:</span> ${key}`;
|
83
|
-
button.className = 'fold-button';
|
84
|
-
const sectionId = `section-${path.join('-')}-${key}`;
|
85
|
-
button.onclick = () => toggleFold(sectionId);
|
86
|
-
container.appendChild(button);
|
87
|
-
|
88
|
-
const section = document.createElement('div');
|
89
|
-
section.id = sectionId;
|
90
|
-
section.style.display = 'none';
|
91
|
-
section.appendChild(createFoldableSection(value, [...path, key], attributes));
|
92
|
-
container.appendChild(section);
|
93
|
-
}
|
94
|
-
}
|
95
|
-
|
96
|
-
return container;
|
97
|
-
}
|
98
|
-
|
99
|
-
const treeData = %s;
|
100
|
-
document.getElementById('root').appendChild(createFoldableSection(treeData));
|
101
|
-
</script>
|
102
|
-
</body>
|
103
|
-
</html>
|
104
|
-
"""
|
105
|
-
|
106
|
-
return html_content % (json.dumps(fold_attributes), json.dumps(tree))
|
107
|
-
|
108
|
-
def save_html(self, fold_attributes: List[str], filename: str = "output.html"):
|
109
|
-
tree = self.tree(fold_attributes)
|
110
|
-
html_content = self.generate_html(tree, fold_attributes)
|
111
|
-
|
112
|
-
with open(filename, "w", encoding="utf-8") as f:
|
113
|
-
f.write(html_content)
|
114
|
-
|
115
|
-
print(f"HTML file has been generated: {filename}")
|
@@ -1,47 +0,0 @@
|
|
1
|
-
from typing import List, Optional
|
2
|
-
|
3
|
-
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
|
4
|
-
|
5
|
-
|
6
|
-
class ChangeInstruction:
|
7
|
-
def __init__(
|
8
|
-
self,
|
9
|
-
keep: Optional[List[str]] = None,
|
10
|
-
drop: Optional[List[str]] = None,
|
11
|
-
):
|
12
|
-
if keep is None and drop is None:
|
13
|
-
raise ValueError("Keep and drop cannot both be None")
|
14
|
-
|
15
|
-
self.keep = keep or []
|
16
|
-
self.drop = drop or []
|
17
|
-
|
18
|
-
def include_instruction(self, instruction_name) -> bool:
|
19
|
-
return (instruction_name in self.keep) or (not instruction_name in self.drop)
|
20
|
-
|
21
|
-
def add_name(self, index) -> None:
|
22
|
-
self.name = "change_instruction_{}".format(index)
|
23
|
-
|
24
|
-
def __str__(self):
|
25
|
-
return self.text
|
26
|
-
|
27
|
-
def _to_dict(self):
|
28
|
-
return {
|
29
|
-
"keep": self.keep,
|
30
|
-
"drop": self.drop,
|
31
|
-
"edsl_class_name": "ChangeInstruction",
|
32
|
-
}
|
33
|
-
|
34
|
-
@add_edsl_version
|
35
|
-
def to_dict(self):
|
36
|
-
return self._to_dict()
|
37
|
-
|
38
|
-
def __hash__(self) -> int:
|
39
|
-
"""Return a hash of the question."""
|
40
|
-
from edsl.utilities.utilities import dict_hash
|
41
|
-
|
42
|
-
return dict_hash(self._to_dict())
|
43
|
-
|
44
|
-
@classmethod
|
45
|
-
@remove_edsl_version
|
46
|
-
def from_dict(cls, data):
|
47
|
-
return cls(data["keep"], data["drop"])
|
@@ -1,34 +0,0 @@
|
|
1
|
-
from typing import Union, Optional, List, Generator, Dict
|
2
|
-
from edsl.questions import QuestionBase
|
3
|
-
|
4
|
-
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
|
5
|
-
|
6
|
-
|
7
|
-
class Instruction:
|
8
|
-
def __init__(self, name, text):
|
9
|
-
self.name = name
|
10
|
-
self.text = text
|
11
|
-
|
12
|
-
def __str__(self):
|
13
|
-
return self.text
|
14
|
-
|
15
|
-
def __repr__(self):
|
16
|
-
return """Instruction(name="{}", text="{}")""".format(self.name, self.text)
|
17
|
-
|
18
|
-
def _to_dict(self):
|
19
|
-
return {"name": self.name, "text": self.text, "edsl_class_name": "Instruction"}
|
20
|
-
|
21
|
-
@add_edsl_version
|
22
|
-
def to_dict(self):
|
23
|
-
return self._to_dict()
|
24
|
-
|
25
|
-
def __hash__(self) -> int:
|
26
|
-
"""Return a hash of the question."""
|
27
|
-
from edsl.utilities.utilities import dict_hash
|
28
|
-
|
29
|
-
return dict_hash(self._to_dict())
|
30
|
-
|
31
|
-
@classmethod
|
32
|
-
@remove_edsl_version
|
33
|
-
def from_dict(cls, data):
|
34
|
-
return cls(data["name"], data["text"])
|
@@ -1,77 +0,0 @@
|
|
1
|
-
from edsl.surveys.instructions.Instruction import Instruction
|
2
|
-
from edsl.surveys.instructions.ChangeInstruction import ChangeInstruction
|
3
|
-
from edsl.questions import QuestionBase
|
4
|
-
from typing import Union, Optional, List, Generator, Dict
|
5
|
-
|
6
|
-
|
7
|
-
from collections import UserDict
|
8
|
-
|
9
|
-
|
10
|
-
class InstructionCollection(UserDict):
|
11
|
-
def __init__(
|
12
|
-
self,
|
13
|
-
instruction_names_to_instruction: Dict[str, Instruction],
|
14
|
-
questions: List[QuestionBase],
|
15
|
-
):
|
16
|
-
self.instruction_names_to_instruction = instruction_names_to_instruction
|
17
|
-
self.questions = questions
|
18
|
-
data = {}
|
19
|
-
for question in self.questions:
|
20
|
-
# just add both the question and the question name
|
21
|
-
data[question.name] = list(self.relevant_instructions(question))
|
22
|
-
# data[question] = list(self.relevant_instructions(question))
|
23
|
-
super().__init__(data)
|
24
|
-
|
25
|
-
def __getitem__(self, key):
|
26
|
-
# in case the person uses question instead of the name
|
27
|
-
if isinstance(key, QuestionBase):
|
28
|
-
key = key.name
|
29
|
-
return self.data[key]
|
30
|
-
|
31
|
-
@property
|
32
|
-
def question_names(self):
|
33
|
-
return [q.name for q in self.questions]
|
34
|
-
|
35
|
-
def question_index(self, question_name):
|
36
|
-
return self.question_names.index(question_name)
|
37
|
-
|
38
|
-
def _entries_before(
|
39
|
-
self, question_name
|
40
|
-
) -> tuple[List[Instruction], List[ChangeInstruction]]:
|
41
|
-
if question_name not in self.question_names:
|
42
|
-
raise ValueError(
|
43
|
-
f"Question name not found in the list of questions: got '{question_name}'; list is {self.question_names}"
|
44
|
-
)
|
45
|
-
instructions, changes = [], []
|
46
|
-
|
47
|
-
index = self.question_index(question_name)
|
48
|
-
for instruction in self.instruction_names_to_instruction.values():
|
49
|
-
if instruction.pseudo_index < index:
|
50
|
-
if isinstance(instruction, Instruction):
|
51
|
-
instructions.append(instruction)
|
52
|
-
elif isinstance(instruction, ChangeInstruction):
|
53
|
-
changes.append(instruction)
|
54
|
-
return instructions, changes
|
55
|
-
|
56
|
-
def relevant_instructions(
|
57
|
-
self, question: Union[str, QuestionBase]
|
58
|
-
) -> Generator[Instruction, None, None]:
|
59
|
-
## Find all the questions that are after a given instruction
|
60
|
-
if isinstance(question, str):
|
61
|
-
question_name = question
|
62
|
-
elif isinstance(question, QuestionBase):
|
63
|
-
question_name = question.name
|
64
|
-
|
65
|
-
instructions_before, changes_before = self._entries_before(question_name)
|
66
|
-
keep_list = []
|
67
|
-
drop_list = []
|
68
|
-
for change in changes_before:
|
69
|
-
keep_list.extend(change.keep)
|
70
|
-
drop_list.extend(change.drop)
|
71
|
-
|
72
|
-
for instruction in instructions_before:
|
73
|
-
if instruction.name in keep_list or instruction.name not in drop_list:
|
74
|
-
yield instruction
|
75
|
-
|
76
|
-
def __len__(self):
|
77
|
-
return len(self.instruction_names_to_instruction)
|
File without changes
|
@@ -1,24 +0,0 @@
|
|
1
|
-
<!DOCTYPE html>
|
2
|
-
<html lang="en">
|
3
|
-
<head>
|
4
|
-
<meta charset="UTF-8">
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
6
|
-
<title>Exception Details</title>
|
7
|
-
<style>
|
8
|
-
{{ css }}
|
9
|
-
</style>
|
10
|
-
|
11
|
-
<script>
|
12
|
-
{{ javascript }}
|
13
|
-
</script>
|
14
|
-
|
15
|
-
</head>
|
16
|
-
<body>
|
17
|
-
{% include 'overview.html' %}
|
18
|
-
{% include 'exceptions_by_type.html' %}
|
19
|
-
{% include 'exceptions_by_model.html' %}
|
20
|
-
{% include 'exceptions_by_question_name.html' %}
|
21
|
-
{% include 'interviews.html' %}
|
22
|
-
{% include 'performance_plot.html' %}
|
23
|
-
</body>
|
24
|
-
</html>
|
@@ -1,35 +0,0 @@
|
|
1
|
-
<h2>Exceptions by Model</h2>
|
2
|
-
<table border="1">
|
3
|
-
<thead>
|
4
|
-
<tr>
|
5
|
-
<th>Model</th>
|
6
|
-
<th>Number</th>
|
7
|
-
</tr>
|
8
|
-
</thead>
|
9
|
-
<tbody>
|
10
|
-
{% for model, exceptions in exceptions_by_model.items() %}
|
11
|
-
<tr>
|
12
|
-
<td>{{ model }}</td>
|
13
|
-
<td>{{ exceptions }}</td>
|
14
|
-
</tr>
|
15
|
-
{% endfor %}
|
16
|
-
</tbody>
|
17
|
-
</table>
|
18
|
-
|
19
|
-
<h2>Exceptions by Service</h2>
|
20
|
-
<table border="1">
|
21
|
-
<thead>
|
22
|
-
<tr>
|
23
|
-
<th>Service</th>
|
24
|
-
<th>Number</th>
|
25
|
-
</tr>
|
26
|
-
</thead>
|
27
|
-
<tbody>
|
28
|
-
{% for service, exceptions in exceptions_by_service.items() %}
|
29
|
-
<tr>
|
30
|
-
<td>{{ service }}</td>
|
31
|
-
<td>{{ exceptions }}</td>
|
32
|
-
</tr>
|
33
|
-
{% endfor %}
|
34
|
-
</tbody>
|
35
|
-
</table>
|
@@ -1,17 +0,0 @@
|
|
1
|
-
<h2>Exceptions by Question Name</h2>
|
2
|
-
<table border="1">
|
3
|
-
<thead>
|
4
|
-
<tr>
|
5
|
-
<th>Question Name</th>
|
6
|
-
<th>Number of Exceptions</th>
|
7
|
-
</tr>
|
8
|
-
</thead>
|
9
|
-
<tbody>
|
10
|
-
{% for question_name, exception_count in exceptions_by_question_name.items() %}
|
11
|
-
<tr>
|
12
|
-
<td>{{ question_name }}</td>
|
13
|
-
<td>{{ exception_count }}</td>
|
14
|
-
</tr>
|
15
|
-
{% endfor %}
|
16
|
-
</tbody>
|
17
|
-
</table>
|
@@ -1,17 +0,0 @@
|
|
1
|
-
<h2>Exceptions by Type</h2>
|
2
|
-
<table border="1">
|
3
|
-
<thead>
|
4
|
-
<tr>
|
5
|
-
<th>Exception Type</th>
|
6
|
-
<th>Number</th>
|
7
|
-
</tr>
|
8
|
-
</thead>
|
9
|
-
<tbody>
|
10
|
-
{% for exception_type, exceptions in exceptions_by_type.items() %}
|
11
|
-
<tr>
|
12
|
-
<td>{{ exception_type }}</td>
|
13
|
-
<td>{{ exceptions }}</td>
|
14
|
-
</tr>
|
15
|
-
{% endfor %}
|
16
|
-
</tbody>
|
17
|
-
</table>
|