edsl 0.1.49__py3-none-any.whl → 0.1.51__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. edsl/__init__.py +124 -53
  2. edsl/__version__.py +1 -1
  3. edsl/agents/agent.py +21 -21
  4. edsl/agents/agent_list.py +2 -5
  5. edsl/agents/exceptions.py +119 -5
  6. edsl/base/__init__.py +10 -35
  7. edsl/base/base_class.py +71 -36
  8. edsl/base/base_exception.py +204 -0
  9. edsl/base/data_transfer_models.py +1 -1
  10. edsl/base/exceptions.py +94 -0
  11. edsl/buckets/__init__.py +15 -1
  12. edsl/buckets/bucket_collection.py +3 -4
  13. edsl/buckets/exceptions.py +107 -0
  14. edsl/buckets/model_buckets.py +1 -2
  15. edsl/buckets/token_bucket.py +11 -6
  16. edsl/buckets/token_bucket_api.py +27 -12
  17. edsl/buckets/token_bucket_client.py +9 -7
  18. edsl/caching/cache.py +12 -4
  19. edsl/caching/cache_entry.py +10 -9
  20. edsl/caching/exceptions.py +113 -7
  21. edsl/caching/remote_cache_sync.py +6 -7
  22. edsl/caching/sql_dict.py +20 -14
  23. edsl/cli.py +43 -0
  24. edsl/config/__init__.py +1 -1
  25. edsl/config/config_class.py +32 -6
  26. edsl/conversation/Conversation.py +8 -4
  27. edsl/conversation/car_buying.py +1 -3
  28. edsl/conversation/exceptions.py +58 -0
  29. edsl/conversation/mug_negotiation.py +2 -8
  30. edsl/coop/__init__.py +28 -6
  31. edsl/coop/coop.py +120 -29
  32. edsl/coop/coop_functions.py +1 -1
  33. edsl/coop/ep_key_handling.py +1 -1
  34. edsl/coop/exceptions.py +188 -9
  35. edsl/coop/price_fetcher.py +5 -8
  36. edsl/coop/utils.py +4 -6
  37. edsl/dataset/__init__.py +5 -4
  38. edsl/dataset/dataset.py +177 -86
  39. edsl/dataset/dataset_operations_mixin.py +98 -76
  40. edsl/dataset/dataset_tree.py +11 -7
  41. edsl/dataset/display/table_display.py +0 -2
  42. edsl/dataset/display/table_renderers.py +6 -4
  43. edsl/dataset/exceptions.py +125 -0
  44. edsl/dataset/file_exports.py +18 -11
  45. edsl/dataset/r/ggplot.py +13 -6
  46. edsl/display/__init__.py +27 -0
  47. edsl/display/core.py +147 -0
  48. edsl/display/plugin.py +189 -0
  49. edsl/display/utils.py +52 -0
  50. edsl/inference_services/__init__.py +9 -1
  51. edsl/inference_services/available_model_cache_handler.py +1 -1
  52. edsl/inference_services/available_model_fetcher.py +5 -6
  53. edsl/inference_services/data_structures.py +10 -7
  54. edsl/inference_services/exceptions.py +132 -1
  55. edsl/inference_services/inference_service_abc.py +2 -2
  56. edsl/inference_services/inference_services_collection.py +2 -6
  57. edsl/inference_services/registry.py +4 -3
  58. edsl/inference_services/service_availability.py +4 -3
  59. edsl/inference_services/services/anthropic_service.py +4 -1
  60. edsl/inference_services/services/aws_bedrock.py +13 -12
  61. edsl/inference_services/services/azure_ai.py +12 -10
  62. edsl/inference_services/services/deep_infra_service.py +1 -4
  63. edsl/inference_services/services/deep_seek_service.py +1 -5
  64. edsl/inference_services/services/google_service.py +7 -3
  65. edsl/inference_services/services/groq_service.py +1 -1
  66. edsl/inference_services/services/mistral_ai_service.py +4 -2
  67. edsl/inference_services/services/ollama_service.py +1 -1
  68. edsl/inference_services/services/open_ai_service.py +7 -5
  69. edsl/inference_services/services/perplexity_service.py +6 -2
  70. edsl/inference_services/services/test_service.py +8 -7
  71. edsl/inference_services/services/together_ai_service.py +2 -3
  72. edsl/inference_services/services/xai_service.py +1 -1
  73. edsl/instructions/__init__.py +1 -1
  74. edsl/instructions/change_instruction.py +7 -5
  75. edsl/instructions/exceptions.py +61 -0
  76. edsl/instructions/instruction.py +6 -2
  77. edsl/instructions/instruction_collection.py +6 -4
  78. edsl/instructions/instruction_handler.py +12 -15
  79. edsl/interviews/ReportErrors.py +0 -3
  80. edsl/interviews/__init__.py +9 -2
  81. edsl/interviews/answering_function.py +11 -13
  82. edsl/interviews/exception_tracking.py +15 -8
  83. edsl/interviews/exceptions.py +79 -0
  84. edsl/interviews/interview.py +33 -30
  85. edsl/interviews/interview_status_dictionary.py +4 -2
  86. edsl/interviews/interview_status_log.py +2 -1
  87. edsl/interviews/interview_task_manager.py +5 -5
  88. edsl/interviews/request_token_estimator.py +5 -2
  89. edsl/interviews/statistics.py +3 -4
  90. edsl/invigilators/__init__.py +7 -1
  91. edsl/invigilators/exceptions.py +79 -0
  92. edsl/invigilators/invigilator_base.py +0 -1
  93. edsl/invigilators/invigilators.py +9 -13
  94. edsl/invigilators/prompt_constructor.py +1 -5
  95. edsl/invigilators/prompt_helpers.py +8 -4
  96. edsl/invigilators/question_instructions_prompt_builder.py +1 -1
  97. edsl/invigilators/question_option_processor.py +9 -5
  98. edsl/invigilators/question_template_replacements_builder.py +3 -2
  99. edsl/jobs/__init__.py +42 -5
  100. edsl/jobs/async_interview_runner.py +25 -23
  101. edsl/jobs/check_survey_scenario_compatibility.py +11 -10
  102. edsl/jobs/data_structures.py +8 -5
  103. edsl/jobs/exceptions.py +177 -8
  104. edsl/jobs/fetch_invigilator.py +1 -1
  105. edsl/jobs/jobs.py +74 -69
  106. edsl/jobs/jobs_checks.py +6 -7
  107. edsl/jobs/jobs_component_constructor.py +4 -4
  108. edsl/jobs/jobs_pricing_estimation.py +4 -3
  109. edsl/jobs/jobs_remote_inference_logger.py +5 -4
  110. edsl/jobs/jobs_runner_asyncio.py +3 -4
  111. edsl/jobs/jobs_runner_status.py +8 -9
  112. edsl/jobs/remote_inference.py +27 -24
  113. edsl/jobs/results_exceptions_handler.py +10 -7
  114. edsl/key_management/__init__.py +3 -1
  115. edsl/key_management/exceptions.py +62 -0
  116. edsl/key_management/key_lookup.py +1 -1
  117. edsl/key_management/key_lookup_builder.py +37 -14
  118. edsl/key_management/key_lookup_collection.py +2 -0
  119. edsl/language_models/__init__.py +1 -1
  120. edsl/language_models/exceptions.py +302 -14
  121. edsl/language_models/language_model.py +9 -8
  122. edsl/language_models/model.py +4 -4
  123. edsl/language_models/model_list.py +1 -1
  124. edsl/language_models/price_manager.py +1 -1
  125. edsl/language_models/raw_response_handler.py +14 -9
  126. edsl/language_models/registry.py +17 -21
  127. edsl/language_models/repair.py +0 -6
  128. edsl/language_models/unused/fake_openai_service.py +0 -1
  129. edsl/load_plugins.py +69 -0
  130. edsl/logger.py +146 -0
  131. edsl/notebooks/__init__.py +24 -1
  132. edsl/notebooks/exceptions.py +82 -0
  133. edsl/notebooks/notebook.py +7 -3
  134. edsl/notebooks/notebook_to_latex.py +1 -2
  135. edsl/plugins/__init__.py +63 -0
  136. edsl/plugins/built_in/export_example.py +50 -0
  137. edsl/plugins/built_in/pig_latin.py +67 -0
  138. edsl/plugins/cli.py +372 -0
  139. edsl/plugins/cli_typer.py +283 -0
  140. edsl/plugins/exceptions.py +31 -0
  141. edsl/plugins/hookspec.py +51 -0
  142. edsl/plugins/plugin_host.py +128 -0
  143. edsl/plugins/plugin_manager.py +633 -0
  144. edsl/plugins/plugins_registry.py +168 -0
  145. edsl/prompts/__init__.py +24 -1
  146. edsl/prompts/exceptions.py +107 -5
  147. edsl/prompts/prompt.py +15 -7
  148. edsl/questions/HTMLQuestion.py +5 -11
  149. edsl/questions/Quick.py +0 -1
  150. edsl/questions/__init__.py +6 -4
  151. edsl/questions/answer_validator_mixin.py +318 -323
  152. edsl/questions/compose_questions.py +3 -3
  153. edsl/questions/descriptors.py +11 -50
  154. edsl/questions/exceptions.py +278 -22
  155. edsl/questions/loop_processor.py +7 -5
  156. edsl/questions/prompt_templates/question_list.jinja +3 -0
  157. edsl/questions/question_base.py +46 -19
  158. edsl/questions/question_base_gen_mixin.py +2 -2
  159. edsl/questions/question_base_prompts_mixin.py +13 -7
  160. edsl/questions/question_budget.py +503 -98
  161. edsl/questions/question_check_box.py +660 -160
  162. edsl/questions/question_dict.py +345 -194
  163. edsl/questions/question_extract.py +401 -61
  164. edsl/questions/question_free_text.py +80 -14
  165. edsl/questions/question_functional.py +119 -9
  166. edsl/questions/{derived/question_likert_five.py → question_likert_five.py} +2 -2
  167. edsl/questions/{derived/question_linear_scale.py → question_linear_scale.py} +3 -4
  168. edsl/questions/question_list.py +275 -28
  169. edsl/questions/question_matrix.py +643 -96
  170. edsl/questions/question_multiple_choice.py +219 -51
  171. edsl/questions/question_numerical.py +361 -32
  172. edsl/questions/question_rank.py +401 -124
  173. edsl/questions/question_registry.py +7 -5
  174. edsl/questions/{derived/question_top_k.py → question_top_k.py} +3 -3
  175. edsl/questions/{derived/question_yes_no.py → question_yes_no.py} +3 -4
  176. edsl/questions/register_questions_meta.py +2 -2
  177. edsl/questions/response_validator_abc.py +13 -15
  178. edsl/questions/response_validator_factory.py +10 -12
  179. edsl/questions/templates/dict/answering_instructions.jinja +1 -0
  180. edsl/questions/templates/rank/question_presentation.jinja +1 -1
  181. edsl/results/__init__.py +1 -1
  182. edsl/results/exceptions.py +141 -7
  183. edsl/results/report.py +1 -2
  184. edsl/results/result.py +11 -9
  185. edsl/results/results.py +480 -321
  186. edsl/results/results_selector.py +8 -4
  187. edsl/scenarios/PdfExtractor.py +2 -2
  188. edsl/scenarios/construct_download_link.py +69 -35
  189. edsl/scenarios/directory_scanner.py +33 -14
  190. edsl/scenarios/document_chunker.py +1 -1
  191. edsl/scenarios/exceptions.py +238 -14
  192. edsl/scenarios/file_methods.py +1 -1
  193. edsl/scenarios/file_store.py +7 -3
  194. edsl/scenarios/handlers/__init__.py +17 -0
  195. edsl/scenarios/handlers/docx_file_store.py +0 -5
  196. edsl/scenarios/handlers/pdf_file_store.py +0 -1
  197. edsl/scenarios/handlers/pptx_file_store.py +0 -5
  198. edsl/scenarios/handlers/py_file_store.py +0 -1
  199. edsl/scenarios/handlers/sql_file_store.py +1 -4
  200. edsl/scenarios/handlers/sqlite_file_store.py +0 -1
  201. edsl/scenarios/handlers/txt_file_store.py +1 -1
  202. edsl/scenarios/scenario.py +1 -3
  203. edsl/scenarios/scenario_list.py +179 -27
  204. edsl/scenarios/scenario_list_pdf_tools.py +1 -0
  205. edsl/scenarios/scenario_selector.py +0 -1
  206. edsl/surveys/__init__.py +3 -4
  207. edsl/surveys/dag/__init__.py +4 -2
  208. edsl/surveys/descriptors.py +1 -1
  209. edsl/surveys/edit_survey.py +1 -0
  210. edsl/surveys/exceptions.py +165 -9
  211. edsl/surveys/memory/__init__.py +5 -3
  212. edsl/surveys/memory/memory_management.py +1 -0
  213. edsl/surveys/memory/memory_plan.py +6 -15
  214. edsl/surveys/rules/__init__.py +5 -3
  215. edsl/surveys/rules/rule.py +1 -2
  216. edsl/surveys/rules/rule_collection.py +1 -1
  217. edsl/surveys/survey.py +12 -24
  218. edsl/surveys/survey_css.py +3 -3
  219. edsl/surveys/survey_export.py +6 -3
  220. edsl/surveys/survey_flow_visualization.py +10 -1
  221. edsl/surveys/survey_simulator.py +2 -1
  222. edsl/tasks/__init__.py +23 -1
  223. edsl/tasks/exceptions.py +72 -0
  224. edsl/tasks/question_task_creator.py +3 -3
  225. edsl/tasks/task_creators.py +1 -3
  226. edsl/tasks/task_history.py +8 -10
  227. edsl/tasks/task_status_log.py +1 -2
  228. edsl/tokens/__init__.py +29 -1
  229. edsl/tokens/exceptions.py +37 -0
  230. edsl/tokens/interview_token_usage.py +3 -2
  231. edsl/tokens/token_usage.py +4 -3
  232. edsl/utilities/__init__.py +21 -1
  233. edsl/utilities/decorators.py +1 -2
  234. edsl/utilities/markdown_to_docx.py +2 -2
  235. edsl/utilities/markdown_to_pdf.py +1 -1
  236. edsl/utilities/repair_functions.py +0 -1
  237. edsl/utilities/restricted_python.py +0 -1
  238. edsl/utilities/template_loader.py +2 -3
  239. edsl/utilities/utilities.py +8 -29
  240. {edsl-0.1.49.dist-info → edsl-0.1.51.dist-info}/METADATA +32 -2
  241. edsl-0.1.51.dist-info/RECORD +365 -0
  242. edsl-0.1.51.dist-info/entry_points.txt +3 -0
  243. edsl/dataset/smart_objects.py +0 -96
  244. edsl/exceptions/BaseException.py +0 -21
  245. edsl/exceptions/__init__.py +0 -54
  246. edsl/exceptions/configuration.py +0 -16
  247. edsl/exceptions/general.py +0 -34
  248. edsl/questions/derived/__init__.py +0 -0
  249. edsl/study/ObjectEntry.py +0 -173
  250. edsl/study/ProofOfWork.py +0 -113
  251. edsl/study/SnapShot.py +0 -80
  252. edsl/study/Study.py +0 -520
  253. edsl/study/__init__.py +0 -6
  254. edsl/utilities/interface.py +0 -135
  255. edsl-0.1.49.dist-info/RECORD +0 -347
  256. {edsl-0.1.49.dist-info → edsl-0.1.51.dist-info}/LICENSE +0 -0
  257. {edsl-0.1.49.dist-info → edsl-0.1.51.dist-info}/WHEEL +0 -0
@@ -1,10 +1,5 @@
1
1
  """Mixin with validators for LLM answers to questions."""
2
2
 
3
- import re
4
- from typing import Any, Type, Union
5
- from .exceptions import (
6
- QuestionAnswerValidationError,
7
- )
8
3
 
9
4
 
10
5
  class AnswerValidatorMixin:
@@ -34,324 +29,324 @@ class AnswerValidatorMixin:
34
29
  #####################
35
30
  # TEMPLATE VALIDATION
36
31
  #####################
37
- def _validate_answer_template_basic(self, answer: Any) -> None:
38
- """Check that the answer (i) is a dictionary (ii) has an 'answer' key.
39
-
40
- - E.g., both {'answer': 1} and {'answer': {'a': 1}, 'other_key'=[1,2,3]} are valid
41
- """
42
- if not isinstance(answer, dict):
43
- raise QuestionAnswerValidationError(
44
- f"Answer must be a dictionary (got {answer})."
45
- )
46
- if not "answer" in answer:
47
- raise QuestionAnswerValidationError(
48
- f"Answer must have an 'answer' key (got {answer})."
49
- )
50
-
51
- #####################
52
- # VALUE VALIDATION
53
- #####################
54
- def _validate_answer_key_value(
55
- self, answer: dict[str, Any], key: str, of_type: Type
56
- ) -> None:
57
- """Check that the value of a key is of the specified type."""
58
- if not isinstance(answer.get(key), of_type):
59
- raise QuestionAnswerValidationError(
60
- f"""Answer key '{key}' must be of type {of_type.__name__};
61
- (got {answer.get(key)}) which is of type {type(answer.get(key))}."""
62
- )
63
-
64
- def _validate_answer_key_value_numeric(
65
- self, answer: dict[str, Any], key: str
66
- ) -> None:
67
- """Check that the value is numeric (int or float).
68
- Can also deal with strings that contain commas and other characters.
69
-
70
- """
71
- value = answer.get(key)
72
- initial_value = value
73
- if type(value) == str:
74
- value = value.replace(",", "")
75
- value = "".join(re.findall(r"[-+]?\d*\.\d+|\d+", value))
76
- if value.isdigit():
77
- value = int(value)
78
- else:
79
- try:
80
- float(value)
81
- value = float(value)
82
- except ValueError:
83
- raise QuestionAnswerValidationError(
84
- f"Answer should be numerical (int or float). Got '{initial_value}'"
85
- )
86
- return None
87
- elif type(value) == int or type(value) == float:
88
- return None
89
- else:
90
- raise QuestionAnswerValidationError(
91
- f"Answer should be numerical (int or float)."
92
- )
93
-
94
- #####################
95
- # QUESTION SPECIFIC VALIDATION
96
- #####################
97
- def _validate_answer_budget(self, answer: dict[str, Any]) -> None:
98
- """Validate QuestionBudget-specific answer.
99
-
100
- Check that answer["answer"]:
101
- - has keys that are in the range of the number of options
102
- - has values that are non-negative integers
103
- - has values that sum to `budget_sum`
104
- - contains all keys in the range of the number of options
105
- """
106
- answer = answer.get("answer")
107
- budget_sum = self.budget_sum
108
- acceptable_answer_keys = set(range(len(self.question_options)))
109
- answer_keys = set([int(k) for k in answer.keys()])
110
- current_sum = sum(answer.values())
111
- if not current_sum == budget_sum:
112
- raise QuestionAnswerValidationError(
113
- f"Budget sum must be {budget_sum}, but got {current_sum}."
114
- )
115
- if any(v < 0 for v in answer.values()):
116
- raise QuestionAnswerValidationError(
117
- f"Budget values must be positive, but got {answer_keys}."
118
- )
119
- if any([int(key) not in acceptable_answer_keys for key in answer.keys()]):
120
- raise QuestionAnswerValidationError(
121
- f"Budget keys must be in {acceptable_answer_keys}, but got {answer_keys}."
122
- )
123
- if acceptable_answer_keys != answer_keys:
124
- missing_keys = acceptable_answer_keys - answer_keys
125
- raise QuestionAnswerValidationError(
126
- f"All but keys must be represented in the answer. Missing: {missing_keys}."
127
- )
128
-
129
- def _validate_answer_checkbox(self, answer: dict[str, Union[str, int]]) -> None:
130
- """Validate QuestionCheckbox-specific answer.
131
-
132
- :param answer: Answer to validate
133
-
134
-
135
- Check that answer["answer"]:
136
- - has elements that are strings, bytes-like objects or real numbers evaluating to integers
137
- - has elements that are in the range of the number of options
138
- - has at least `min_selections` elements, if provided
139
- - has at most `max_selections` elements, if provided
140
- """
141
- answer_codes = answer["answer"]
142
- try:
143
- answer_codes = [int(k) for k in answer["answer"]]
144
- except:
145
- raise QuestionAnswerValidationError(
146
- f"Answer codes must be a list of strings, bytes-like objects or real numbers (got {answer['answer']})."
147
- )
148
- acceptable_values = list(range(len(self.question_options)))
149
- for answer_code in answer_codes:
150
- if answer_code not in acceptable_values:
151
- raise QuestionAnswerValidationError(
152
- f"Answer code {answer_code} has elements not in {acceptable_values}."
153
- )
154
- if self.min_selections is not None and len(answer_codes) < self.min_selections:
155
- raise QuestionAnswerValidationError(
156
- f"Answer codes, {answer_codes}, has fewer than {self.min_selections} options selected."
157
- )
158
- if self.max_selections is not None and len(answer_codes) > self.max_selections:
159
- raise QuestionAnswerValidationError(
160
- f"Answer codes, {answer_codes}, has more than {self.max_selections} options selected."
161
- )
162
-
163
- def _validate_answer_extract(self, answer: dict[str, Any]) -> None:
164
- """Validate QuestionExtract-specific answer.
165
-
166
- Check that answer["answer"]:
167
- - does not have keys that are not in the answer template
168
- - has all keys that are in the answer template
169
- """
170
- value = answer.get("answer")
171
- acceptable_answer_keys = set(self.answer_template.keys())
172
- if any([key not in acceptable_answer_keys for key in value.keys()]):
173
- raise QuestionAnswerValidationError(
174
- f"Answer keys must be in {acceptable_answer_keys}, but got {value.keys()}."
175
- )
176
- if any([key not in value.keys() for key in acceptable_answer_keys]):
177
- raise QuestionAnswerValidationError(
178
- f"Answer must have all keys in {acceptable_answer_keys}, but got {value.keys()}."
179
- )
180
-
181
- def _validate_answer_list(self, answer: dict[str, Union[list, str]]) -> None:
182
- """Validate QuestionList-specific answer.
183
-
184
- Check that answer["answer"]:
185
- - is not empty, if `allow_nonresponse` is False
186
- - has no more than `max_list_items` elements
187
- - has no empty strings
188
- """
189
- value = answer.get("answer")
190
- if (
191
- hasattr(self, "allow_nonresponse")
192
- and self.allow_nonresponse == False
193
- and (value == [] or value is None)
194
- ):
195
- raise QuestionAnswerValidationError("You must provide a response.")
196
-
197
- if (
198
- hasattr(self, "max_list_items")
199
- and self.max_list_items is not None
200
- and (len(value) > self.max_list_items)
201
- ):
202
- raise QuestionAnswerValidationError("Response has too many items.")
203
-
204
- if any([item == "" for item in value]):
205
- raise QuestionAnswerValidationError(
206
- f"Answer cannot contain empty strings, but got {value}."
207
- )
208
-
209
- def _validate_answer_numerical(self, answer: dict) -> None:
210
- """Validate QuestionNumerical-specific answer.
211
-
212
- Check that answer["answer"]:
213
- - is not less than `min_value`
214
- - is not greater than `max_value`
215
- """
216
- try:
217
- value = float(answer.get("answer"))
218
- except ValueError:
219
- raise QuestionAnswerValidationError(
220
- f"Answer must real number or convertible to a real number (got {answer.get('answer')})."
221
- )
222
- if self.min_value is not None and value < self.min_value:
223
- raise QuestionAnswerValidationError(
224
- f"Value {value} is less than {self.min_value}"
225
- )
226
- if self.max_value is not None and value > self.max_value:
227
- raise QuestionAnswerValidationError(
228
- f"Value {value} is greater than {self.max_value}"
229
- )
230
- return value
231
-
232
- def _validate_answer_multiple_choice(
233
- self, answer: dict[str, Union[str, int]]
234
- ) -> None:
235
- """Validate QuestionMultipleChoice-specific answer.
236
-
237
- Check that answer["answer"]:
238
- - is a string, bytes-like object or real number
239
- - is a non-negative integer
240
- - is in the range of the number of options
241
- """
242
- try:
243
- value = int(answer.get("answer"))
244
- except:
245
- raise QuestionAnswerValidationError(
246
- f"Answer code must be a string, a bytes-like object or a real number (got {answer.get('answer')})."
247
- )
248
- if not value >= 0:
249
- raise QuestionAnswerValidationError(
250
- f"Answer code must be a non-negative integer (got {value})."
251
- )
252
- if int(value) not in range(len(self.question_options)):
253
- raise QuestionAnswerValidationError(
254
- f"Answer code {value} must be in {list(range(len(self.question_options)))}."
255
- )
256
-
257
- def _validate_answer_rank(self, answer: dict[str, Union[str, int]]) -> None:
258
- """Validate QuestionRank-specific answer.
259
-
260
- Check that answer["answer"]:
261
- - contains only integers
262
- - contains only integers in the range of the number of options
263
- - has the correct number of elements
264
- """
265
- value = answer.get("answer")
266
- acceptable_values = list(range(len(self.question_options)))
267
- for v in value:
268
- try:
269
- answer_code = int(v)
270
- except ValueError:
271
- raise QuestionAnswerValidationError(
272
- f"Rank answer {value} has elements that are not integers, namely {v}."
273
- )
274
- except TypeError:
275
- raise QuestionAnswerValidationError(
276
- f"Rank answer {value} has elements that are not integers, namely {v}."
277
- )
278
- if answer_code not in acceptable_values:
279
- raise QuestionAnswerValidationError(
280
- f"Answer {value} has elements not in {acceptable_values}, namely {v}."
281
- )
282
- if len(value) != self.num_selections:
283
- raise QuestionAnswerValidationError(
284
- f"Rank answer {value}, but exactly {self.num_selections} selections required."
285
- )
286
-
287
- def _validate_answer_matrix(self, answer: dict[str, Any]) -> None:
288
- """Validate QuestionMatrix-specific answer.
289
-
290
- Check that answer["answer"]:
291
- - is a dictionary
292
- - has all required question_items as keys
293
- - has values that are valid options from question_options
294
- - has the correct number of responses (one per item)
295
- """
296
- value = answer.get("answer")
297
-
298
- # Check that answer is a dictionary
299
- if not isinstance(value, dict):
300
- raise QuestionAnswerValidationError(
301
- f"Matrix answer must be a dictionary mapping items to responses (got {value})"
302
- )
303
-
304
- # Check that all required items are present
305
- required_items = set(self.question_items)
306
- provided_items = set(value.keys())
307
-
308
- if missing_items := (required_items - provided_items):
309
- raise QuestionAnswerValidationError(
310
- f"Missing responses for items: {missing_items}"
311
- )
312
-
313
- if extra_items := (provided_items - required_items):
314
- raise QuestionAnswerValidationError(
315
- f"Unexpected responses for items: {extra_items}"
316
- )
317
-
318
- # Check that all responses are valid options
319
- valid_options = set(self.question_options)
320
- for item, response in value.items():
321
- if response not in valid_options:
322
- raise QuestionAnswerValidationError(
323
- f"Invalid response '{response}' for item '{item}'. "
324
- f"Must be one of: {valid_options}"
325
- )
326
-
327
- def _validate_answer_dict(self, answer: dict[str, Any]) -> None:
328
- """Validate QuestionDict-specific answer.
329
-
330
- Check that answer["answer"]:
331
- - is a dictionary
332
- - has all required answer_keys as keys
333
- """
334
- value = answer.get("answer")
335
-
336
- # Check that answer is a dictionary
337
- if not isinstance(value, dict):
338
- raise QuestionAnswerValidationError(
339
- f"Dict answer must be a dictionary mapping values to specified keys (got {value})"
340
- )
341
-
342
- # Check that all required answer keys are present
343
- required_keys = set(self.answer_keys)
344
- provided_keys = set(value.keys())
345
-
346
- if missing_keys := (required_keys - provided_keys):
347
- raise QuestionAnswerValidationError(
348
- f"Missing required keys: {missing_keys}"
349
- )
350
-
351
- if extra_keys := (provided_keys - required_keys):
352
- raise QuestionAnswerValidationError(
353
- f"Unexpected keys: {extra_keys}"
354
- )
32
+ # def _validate_answer_template_basic(self, answer: Any) -> None:
33
+ # """Check that the answer (i) is a dictionary (ii) has an 'answer' key.
34
+
35
+ # - E.g., both {'answer': 1} and {'answer': {'a': 1}, 'other_key'=[1,2,3]} are valid
36
+ # """
37
+ # if not isinstance(answer, dict):
38
+ # raise QuestionAnswerValidationError(
39
+ # f"Answer must be a dictionary (got {answer})."
40
+ # )
41
+ # if "answer" not in answer:
42
+ # raise QuestionAnswerValidationError(
43
+ # f"Answer must have an 'answer' key (got {answer})."
44
+ # )
45
+
46
+ # #####################
47
+ # # VALUE VALIDATION
48
+ # #####################
49
+ # def _validate_answer_key_value(
50
+ # self, answer: dict[str, Any], key: str, of_type: Type
51
+ # ) -> None:
52
+ # """Check that the value of a key is of the specified type."""
53
+ # if not isinstance(answer.get(key), of_type):
54
+ # raise QuestionAnswerValidationError(
55
+ # f"""Answer key '{key}' must be of type {of_type.__name__};
56
+ # (got {answer.get(key)}) which is of type {type(answer.get(key))}."""
57
+ # )
58
+
59
+ # def _validate_answer_key_value_numeric(
60
+ # self, answer: dict[str, Any], key: str
61
+ # ) -> None:
62
+ # """Check that the value is numeric (int or float).
63
+ # Can also deal with strings that contain commas and other characters.
64
+
65
+ # """
66
+ # value = answer.get(key)
67
+ # initial_value = value
68
+ # if isinstance(value, str):
69
+ # value = value.replace(",", "")
70
+ # value = "".join(re.findall(r"[-+]?\d*\.\d+|\d+", value))
71
+ # if value.isdigit():
72
+ # value = int(value)
73
+ # else:
74
+ # try:
75
+ # float(value)
76
+ # value = float(value)
77
+ # except ValueError:
78
+ # raise QuestionAnswerValidationError(
79
+ # f"Answer should be numerical (int or float). Got '{initial_value}'"
80
+ # )
81
+ # return None
82
+ # elif isinstance(value, (int, float)):
83
+ # return None
84
+ # else:
85
+ # raise QuestionAnswerValidationError(
86
+ # "Answer should be numerical (int or float)."
87
+ # )
88
+
89
+ # #####################
90
+ # # QUESTION SPECIFIC VALIDATION
91
+ # #####################
92
+ # def _validate_answer_budget(self, answer: dict[str, Any]) -> None:
93
+ # """Validate QuestionBudget-specific answer.
94
+
95
+ # Check that answer["answer"]:
96
+ # - has keys that are in the range of the number of options
97
+ # - has values that are non-negative integers
98
+ # - has values that sum to `budget_sum`
99
+ # - contains all keys in the range of the number of options
100
+ # """
101
+ # answer = answer.get("answer")
102
+ # budget_sum = self.budget_sum
103
+ # acceptable_answer_keys = set(range(len(self.question_options)))
104
+ # answer_keys = set([int(k) for k in answer.keys()])
105
+ # current_sum = sum(answer.values())
106
+ # if not current_sum == budget_sum:
107
+ # raise QuestionAnswerValidationError(
108
+ # f"Budget sum must be {budget_sum}, but got {current_sum}."
109
+ # )
110
+ # if any(v < 0 for v in answer.values()):
111
+ # raise QuestionAnswerValidationError(
112
+ # f"Budget values must be positive, but got {answer_keys}."
113
+ # )
114
+ # if any([int(key) not in acceptable_answer_keys for key in answer.keys()]):
115
+ # raise QuestionAnswerValidationError(
116
+ # f"Budget keys must be in {acceptable_answer_keys}, but got {answer_keys}."
117
+ # )
118
+ # if acceptable_answer_keys != answer_keys:
119
+ # missing_keys = acceptable_answer_keys - answer_keys
120
+ # raise QuestionAnswerValidationError(
121
+ # f"All but keys must be represented in the answer. Missing: {missing_keys}."
122
+ # )
123
+
124
+ # def _validate_answer_checkbox(self, answer: dict[str, Union[str, int]]) -> None:
125
+ # """Validate QuestionCheckbox-specific answer.
126
+
127
+ # :param answer: Answer to validate
128
+
129
+
130
+ # Check that answer["answer"]:
131
+ # - has elements that are strings, bytes-like objects or real numbers evaluating to integers
132
+ # - has elements that are in the range of the number of options
133
+ # - has at least `min_selections` elements, if provided
134
+ # - has at most `max_selections` elements, if provided
135
+ # """
136
+ # answer_codes = answer["answer"]
137
+ # try:
138
+ # answer_codes = [int(k) for k in answer["answer"]]
139
+ # except (ValueError, TypeError):
140
+ # raise QuestionAnswerValidationError(
141
+ # f"Answer codes must be a list of strings, bytes-like objects or real numbers (got {answer['answer']})."
142
+ # )
143
+ # acceptable_values = list(range(len(self.question_options)))
144
+ # for answer_code in answer_codes:
145
+ # if answer_code not in acceptable_values:
146
+ # raise QuestionAnswerValidationError(
147
+ # f"Answer code {answer_code} has elements not in {acceptable_values}."
148
+ # )
149
+ # if self.min_selections is not None and len(answer_codes) < self.min_selections:
150
+ # raise QuestionAnswerValidationError(
151
+ # f"Answer codes, {answer_codes}, has fewer than {self.min_selections} options selected."
152
+ # )
153
+ # if self.max_selections is not None and len(answer_codes) > self.max_selections:
154
+ # raise QuestionAnswerValidationError(
155
+ # f"Answer codes, {answer_codes}, has more than {self.max_selections} options selected."
156
+ # )
157
+
158
+ # def _validate_answer_extract(self, answer: dict[str, Any]) -> None:
159
+ # """Validate QuestionExtract-specific answer.
160
+
161
+ # Check that answer["answer"]:
162
+ # - does not have keys that are not in the answer template
163
+ # - has all keys that are in the answer template
164
+ # """
165
+ # value = answer.get("answer")
166
+ # acceptable_answer_keys = set(self.answer_template.keys())
167
+ # if any([key not in acceptable_answer_keys for key in value.keys()]):
168
+ # raise QuestionAnswerValidationError(
169
+ # f"Answer keys must be in {acceptable_answer_keys}, but got {value.keys()}."
170
+ # )
171
+ # if any([key not in value.keys() for key in acceptable_answer_keys]):
172
+ # raise QuestionAnswerValidationError(
173
+ # f"Answer must have all keys in {acceptable_answer_keys}, but got {value.keys()}."
174
+ # )
175
+
176
+ # def _validate_answer_list(self, answer: dict[str, Union[list, str]]) -> None:
177
+ # """Validate QuestionList-specific answer.
178
+
179
+ # Check that answer["answer"]:
180
+ # - is not empty, if `allow_nonresponse` is False
181
+ # - has no more than `max_list_items` elements
182
+ # - has no empty strings
183
+ # """
184
+ # value = answer.get("answer")
185
+ # if (
186
+ # hasattr(self, "allow_nonresponse")
187
+ # and not self.allow_nonresponse
188
+ # and (value == [] or value is None)
189
+ # ):
190
+ # raise QuestionAnswerValidationError("You must provide a response.")
191
+
192
+ # if (
193
+ # hasattr(self, "max_list_items")
194
+ # and self.max_list_items is not None
195
+ # and (len(value) > self.max_list_items)
196
+ # ):
197
+ # raise QuestionAnswerValidationError("Response has too many items.")
198
+
199
+ # if any([item == "" for item in value]):
200
+ # raise QuestionAnswerValidationError(
201
+ # f"Answer cannot contain empty strings, but got {value}."
202
+ # )
203
+
204
+ # def _validate_answer_numerical(self, answer: dict) -> None:
205
+ # """Validate QuestionNumerical-specific answer.
206
+
207
+ # Check that answer["answer"]:
208
+ # - is not less than `min_value`
209
+ # - is not greater than `max_value`
210
+ # """
211
+ # try:
212
+ # value = float(answer.get("answer"))
213
+ # except ValueError:
214
+ # raise QuestionAnswerValidationError(
215
+ # f"Answer must real number or convertible to a real number (got {answer.get('answer')})."
216
+ # )
217
+ # if self.min_value is not None and value < self.min_value:
218
+ # raise QuestionAnswerValidationError(
219
+ # f"Value {value} is less than {self.min_value}"
220
+ # )
221
+ # if self.max_value is not None and value > self.max_value:
222
+ # raise QuestionAnswerValidationError(
223
+ # f"Value {value} is greater than {self.max_value}"
224
+ # )
225
+ # return value
226
+
227
+ # def _validate_answer_multiple_choice(
228
+ # self, answer: dict[str, Union[str, int]]
229
+ # ) -> None:
230
+ # """Validate QuestionMultipleChoice-specific answer.
231
+
232
+ # Check that answer["answer"]:
233
+ # - is a string, bytes-like object or real number
234
+ # - is a non-negative integer
235
+ # - is in the range of the number of options
236
+ # """
237
+ # try:
238
+ # value = int(answer.get("answer"))
239
+ # except (ValueError, TypeError):
240
+ # raise QuestionAnswerValidationError(
241
+ # f"Answer code must be a string, a bytes-like object or a real number (got {answer.get('answer')})."
242
+ # )
243
+ # if not value >= 0:
244
+ # raise QuestionAnswerValidationError(
245
+ # f"Answer code must be a non-negative integer (got {value})."
246
+ # )
247
+ # if int(value) not in range(len(self.question_options)):
248
+ # raise QuestionAnswerValidationError(
249
+ # f"Answer code {value} must be in {list(range(len(self.question_options)))}."
250
+ # )
251
+
252
+ # def _validate_answer_rank(self, answer: dict[str, Union[str, int]]) -> None:
253
+ # """Validate QuestionRank-specific answer.
254
+
255
+ # Check that answer["answer"]:
256
+ # - contains only integers
257
+ # - contains only integers in the range of the number of options
258
+ # - has the correct number of elements
259
+ # """
260
+ # value = answer.get("answer")
261
+ # acceptable_values = list(range(len(self.question_options)))
262
+ # for v in value:
263
+ # try:
264
+ # answer_code = int(v)
265
+ # except ValueError:
266
+ # raise QuestionAnswerValidationError(
267
+ # f"Rank answer {value} has elements that are not integers, namely {v}."
268
+ # )
269
+ # except TypeError:
270
+ # raise QuestionAnswerValidationError(
271
+ # f"Rank answer {value} has elements that are not integers, namely {v}."
272
+ # )
273
+ # if answer_code not in acceptable_values:
274
+ # raise QuestionAnswerValidationError(
275
+ # f"Answer {value} has elements not in {acceptable_values}, namely {v}."
276
+ # )
277
+ # if len(value) != self.num_selections:
278
+ # raise QuestionAnswerValidationError(
279
+ # f"Rank answer {value}, but exactly {self.num_selections} selections required."
280
+ # )
281
+
282
+ # def _validate_answer_matrix(self, answer: dict[str, Any]) -> None:
283
+ # """Validate QuestionMatrix-specific answer.
284
+
285
+ # Check that answer["answer"]:
286
+ # - is a dictionary
287
+ # - has all required question_items as keys
288
+ # - has values that are valid options from question_options
289
+ # - has the correct number of responses (one per item)
290
+ # """
291
+ # value = answer.get("answer")
292
+
293
+ # # Check that answer is a dictionary
294
+ # if not isinstance(value, dict):
295
+ # raise QuestionAnswerValidationError(
296
+ # f"Matrix answer must be a dictionary mapping items to responses (got {value})"
297
+ # )
298
+
299
+ # # Check that all required items are present
300
+ # required_items = set(self.question_items)
301
+ # provided_items = set(value.keys())
302
+
303
+ # if missing_items := (required_items - provided_items):
304
+ # raise QuestionAnswerValidationError(
305
+ # f"Missing responses for items: {missing_items}"
306
+ # )
307
+
308
+ # if extra_items := (provided_items - required_items):
309
+ # raise QuestionAnswerValidationError(
310
+ # f"Unexpected responses for items: {extra_items}"
311
+ # )
312
+
313
+ # # Check that all responses are valid options
314
+ # valid_options = set(self.question_options)
315
+ # for item, response in value.items():
316
+ # if response not in valid_options:
317
+ # raise QuestionAnswerValidationError(
318
+ # f"Invalid response '{response}' for item '{item}'. "
319
+ # f"Must be one of: {valid_options}"
320
+ # )
321
+
322
+ # def _validate_answer_dict(self, answer: dict[str, Any]) -> None:
323
+ # """Validate QuestionDict-specific answer.
324
+
325
+ # Check that answer["answer"]:
326
+ # - is a dictionary
327
+ # - has all required answer_keys as keys
328
+ # """
329
+ # value = answer.get("answer")
330
+
331
+ # # Check that answer is a dictionary
332
+ # if not isinstance(value, dict):
333
+ # raise QuestionAnswerValidationError(
334
+ # f"Dict answer must be a dictionary mapping values to specified keys (got {value})"
335
+ # )
336
+
337
+ # # Check that all required answer keys are present
338
+ # required_keys = set(self.answer_keys)
339
+ # provided_keys = set(value.keys())
340
+
341
+ # if missing_keys := (required_keys - provided_keys):
342
+ # raise QuestionAnswerValidationError(
343
+ # f"Missing required keys: {missing_keys}"
344
+ # )
345
+
346
+ # if extra_keys := (provided_keys - required_keys):
347
+ # raise QuestionAnswerValidationError(
348
+ # f"Unexpected keys: {extra_keys}"
349
+ # )
355
350
 
356
351
 
357
352
  if __name__ == "__main__":