evalscope 0.8.2__py3-none-any.whl → 0.10.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. evalscope/__init__.py +2 -0
  2. evalscope/arguments.py +11 -3
  3. evalscope/backend/rag_eval/clip_benchmark/tasks/zeroshot_classification.py +0 -1
  4. evalscope/backend/rag_eval/utils/llm.py +1 -1
  5. evalscope/benchmarks/__init__.py +20 -1
  6. evalscope/benchmarks/arc/__init__.py +0 -5
  7. evalscope/benchmarks/arc/arc_adapter.py +24 -102
  8. evalscope/benchmarks/bbh/__init__.py +0 -4
  9. evalscope/benchmarks/bbh/bbh_adapter.py +20 -90
  10. evalscope/benchmarks/benchmark.py +70 -59
  11. evalscope/benchmarks/ceval/__init__.py +0 -5
  12. evalscope/benchmarks/ceval/ceval_adapter.py +24 -125
  13. evalscope/benchmarks/cmmlu/__init__.py +0 -5
  14. evalscope/benchmarks/cmmlu/cmmlu_adapter.py +22 -117
  15. evalscope/benchmarks/competition_math/__init__.py +0 -5
  16. evalscope/benchmarks/competition_math/competition_math_adapter.py +29 -371
  17. evalscope/benchmarks/data_adapter.py +115 -87
  18. evalscope/benchmarks/general_qa/__init__.py +0 -5
  19. evalscope/benchmarks/general_qa/general_qa_adapter.py +23 -79
  20. evalscope/benchmarks/gsm8k/__init__.py +0 -4
  21. evalscope/benchmarks/gsm8k/gsm8k_adapter.py +21 -101
  22. evalscope/benchmarks/hellaswag/__init__.py +0 -5
  23. evalscope/benchmarks/hellaswag/hellaswag_adapter.py +32 -99
  24. evalscope/benchmarks/humaneval/__init__.py +0 -4
  25. evalscope/benchmarks/humaneval/humaneval_adapter.py +18 -120
  26. evalscope/benchmarks/ifeval/__init__.py +0 -0
  27. evalscope/benchmarks/ifeval/ifeval_adapter.py +57 -0
  28. evalscope/benchmarks/ifeval/instructions.py +1478 -0
  29. evalscope/benchmarks/ifeval/instructions_registry.py +188 -0
  30. evalscope/benchmarks/ifeval/instructions_util.py +1670 -0
  31. evalscope/benchmarks/ifeval/utils.py +134 -0
  32. evalscope/benchmarks/iquiz/__init__.py +0 -0
  33. evalscope/benchmarks/iquiz/iquiz_adapter.py +63 -0
  34. evalscope/benchmarks/mmlu/__init__.py +0 -5
  35. evalscope/benchmarks/mmlu/mmlu_adapter.py +32 -130
  36. evalscope/benchmarks/mmlu_pro/__init__.py +0 -0
  37. evalscope/benchmarks/mmlu_pro/mmlu_pro_adapter.py +110 -0
  38. evalscope/benchmarks/race/__init__.py +0 -5
  39. evalscope/benchmarks/race/race_adapter.py +26 -123
  40. evalscope/benchmarks/trivia_qa/__init__.py +0 -5
  41. evalscope/benchmarks/trivia_qa/trivia_qa_adapter.py +23 -99
  42. evalscope/benchmarks/truthful_qa/__init__.py +0 -5
  43. evalscope/benchmarks/truthful_qa/truthful_qa_adapter.py +29 -88
  44. evalscope/cli/cli.py +2 -0
  45. evalscope/cli/start_app.py +29 -0
  46. evalscope/collections/__init__.py +3 -0
  47. evalscope/collections/evaluator.py +198 -0
  48. evalscope/collections/sampler.py +138 -0
  49. evalscope/collections/schema.py +126 -0
  50. evalscope/config.py +7 -5
  51. evalscope/constants.py +9 -26
  52. evalscope/evaluator/evaluator.py +87 -121
  53. evalscope/evaluator/reviewer/auto_reviewer.py +12 -4
  54. evalscope/metrics/__init__.py +3 -0
  55. evalscope/metrics/bundled_rouge_score/rouge_scorer.py +1 -1
  56. evalscope/metrics/math_accuracy.py +193 -50
  57. evalscope/metrics/metrics.py +18 -6
  58. evalscope/metrics/named_metrics.py +17 -0
  59. evalscope/metrics/rouge_metric.py +13 -8
  60. evalscope/models/__init__.py +14 -1
  61. evalscope/models/base_adapter.py +52 -0
  62. evalscope/models/chat_adapter.py +138 -0
  63. evalscope/models/choice_adapter.py +211 -0
  64. evalscope/models/custom_adapter.py +67 -0
  65. evalscope/models/local_model.py +74 -0
  66. evalscope/models/model.py +141 -0
  67. evalscope/models/server_adapter.py +111 -0
  68. evalscope/perf/__init__.py +1 -0
  69. evalscope/perf/main.py +0 -1
  70. evalscope/perf/plugin/api/custom_api.py +1 -1
  71. evalscope/perf/plugin/api/openai_api.py +1 -1
  72. evalscope/perf/plugin/datasets/flickr8k.py +1 -1
  73. evalscope/perf/plugin/datasets/longalpaca.py +1 -1
  74. evalscope/report/__init__.py +5 -0
  75. evalscope/report/app.py +506 -0
  76. evalscope/report/combinator.py +73 -0
  77. evalscope/report/generator.py +80 -0
  78. evalscope/report/utils.py +133 -0
  79. evalscope/run.py +48 -72
  80. evalscope/run_arena.py +1 -1
  81. evalscope/summarizer.py +1 -1
  82. evalscope/utils/__init__.py +1 -1
  83. evalscope/utils/chat_service.py +5 -4
  84. evalscope/utils/io_utils.py +8 -0
  85. evalscope/utils/logger.py +5 -0
  86. evalscope/utils/model_utils.py +15 -2
  87. evalscope/utils/utils.py +3 -25
  88. evalscope/version.py +2 -2
  89. {evalscope-0.8.2.dist-info → evalscope-0.10.0.dist-info}/METADATA +115 -21
  90. {evalscope-0.8.2.dist-info → evalscope-0.10.0.dist-info}/RECORD +99 -78
  91. tests/cli/test_collection.py +57 -0
  92. tests/cli/test_run.py +52 -1
  93. tests/rag/test_mteb.py +3 -2
  94. evalscope/models/api/__init__.py +0 -3
  95. evalscope/models/dummy_chat_model.py +0 -49
  96. evalscope/models/model_adapter.py +0 -525
  97. evalscope/models/openai_model.py +0 -103
  98. evalscope/tools/__init__.py +0 -1
  99. evalscope/tools/combine_reports.py +0 -133
  100. evalscope/tools/gen_mmlu_subject_mapping.py +0 -90
  101. /evalscope/{tools/rewrite_eval_results.py → models/custom/dummy_model.py} +0 -0
  102. /evalscope/{models/api → third_party/longbench_write/tools}/openai_api.py +0 -0
  103. {evalscope-0.8.2.dist-info → evalscope-0.10.0.dist-info}/LICENSE +0 -0
  104. {evalscope-0.8.2.dist-info → evalscope-0.10.0.dist-info}/WHEEL +0 -0
  105. {evalscope-0.8.2.dist-info → evalscope-0.10.0.dist-info}/entry_points.txt +0 -0
  106. {evalscope-0.8.2.dist-info → evalscope-0.10.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1478 @@
1
+ # Copyright 2023 The Google Research Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Library of instructions."""
15
+
16
+ import collections
17
+ import json
18
+ import langdetect
19
+ import logging
20
+ import random
21
+ import re
22
+ import string
23
+ from typing import Dict, Optional, Sequence, Union
24
+
25
+ from evalscope.benchmarks.ifeval import instructions_util
26
+
27
+ _InstructionArgsDtype = Optional[Dict[str, Union[int, str, Sequence[str]]]]
28
+
29
+ _LANGUAGES = instructions_util.LANGUAGE_CODES
30
+
31
+ # The relational operation for comparison.
32
+ _COMPARISON_RELATION = ('less than', 'at least')
33
+
34
+ # The maximum number of sentences.
35
+ _MAX_NUM_SENTENCES = 20
36
+
37
+ # The number of placeholders.
38
+ _NUM_PLACEHOLDERS = 4
39
+
40
+ # The number of bullet lists.
41
+ _NUM_BULLETS = 5
42
+
43
+ # The options of constrained response.
44
+ _CONSTRAINED_RESPONSE_OPTIONS = (
45
+ 'My answer is yes.',
46
+ 'My answer is no.',
47
+ 'My answer is maybe.',
48
+ )
49
+
50
+ # The options of starter keywords.
51
+ _STARTER_OPTIONS = (
52
+ 'I would say',
53
+ 'My answer is',
54
+ 'I believe',
55
+ 'In my opinion',
56
+ 'I think',
57
+ 'I reckon',
58
+ 'I feel',
59
+ 'From my perspective',
60
+ 'As I see it',
61
+ 'According to me',
62
+ "As far as I'm concerned",
63
+ 'To my understanding',
64
+ 'In my view',
65
+ 'My take on it is',
66
+ 'As per my perception',
67
+ )
68
+
69
+ # The options of ending keywords.
70
+ # TODO(jeffreyzhou) add more ending options
71
+ _ENDING_OPTIONS = ('Any other questions?', 'Is there anything else I can help with?')
72
+
73
+ # The number of highlighted sections.
74
+ _NUM_HIGHLIGHTED_SECTIONS = 4
75
+
76
+ # The section splitter.
77
+ _SECTION_SPLITER = ('Section', 'SECTION')
78
+
79
+ # The number of sections.
80
+ _NUM_SECTIONS = 5
81
+
82
+ # The number of paragraphs.
83
+ _NUM_PARAGRAPHS = 5
84
+
85
+ # The postscript marker.
86
+ _POSTSCRIPT_MARKER = ('P.S.', 'P.P.S')
87
+
88
+ # The number of keywords.
89
+ _NUM_KEYWORDS = 2
90
+
91
+ # The occurrences of a single keyword.
92
+ _KEYWORD_FREQUENCY = 3
93
+
94
+ # The occurrences of a single letter.
95
+ _LETTER_FREQUENCY = 10
96
+
97
+ # The occurrences of words with all capital letters.
98
+ _ALL_CAPITAL_WORD_FREQUENCY = 20
99
+
100
+ # The number of words in the response.
101
+ _NUM_WORDS_LOWER_LIMIT = 100
102
+ _NUM_WORDS_UPPER_LIMIT = 500
103
+
104
+
105
+ class Instruction:
106
+ """An instruction template."""
107
+
108
+ def __init__(self, instruction_id):
109
+ self.id = instruction_id
110
+
111
+ def build_description(self, **kwargs):
112
+ raise NotImplementedError('`build_description` not implemented.')
113
+
114
+ def get_instruction_args(self):
115
+ raise NotImplementedError('`get_instruction_args` not implemented.')
116
+
117
+ def get_instruction_args_keys(self):
118
+ raise NotImplementedError('`get_instruction_args_keys` not implemented.')
119
+
120
+ def check_following(self, value):
121
+ raise NotImplementedError('`check_following` not implemented.')
122
+
123
+
124
+ class ResponseLanguageChecker(Instruction):
125
+ """Check the language of the entire response."""
126
+
127
+ def build_description(self, *, language=None):
128
+ """Build the instruction description.
129
+
130
+ Args:
131
+ language: A string representing the expected language of the response. The
132
+ language has to comply to the 97 types defined in
133
+ `langid.py` (https://pypi.org/project/langid/1.1.5/), which follows
134
+ ISO 639-1 codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes);
135
+ for example, `en` for English, `zh` for Chinese, `fr` for French.
136
+
137
+ Returns:
138
+ A string representing the instruction description.
139
+ """
140
+ self._language = language
141
+ if self._language is None:
142
+ self._language = random.choice(list(_LANGUAGES.keys()))
143
+ # TODO(tianjianlu): opens the description generation to more choices.
144
+ self._description_pattern = ('Your ENTIRE response should be in {language} language, no other '
145
+ + 'language is allowed.')
146
+ return self._description_pattern.format(language=_LANGUAGES[self._language])
147
+
148
+ def get_instruction_args(self):
149
+ """Returns the keyword args of `build_description`."""
150
+ return {'language': self._language}
151
+
152
+ def get_instruction_args_keys(self):
153
+ """Returns the args keys of `build_description`."""
154
+ return ['language']
155
+
156
+ def check_following(self, value):
157
+ """Check if the language of the entire response follows the instruction.
158
+
159
+ Args:
160
+ value: A string representing the response.
161
+
162
+ Returns:
163
+ True if the language of `value` follows instruction; otherwise False.
164
+ """
165
+ assert isinstance(value, str)
166
+
167
+ try:
168
+ return langdetect.detect(value) == self._language
169
+ except langdetect.LangDetectException as e:
170
+ # Count as instruction is followed.
171
+ logging.error('Unable to detect language for text %s due to %s', value, e) # refex: disable=pytotw.037
172
+ return True
173
+
174
+
175
+ class NumberOfSentences(Instruction):
176
+ """Check the number of sentences."""
177
+
178
+ def build_description(self, *, num_sentences=None, relation=None):
179
+ """Build the instruction description.
180
+
181
+ Args:
182
+ num_sentences: An integer specifying the number of sentences as a
183
+ threshold.
184
+ relation: A string in (`less than`, `at least`), defining the relational
185
+ operator for comparison.
186
+ Two relational comparisons are supported for now:
187
+ if 'less than', the actual number of sentences < the threshold;
188
+ if 'at least', the actual number of sentences >= the threshold.
189
+
190
+ Returns:
191
+ A string representing the instruction description.
192
+ """
193
+ # The number of sentences as a threshold for comparison.
194
+ self._num_sentences_threshold = num_sentences
195
+ if self._num_sentences_threshold is None or self._num_sentences_threshold < 0:
196
+ self._num_sentences_threshold = random.randint(1, _MAX_NUM_SENTENCES)
197
+
198
+ if relation is None:
199
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
200
+ elif relation not in _COMPARISON_RELATION:
201
+ raise ValueError('The supported relation for comparison must be in '
202
+ f'{_COMPARISON_RELATION}, but {relation} is given.')
203
+ else:
204
+ self._comparison_relation = relation
205
+
206
+ self._description_pattern = ('Your response should contain {relation} {num_sentences} sentences.')
207
+ return self._description_pattern.format(
208
+ relation=self._comparison_relation,
209
+ num_sentences=self._num_sentences_threshold,
210
+ )
211
+
212
+ def get_instruction_args(self):
213
+ """Returns the keyword args of `build_description`."""
214
+ return {
215
+ 'num_sentences': self._num_sentences_threshold,
216
+ 'relation': self._comparison_relation,
217
+ }
218
+
219
+ def get_instruction_args_keys(self):
220
+ """Returns the args keys of `build_description`."""
221
+ return ['num_sentences', 'relation']
222
+
223
+ def check_following(self, value):
224
+ """Check if the number of sentences follows the instruction.
225
+
226
+ Args:
227
+ value: A string representing the response.
228
+
229
+ Returns:
230
+ True if the response follows the instruction.
231
+
232
+ Raise:
233
+ ValueError if the string in `instruction_args` is not in
234
+ [`less_than`, `at_least`].
235
+ """
236
+ num_sentences = instructions_util.count_sentences(value)
237
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
238
+ return num_sentences < self._num_sentences_threshold
239
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
240
+ return num_sentences >= self._num_sentences_threshold
241
+
242
+
243
+ class PlaceholderChecker(Instruction):
244
+ """Check the placeholders in template writing."""
245
+
246
+ def build_description(self, *, num_placeholders=None):
247
+ """Build the instruction description.
248
+
249
+ Args:
250
+ num_placeholders: An integer denoting the minimum number of
251
+ placeholders required in the response.
252
+
253
+ Returns:
254
+ A string representing the instruction description.
255
+ """
256
+ self._num_placeholders = num_placeholders
257
+ if self._num_placeholders is None or self._num_placeholders < 0:
258
+ self._num_placeholders = random.randint(1, _NUM_PLACEHOLDERS)
259
+ self._description_pattern = ('The response must contain at least {num_placeholders} placeholders '
260
+ + 'represented by square brackets, such as [address].')
261
+ return self._description_pattern.format(num_placeholders=self._num_placeholders)
262
+
263
+ def get_instruction_args(self):
264
+ """Returns the keyword args of `build_description`."""
265
+ return {'num_placeholders': self._num_placeholders}
266
+
267
+ def get_instruction_args_keys(self):
268
+ """Returns the args keys of `build_description`."""
269
+ return ['num_placeholders']
270
+
271
+ def check_following(self, value):
272
+ """Check if the number of placeholders follows the instruction.
273
+
274
+ Args:
275
+ value: A string representing the response.
276
+
277
+ Returns:
278
+ True if the actual number of placeholders in the response is greater than
279
+ or equal to `num_placeholders`; otherwise, False.
280
+ """
281
+ placeholders = re.findall(r'\[.*?\]', value)
282
+ num_placeholders = len(placeholders)
283
+ return num_placeholders >= self._num_placeholders
284
+
285
+
286
+ class BulletListChecker(Instruction):
287
+ """Checks the bullet list in the prompt."""
288
+
289
+ def build_description(self, *, num_bullets=None):
290
+ """Build the instruction description.
291
+
292
+ Args:
293
+ num_bullets: An integer specifying the exact number of bullet lists
294
+ that is required to appear in the response.
295
+
296
+ Returns:
297
+ A string representing the instruction description.
298
+ """
299
+ self._num_bullets = num_bullets
300
+ if self._num_bullets is None or self._num_bullets < 0:
301
+ self._num_bullets = random.randint(1, _NUM_BULLETS)
302
+ self._description_pattern = ('Your answer must contain exactly {num_bullets} bullet points. '
303
+ + 'Use the markdown bullet points such as:\n' + '* This is point 1. \n'
304
+ + '* This is point 2')
305
+ return self._description_pattern.format(num_bullets=self._num_bullets)
306
+
307
+ def get_instruction_args(self):
308
+ """Returns the keyword args of `build_description`."""
309
+ return {'num_bullets': self._num_bullets}
310
+
311
+ def get_instruction_args_keys(self):
312
+ """Returns the args keys of `build_description`."""
313
+ return ['num_bullets']
314
+
315
+ def check_following(self, value):
316
+ r"""Check if the number of bullet lists meets the requirement.
317
+
318
+ Args:
319
+ value: A string representing the response. The response is expected to
320
+ contain some bullet lists that start with `\*`.
321
+
322
+ Returns:
323
+ True if the actual number of bullet lists in the response meets the
324
+ requirement.
325
+ """
326
+ bullet_lists = re.findall(r'^\s*\*[^\*].*$', value, flags=re.MULTILINE)
327
+ bullet_lists_2 = re.findall(r'^\s*-.*$', value, flags=re.MULTILINE)
328
+ num_bullet_lists = len(bullet_lists) + len(bullet_lists_2)
329
+ return num_bullet_lists == self._num_bullets
330
+
331
+
332
+ class ConstrainedResponseChecker(Instruction):
333
+ """Checks the constrained response."""
334
+
335
+ def build_description(self):
336
+ """Build the instruction description."""
337
+ # A sequence of string(s) representing the options of the expected response.
338
+ self._constrained_responses = _CONSTRAINED_RESPONSE_OPTIONS
339
+ self._description_pattern = ('Answer with one of the following options: {response_options}')
340
+ return self._description_pattern.format(response_options=self._constrained_responses)
341
+
342
+ def get_instruction_args(self):
343
+ """Returns the keyword args of `build_description`."""
344
+ return None
345
+
346
+ def get_instruction_args_keys(self):
347
+ """Returns the args keys of `build_description`."""
348
+ return []
349
+
350
+ def check_following(self, value):
351
+ """Checks if the response matches the constrained options.
352
+
353
+ Args:
354
+ value: A string representing the response.
355
+
356
+ Returns:
357
+ True if the actual response contains one of the options in the constrained
358
+ responses; otherwise False.
359
+ """
360
+ value = value.strip()
361
+ for constrained_response in self._constrained_responses:
362
+ if constrained_response in value:
363
+ return True
364
+ return False
365
+
366
+
367
+ class ConstrainedStartChecker(Instruction):
368
+ """Checks the response start."""
369
+
370
+ def build_description(self, *, starter=None):
371
+ """Build the instruction description.
372
+
373
+ Args:
374
+ starter: A string representing the keyword that the response should start
375
+ with.
376
+
377
+ Returns:
378
+ A string representing the instruction description.
379
+ """
380
+ self._starter = starter.strip() if isinstance(starter, str) else starter
381
+ if self._starter is None:
382
+ self._starter = random.choice(_STARTER_OPTIONS)
383
+ self._description_pattern = ('During the conversation, when it is your turn, '
384
+ + 'please always start with {starter}')
385
+ return self._description_pattern.format(starter=self._starter)
386
+
387
+ def get_instruction_args(self):
388
+ """Returns the keyword args of `build_description`."""
389
+ return {'starter': self._starter}
390
+
391
+ def get_instruction_args_keys(self):
392
+ """Returns the args keys of `build_description`."""
393
+ return ['starter']
394
+
395
+ def check_following(self, value):
396
+ """Checks if the response starts with the constrained keyword or phrase.
397
+
398
+ Args:
399
+ value: A string representing the response.
400
+
401
+ Returns:
402
+ True if the response starts with the given phrase or keyword that is
403
+ contained in `instruction_args`; otherwise, False.
404
+ """
405
+ response_pattern = r'^\s*' + self._starter + r'.*$'
406
+ response_with_constrained_start = re.search(response_pattern, value, flags=re.MULTILINE)
407
+ return True if response_with_constrained_start else False
408
+
409
+
410
+ class HighlightSectionChecker(Instruction):
411
+ """Checks the highlighted section."""
412
+
413
+ def build_description(self, *, num_highlights=None):
414
+ """Build the instruction description.
415
+
416
+ Args:
417
+ num_highlights: An integer specifying the minimum number of highlighted
418
+ sections.
419
+
420
+ Returns:
421
+ A string representing the instruction description.
422
+ """
423
+ self._num_highlights = num_highlights
424
+ if self._num_highlights is None or self._num_highlights < 0:
425
+ self._num_highlights = random.randint(1, _NUM_HIGHLIGHTED_SECTIONS)
426
+
427
+ self._description_pattern = ('Highlight at least {num_highlights} sections in your answer with '
428
+ + 'markdown, i.e. *highlighted section*.')
429
+
430
+ return self._description_pattern.format(num_highlights=self._num_highlights)
431
+
432
+ def get_instruction_args(self):
433
+ """Returns the keyword args of `build_description`."""
434
+ return {'num_highlights': self._num_highlights}
435
+
436
+ def get_instruction_args_keys(self):
437
+ """Returns the args keys of `build_description`."""
438
+ return ['num_highlights']
439
+
440
+ def check_following(self, value):
441
+ """Checks if the number of highlighted sections meets the requirement.
442
+
443
+ Args:
444
+ value: a string representing the response. The response is expected to
445
+ contain highlighted sections in the format of *highlighted*.
446
+
447
+ Returns:
448
+ True if the actual number of highlighted sections in the format of
449
+ *highlighted sections* meets the minimum requirement; otherwise False.
450
+ """
451
+ num_highlights = 0
452
+ highlights = re.findall(r'\*[^\n\*]*\*', value)
453
+ double_highlights = re.findall(r'\*\*[^\n\*]*\*\*', value)
454
+ for highlight in highlights:
455
+ if highlight.strip('*').strip():
456
+ num_highlights += 1
457
+ for highlight in double_highlights:
458
+ if highlight.removeprefix('**').removesuffix('**').strip():
459
+ num_highlights += 1
460
+
461
+ return num_highlights >= self._num_highlights
462
+
463
+
464
+ class SectionChecker(Instruction):
465
+ """Checks the sections."""
466
+
467
+ def build_description(self, *, section_spliter=None, num_sections=None):
468
+ """Build the instruction description.
469
+
470
+ Args:
471
+ section_spliter: A string represents the section spliter keyword that
472
+ marks a new section, i.e., `Section` or `SECTION`.
473
+ num_sections: An integer specifying the number of sections.
474
+
475
+ Returns:
476
+ A string representing the instruction description.
477
+ """
478
+ self._section_spliter = (section_spliter.strip() if isinstance(section_spliter, str) else section_spliter)
479
+ if self._section_spliter is None:
480
+ self._section_spliter = random.choice(_SECTION_SPLITER)
481
+
482
+ self._num_sections = num_sections
483
+ if self._num_sections is None or self._num_sections < 0:
484
+ self._num_sections = random.randint(1, _NUM_SECTIONS)
485
+
486
+ self._description_pattern = ('Your response must have {num_sections} sections. Mark the beginning '
487
+ + 'of each section with {section_spliter} X, such as:\n' + '{section_spliter} 1\n'
488
+ + '[content of section 1]\n' + '{section_spliter} 2\n' + '[content of section 2]')
489
+
490
+ return self._description_pattern.format(num_sections=self._num_sections, section_spliter=self._section_spliter)
491
+
492
+ def get_instruction_args(self):
493
+ """Returns the keyword args of `build_description`."""
494
+ return {
495
+ 'section_spliter': self._section_spliter,
496
+ 'num_sections': self._num_sections,
497
+ }
498
+
499
+ def get_instruction_args_keys(self):
500
+ """Returns the args keys of `build_description`."""
501
+ return ['section_spliter', 'num_sections']
502
+
503
+ def check_following(self, value):
504
+ """Checks the response contains multiple sections.
505
+
506
+ Args:
507
+ value: A string representing the response. The response is expected
508
+ to contain multiple sections (number of sections is greater than 1).
509
+ A new section starts with `Section 1`, where the number denotes the
510
+ section index.
511
+
512
+ Returns:
513
+ True if the number of sections in the response is greater than or equal to
514
+ the minimum number of sections; otherwise, False.
515
+ """
516
+ section_splitter_patten = r'\s?' + self._section_spliter + r'\s?\d+\s?'
517
+ sections = re.split(section_splitter_patten, value)
518
+ num_sections = len(sections) - 1
519
+ return num_sections >= self._num_sections
520
+
521
+
522
+ class ParagraphChecker(Instruction):
523
+ """Checks the paragraphs."""
524
+
525
+ def build_description(self, *, num_paragraphs=None):
526
+ """Build the instruction description.
527
+
528
+ Args:
529
+ num_paragraphs: An integer specifying the number of paragraphs.
530
+
531
+ Returns:
532
+ A string representing the instruction description.
533
+ """
534
+ self._num_paragraphs = num_paragraphs
535
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
536
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
537
+
538
+ self._description_pattern = ('There should be {num_paragraphs} paragraphs. '
539
+ + 'Paragraphs are separated with the markdown divider: ***')
540
+
541
+ return self._description_pattern.format(num_paragraphs=self._num_paragraphs)
542
+
543
+ def get_instruction_args(self):
544
+ """Returns the keyword args of `build_description`."""
545
+ return {'num_paragraphs': self._num_paragraphs}
546
+
547
+ def get_instruction_args_keys(self):
548
+ """Returns the args keys of `build_description`."""
549
+ return ['num_paragraphs']
550
+
551
+ def check_following(self, value):
552
+ """Checks the response contains required number of paragraphs.
553
+
554
+ Args:
555
+ value: A string representing the response. The response may contain
556
+ paragraphs that are separated by the markdown divider: `***`.
557
+
558
+ Returns:
559
+ True if the actual number of paragraphs is the same as required;
560
+ otherwise, False.
561
+ """
562
+ paragraphs = re.split(r'\s?\*\*\*\s?', value)
563
+ num_paragraphs = len(paragraphs)
564
+
565
+ for index, paragraph in enumerate(paragraphs):
566
+ if not paragraph.strip():
567
+ if index == 0 or index == len(paragraphs) - 1:
568
+ num_paragraphs -= 1
569
+ else:
570
+ return False
571
+
572
+ return num_paragraphs == self._num_paragraphs
573
+
574
+
575
+ class PostscriptChecker(Instruction):
576
+ """Checks the postscript."""
577
+
578
+ def build_description(self, *, postscript_marker=None):
579
+ """Build the instruction description.
580
+
581
+ Args:
582
+ postscript_marker: A string containing the keyword that marks the start
583
+ of the postscript section.
584
+
585
+ Returns:
586
+ A string representing the instruction description.
587
+ """
588
+ self._postscript_marker = (
589
+ postscript_marker.strip() if isinstance(postscript_marker, str) else postscript_marker)
590
+ if self._postscript_marker is None:
591
+ self._postscript_marker = random.choice(_POSTSCRIPT_MARKER)
592
+
593
+ self._description_pattern = ('At the end of your response, please explicitly add a postscript '
594
+ + 'starting with {postscript}')
595
+
596
+ return self._description_pattern.format(postscript=self._postscript_marker)
597
+
598
+ def get_instruction_args(self):
599
+ """Returns the keyword args of `build_description`."""
600
+ return {'postscript_marker': self._postscript_marker}
601
+
602
+ def get_instruction_args_keys(self):
603
+ """Returns the args keys of `build_description`."""
604
+ return ['postscript_marker']
605
+
606
+ def check_following(self, value):
607
+ """Checks if the response follows the postscript format.
608
+
609
+ Args:
610
+ value: a string representing the response. The response is expected to
611
+ contain a postscript section.
612
+
613
+ Returns:
614
+ True if the response contains a postscript section starting with
615
+ the keyword containing in the `instruction_args`; otherwise False.
616
+ """
617
+ value = value.lower()
618
+ if self._postscript_marker == 'P.P.S':
619
+ postscript_pattern = r'\s*p\.\s?p\.\s?s.*$'
620
+ elif self._postscript_marker == 'P.S.':
621
+ postscript_pattern = r'\s*p\.\s?s\..*$'
622
+ else:
623
+ postscript_pattern = r'\s*' + self._postscript_marker.lower() + r'.*$'
624
+ postscript = re.findall(postscript_pattern, value, flags=re.MULTILINE)
625
+ return True if postscript else False
626
+
627
+
628
+ class RephraseChecker(Instruction):
629
+ """Checks the rephrase."""
630
+
631
+ def build_description(self, *, original_message):
632
+ """Build the instruction description.
633
+
634
+ Args:
635
+ original_message: A string representing the original message. The
636
+ rephrased response should only change its words/sentences in between
637
+ its two asterisks, for example, *change me*. Both original and rephrased
638
+ messages should contain the changes in the form of *change me*.
639
+
640
+ Returns:
641
+ A string representing the instruction description.
642
+ """
643
+ if not self.is_change(original_message):
644
+ raise ValueError(f'Message {original_message} does not contain changes '
645
+ 'in the form of *change me*.')
646
+
647
+ self._reference_without_change = original_message
648
+ self._description = ('Rephrasing: Your rephrased response should only'
649
+ + 'change the words/sentences in between two asterisks' + 'such as *change me*.')
650
+ return self._description
651
+
652
+ def get_instruction_args(self):
653
+ """Returns the keyword args of `build_description`."""
654
+ return {'original_message': self._reference_without_change}
655
+
656
+ def get_instruction_args_keys(self):
657
+ """Returns the args keys of `build_description`."""
658
+ return ['original_message']
659
+
660
+ def check_following(self, value):
661
+ r"""Checks if the rephrasing follows the instruction.
662
+
663
+ Args:
664
+ value: A string representing the response, which is expected to rephras
665
+ the string of `instruction_args`.
666
+
667
+ Returns:
668
+ True if `value` and `instruction_args` only differ by the words/sentences
669
+ in between two asterisks such as *change me*; otherwise, False.
670
+ """
671
+
672
+ if not self.is_change(value):
673
+ raise ValueError(f'value {value} does not contain '
674
+ 'changes in the form of *change me*.')
675
+
676
+ response_without_changes = self.strip_changes(value)
677
+ reference_without_changes = self.strip_changes(self._reference_without_change)
678
+
679
+ return response_without_changes == reference_without_changes
680
+
681
+ def is_change(self, response):
682
+ """Check if there is change in the response in the form of *change me*."""
683
+ return re.search(r'\*.*\*', response)
684
+
685
+ def strip_changes(self, response):
686
+ """Strips off the changes."""
687
+ return re.sub(r'\*.*\*', '', response)
688
+
689
+
690
+ class KeywordChecker(Instruction):
691
+ """Check the exisitence of certain keywords."""
692
+
693
+ def build_description(self, *, keywords=None):
694
+ """Build the instruction description.
695
+
696
+ Args:
697
+ keywords: A sequence of strings representing the keywords that are
698
+ expected in the response.
699
+
700
+ Returns:
701
+ A string representing the instruction description.
702
+ """
703
+
704
+ if not keywords:
705
+ self._keywords = instructions_util.generate_keywords(num_keywords=_NUM_KEYWORDS)
706
+ else:
707
+ self._keywords = keywords
708
+ self._keywords = sorted(self._keywords)
709
+
710
+ self._description_pattern = 'Include keywords {keywords} in the response.'
711
+
712
+ return self._description_pattern.format(keywords=self._keywords)
713
+
714
+ def get_instruction_args(self):
715
+ """Returns the keyword args of `build_description`."""
716
+ return {'keywords': self._keywords}
717
+
718
+ def get_instruction_args_keys(self):
719
+ """Returns the args keys of `build_description`."""
720
+ return ['keywords']
721
+
722
+ def check_following(self, value):
723
+ """Check if the response contain the expected keywords."""
724
+ for keyword in self._keywords:
725
+ if not re.search(keyword, value, flags=re.IGNORECASE):
726
+ return False
727
+ return True
728
+
729
+
730
+ class KeywordFrequencyChecker(Instruction):
731
+ """Check the keyword frequency."""
732
+
733
+ def build_description(self, *, keyword=None, frequency=None, relation=None):
734
+ """Build the instruction description.
735
+
736
+ Args:
737
+ keyword: A string representing a keyword that is expected in the response.
738
+ frequency: An integer specifying the number of times `keyword` is expected
739
+ to appear in the response.
740
+ relation: A string in (`less than`, `at least`), defining the relational
741
+ operator for comparison.
742
+ Two relational comparisons are supported for now:
743
+ if 'less than', the actual number of occurrences < frequency;
744
+ if 'at least', the actual number of occurrences >= frequency.
745
+
746
+ Returns:
747
+ A string representing the instruction description.
748
+ """
749
+ if not keyword:
750
+ self._keyword = instructions_util.generate_keywords(num_keywords=1)[0]
751
+ else:
752
+ self._keyword = keyword.strip()
753
+
754
+ self._frequency = frequency
755
+ if self._frequency is None or self._frequency < 0:
756
+ self._frequency = random.randint(1, _KEYWORD_FREQUENCY)
757
+
758
+ if relation is None:
759
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
760
+ elif relation not in _COMPARISON_RELATION:
761
+ raise ValueError('The supported relation for comparison must be in '
762
+ f'{_COMPARISON_RELATION}, but {relation} is given.')
763
+ else:
764
+ self._comparison_relation = relation
765
+
766
+ self._description_pattern = ('In your response, the word {keyword} should appear {relation} '
767
+ + '{frequency} times.')
768
+
769
+ return self._description_pattern.format(
770
+ keyword=self._keyword,
771
+ relation=self._comparison_relation,
772
+ frequency=self._frequency,
773
+ )
774
+
775
+ def get_instruction_args(self):
776
+ """Returns the keyword args of `build_description`."""
777
+ return {
778
+ 'keyword': self._keyword,
779
+ 'frequency': self._frequency,
780
+ 'relation': self._comparison_relation,
781
+ }
782
+
783
+ def get_instruction_args_keys(self):
784
+ """Returns the args keys of `build_description`."""
785
+ return ['keyword', 'frequency', 'relation']
786
+
787
+ def check_following(self, value):
788
+ """Checks if the response contain the keyword with required frequency."""
789
+ actual_occurrences = len(re.findall(self._keyword, value, flags=re.IGNORECASE))
790
+
791
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
792
+ return actual_occurrences < self._frequency
793
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
794
+ return actual_occurrences >= self._frequency
795
+
796
+
797
+ class NumberOfWords(Instruction):
798
+ """Checks the number of words."""
799
+
800
+ def build_description(self, *, num_words=None, relation=None):
801
+ """Build the instruction description.
802
+
803
+ Args:
804
+ num_words: An integer specifying the number of words contained in the
805
+ response.
806
+ relation: A string in (`less than`, `at least`), defining the relational
807
+ operator for comparison.
808
+ Two relational comparisons are supported for now:
809
+ if 'less than', the actual number of words < num_words;
810
+ if 'at least', the actual number of words >= num_words.
811
+
812
+ Returns:
813
+ A string representing the instruction description.
814
+ """
815
+
816
+ self._num_words = num_words
817
+ if self._num_words is None or self._num_words < 0:
818
+ self._num_words = random.randint(_NUM_WORDS_LOWER_LIMIT, _NUM_WORDS_UPPER_LIMIT)
819
+
820
+ if relation is None:
821
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
822
+ elif relation not in _COMPARISON_RELATION:
823
+ raise ValueError('The supported relation for comparison must be in '
824
+ f'{_COMPARISON_RELATION}, but {relation} is given.')
825
+ else:
826
+ self._comparison_relation = relation
827
+
828
+ self._description_pattern = 'Answer with {relation} {num_words} words.'
829
+
830
+ return self._description_pattern.format(relation=self._comparison_relation, num_words=self._num_words)
831
+
832
+ def get_instruction_args(self):
833
+ """Returns the keyword args of `build_description`."""
834
+ return {'num_words': self._num_words, 'relation': self._comparison_relation}
835
+
836
+ def get_instruction_args_keys(self):
837
+ """Returns the args keys of `build_description`."""
838
+ return ['num_words', 'relation']
839
+
840
+ def check_following(self, value):
841
+ """Checks if the response contains the expected number of words."""
842
+ num_words = instructions_util.count_words(value)
843
+
844
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
845
+ return num_words < self._num_words
846
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
847
+ return num_words >= self._num_words
848
+
849
+
850
+ class JsonFormat(Instruction):
851
+ """Check the Json format."""
852
+
853
+ def build_description(self):
854
+ self._description_pattern = ('Entire output should be wrapped in JSON format. You can use markdown'
855
+ ' ticks such as ```.')
856
+ return self._description_pattern
857
+
858
+ def get_instruction_args(self):
859
+ """Returns the keyword args of `build_description`."""
860
+ return None
861
+
862
+ def get_instruction_args_keys(self):
863
+ """Returns the args keys of `build_description`."""
864
+ return []
865
+
866
+ def check_following(self, value):
867
+ value = (
868
+ value.strip().removeprefix('```json').removeprefix('```Json').removeprefix('```JSON').removeprefix(
869
+ '```').removesuffix('```').strip())
870
+ try:
871
+ json.loads(value)
872
+ except ValueError:
873
+ return False
874
+ return True
875
+
876
+
877
+ class ParagraphFirstWordCheck(Instruction):
878
+ """Check the paragraph and the first word of the nth paragraph."""
879
+
880
+ def build_description(self, num_paragraphs=None, nth_paragraph=None, first_word=None):
881
+ r"""Build the instruction description.
882
+
883
+ Args:
884
+ num_paragraphs: An integer indicating the number of paragraphs expected
885
+ in the response. A paragraph is a subset of the string that is
886
+ expected to be separated by '\n\n'.
887
+ nth_paragraph: An integer indicating the paragraph number that we look at.
888
+ Note that n starts from 1.
889
+ first_word: A string that represent the first word of the bth paragraph.
890
+
891
+ Returns:
892
+ A string representing the instruction description.
893
+ """
894
+ self._num_paragraphs = num_paragraphs
895
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
896
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
897
+
898
+ self._nth_paragraph = nth_paragraph
899
+ if (self._nth_paragraph is None or self._nth_paragraph <= 0 or self._nth_paragraph > self._num_paragraphs):
900
+ self._nth_paragraph = random.randint(1, self._num_paragraphs + 1)
901
+
902
+ self._first_word = first_word
903
+ if self._first_word is None:
904
+ self._first_word = instructions_util.generate_keywords(num_keywords=1)[0]
905
+ self._first_word = self._first_word.lower()
906
+
907
+ self._description_pattern = ('There should be {num_paragraphs} paragraphs. '
908
+ + 'Paragraphs and only paragraphs are separated with each other by two '
909
+ + "new lines as if it was '\\n\\n' in python. "
910
+ + 'Paragraph {nth_paragraph} must start with word {first_word}.')
911
+
912
+ return self._description_pattern.format(
913
+ num_paragraphs=self._num_paragraphs,
914
+ nth_paragraph=self._nth_paragraph,
915
+ first_word=self._first_word,
916
+ )
917
+
918
+ def get_instruction_args(self):
919
+ """Returns the keyword args of `build_description`."""
920
+ return {
921
+ 'num_paragraphs': self._num_paragraphs,
922
+ 'nth_paragraph': self._nth_paragraph,
923
+ 'first_word': self._first_word,
924
+ }
925
+
926
+ def get_instruction_args_keys(self):
927
+ """Returns the args keys of `build_description`."""
928
+ return ['num_paragraphs', 'nth_paragraph', 'first_word']
929
+
930
+ def check_following(self, value):
931
+ """Checks for required number of paragraphs and correct first word.
932
+
933
+ Args:
934
+ value: a string representing the response. The response may contain
935
+ paragraphs that are separated by two new lines and the first word of
936
+ the nth paragraph will have to match a specified word.
937
+
938
+ Returns:
939
+ True if the number of paragraphs is the same as required and the first
940
+ word of the specified paragraph is the same as required. Otherwise, false.
941
+ """
942
+
943
+ paragraphs = re.split(r'\n\n', value)
944
+ num_paragraphs = len(paragraphs)
945
+
946
+ for paragraph in paragraphs:
947
+ if not paragraph.strip():
948
+ num_paragraphs -= 1
949
+
950
+ # check that index doesn't go out of bounds
951
+ if self._nth_paragraph <= num_paragraphs:
952
+ paragraph = paragraphs[self._nth_paragraph - 1].strip()
953
+ if not paragraph:
954
+ return False
955
+ else:
956
+ return False
957
+
958
+ first_word = ''
959
+ punctuation = {'.', ',', '?', '!', "'", '"'}
960
+
961
+ # get first word and remove punctuation
962
+ word = paragraph.split()[0].strip()
963
+ # TODO(jeffrey): make more complex?
964
+ word = word.lstrip("'")
965
+ word = word.lstrip('"')
966
+
967
+ for letter in word:
968
+ if letter in punctuation:
969
+ break
970
+ first_word += letter.lower()
971
+
972
+ return num_paragraphs == self._num_paragraphs and first_word == self._first_word
973
+
974
+
975
+ # TODO(jeffrey) add relation - at least/at most?
976
+ class KeySentenceChecker(Instruction):
977
+ """Check the existence of certain key sentences."""
978
+
979
+ def build_description(self, key_sentences=None, num_sentences=None):
980
+ """Build the instruction description.
981
+
982
+ Args:
983
+ key_sentences: A sequences of strings representing the key sentences that
984
+ are expected in the response.
985
+ num_sentences: The number of key sentences that are expected to be seen in
986
+ the response.
987
+
988
+ Returns:
989
+ A string representing the instruction description.
990
+ """
991
+
992
+ if not key_sentences:
993
+ # TODO(jeffrey) make a generate sentences function? wonderwords package
994
+ self._key_sentences = set(['For now, this is fine.'])
995
+ else:
996
+ self._key_sentences = key_sentences
997
+
998
+ if not num_sentences:
999
+ self._num_sentences = random.randint(1, len(self._key_sentences))
1000
+ else:
1001
+ self._num_sentences = num_sentences
1002
+
1003
+ self._description_pattern = ('Include {num_sentences} of the following sentences {key_sentences}')
1004
+
1005
+ return self._description_pattern.format(num_sentences=self._num_sentences, key_sentences=self._key_sentences)
1006
+
1007
+ def get_instruction_args(self):
1008
+ """Returns the keyword args of `build_description`."""
1009
+ return {
1010
+ 'num_sentences': self._num_sentences,
1011
+ 'key_sentences': list(self._key_sentences),
1012
+ }
1013
+
1014
+ def get_instruction_args_keys(self):
1015
+ """Returns the args keys of `build_description`."""
1016
+ return ['num_sentences', 'key_sentences']
1017
+
1018
+ def check_following(self, value):
1019
+ """Checks if the response contains the expected key sentences."""
1020
+ count = 0
1021
+ sentences = instructions_util.split_into_sentences(value)
1022
+ for sentence in self._key_sentences:
1023
+ if sentence in sentences:
1024
+ count += 1
1025
+
1026
+ return count == self._num_sentences
1027
+
1028
+
1029
+ class ForbiddenWords(Instruction):
1030
+ """Checks that specified words are not used in response."""
1031
+
1032
+ def build_description(self, forbidden_words=None):
1033
+ """Build the instruction description.
1034
+
1035
+ Args:
1036
+ forbidden_words: A sequences of strings representing words that are not
1037
+ allowed in the response.
1038
+
1039
+ Returns:
1040
+ A string representing the instruction description.
1041
+ """
1042
+
1043
+ if not forbidden_words:
1044
+ self._forbidden_words = instructions_util.generate_keywords(num_keywords=_NUM_KEYWORDS)
1045
+ else:
1046
+ self._forbidden_words = list(set(forbidden_words))
1047
+ self._forbidden_words = sorted(self._forbidden_words)
1048
+ self._description_pattern = ('Do not include keywords {forbidden_words} in the response.')
1049
+
1050
+ return self._description_pattern.format(forbidden_words=self._forbidden_words)
1051
+
1052
+ def get_instruction_args(self):
1053
+ """Returns the keyword args of `build_description`."""
1054
+ return {'forbidden_words': self._forbidden_words}
1055
+
1056
+ def get_instruction_args_keys(self):
1057
+ """Returns the args keys of `build_description`."""
1058
+ return ['forbidden_words']
1059
+
1060
+ def check_following(self, value):
1061
+ """Check if the response does not contain the expected keywords."""
1062
+ for word in self._forbidden_words:
1063
+ if re.search(r'\b' + word + r'\b', value, flags=re.IGNORECASE):
1064
+ return False
1065
+ return True
1066
+
1067
+
1068
+ class RephraseParagraph(Instruction):
1069
+ """Checks that the paragraph is rephrased."""
1070
+
1071
+ def build_description(self, *, original_paragraph, low, high):
1072
+ """Builds the instruction description.
1073
+
1074
+ Args:
1075
+ original_paragraph: A string presenting the original paragraph. The
1076
+ rephrases response should have betweeb low-high words in common.
1077
+ low: An integer presenting the lower bound of similar words.
1078
+ high: An integer representing the upper bound of similar words.
1079
+
1080
+ Returns:
1081
+ A string representing the instruction description.
1082
+ """
1083
+ # TODO(jeffrey) make more encompassing
1084
+ self._original_paragraph = original_paragraph
1085
+ self._low = low
1086
+ self._high = high
1087
+
1088
+ self._description = ('Rephrase the following paragraph: ' + '{original_paragraph}\nYour response should have '
1089
+ + 'between {low} and {high} of the same words. '
1090
+ + 'Words are the same if and only if all of the '
1091
+ + 'letters, ignoring cases, are the same. For '
1092
+ + "example, 'run' is the same as 'Run' but different " + "to 'ran'.")
1093
+
1094
+ return self._description.format(original_paragraph=original_paragraph, low=self._low, high=self._high)
1095
+
1096
+ def get_instruction_args(self):
1097
+ """Returns the keyword args of `build_description`."""
1098
+ return {
1099
+ 'original_paragraph': self._original_paragraph,
1100
+ 'low': self._low,
1101
+ 'high': self._high,
1102
+ }
1103
+
1104
+ def get_instruction_args_keys(self):
1105
+ """Returns the args keys of `build_description`."""
1106
+ return ['original_paragraph', 'low', 'high']
1107
+
1108
+ def check_following(self, value):
1109
+ val_words = re.findall(r'\w+', value.lower())
1110
+ original_words = re.findall(r'\w+', self._original_paragraph.lower())
1111
+ similar_words = 0
1112
+
1113
+ dict_val = collections.Counter(val_words)
1114
+ dict_original = collections.Counter(original_words)
1115
+
1116
+ for word in dict_original:
1117
+ similar_words += min(dict_original[word], dict_val[word])
1118
+
1119
+ return similar_words >= self._low and similar_words <= self._high
1120
+
1121
+
1122
+ class TwoResponsesChecker(Instruction):
1123
+ """Check that two responses were given."""
1124
+
1125
+ def build_description(self):
1126
+ """Build the instruction description."""
1127
+ self._description_pattern = ('Give two different responses. Responses and only responses should'
1128
+ ' be separated by 6 asterisk symbols: ******.')
1129
+ return self._description_pattern
1130
+
1131
+ def get_instruction_args(self):
1132
+ """Returns the keyword args of `build_description`."""
1133
+ return None
1134
+
1135
+ def get_instruction_args_keys(self):
1136
+ """Returns the args keys of `build_description`."""
1137
+ return []
1138
+
1139
+ def check_following(self, value):
1140
+ """Checks if the response has two different answers.
1141
+
1142
+ Args:
1143
+ value: A string representing the response.
1144
+
1145
+ Returns:
1146
+ True if two responses are detected and false otherwise.
1147
+ """
1148
+ valid_responses = list()
1149
+ responses = value.split('******')
1150
+ for index, response in enumerate(responses):
1151
+ if not response.strip():
1152
+ if index != 0 and index != len(responses) - 1:
1153
+ return False
1154
+ else:
1155
+ valid_responses.append(response)
1156
+ return (len(valid_responses) == 2 and valid_responses[0].strip() != valid_responses[1].strip())
1157
+
1158
+
1159
+ class RepeatPromptThenAnswer(Instruction):
1160
+ """Checks that Prompt is first repeated then answered."""
1161
+
1162
+ def build_description(self, *, prompt_to_repeat=None):
1163
+ """Build the instruction description.
1164
+
1165
+ Args:
1166
+ prompt_to_repeat: The prompt that is meant to be repeated.
1167
+
1168
+ Returns:
1169
+ A string representing the instruction description.
1170
+ """
1171
+ if not prompt_to_repeat:
1172
+ raise ValueError('prompt_to_repeat must be set.')
1173
+ else:
1174
+ self._prompt_to_repeat = prompt_to_repeat
1175
+ self._description_pattern = ('First repeat the request word for word without change,'
1176
+ ' then give your answer (1. do not say any words or characters'
1177
+ ' before repeating the request; 2. the request you need to repeat'
1178
+ ' does not include this sentence)')
1179
+ return self._description_pattern
1180
+
1181
+ def get_instruction_args(self):
1182
+ return {'prompt_to_repeat': self._prompt_to_repeat}
1183
+
1184
+ def get_instruction_args_keys(self):
1185
+ """Returns the args keys of `build_description`."""
1186
+ return ['prompt_to_repeat']
1187
+
1188
+ def check_following(self, value):
1189
+ if value.strip().lower().startswith(self._prompt_to_repeat.strip().lower()):
1190
+ return True
1191
+ return False
1192
+
1193
+
1194
+ class EndChecker(Instruction):
1195
+ """Checks that the prompt ends with a given phrase."""
1196
+
1197
+ def build_description(self, *, end_phrase=None):
1198
+ """Build the instruction description.
1199
+
1200
+ Args:
1201
+ end_phrase: A string representing the phrase the response should end with.
1202
+
1203
+ Returns:
1204
+ A string representing the instruction description.
1205
+ """
1206
+ self._end_phrase = (end_phrase.strip() if isinstance(end_phrase, str) else end_phrase)
1207
+ if self._end_phrase is None:
1208
+ self._end_phrase = random.choice(_ENDING_OPTIONS)
1209
+ self._description_pattern = ('Finish your response with this exact phrase {ender}. '
1210
+ 'No other words should follow this phrase.')
1211
+ return self._description_pattern.format(ender=self._end_phrase)
1212
+
1213
+ def get_instruction_args(self):
1214
+ return {'end_phrase': self._end_phrase}
1215
+
1216
+ def get_instruction_args_keys(self):
1217
+ """Returns the args keys of `build_description`."""
1218
+ return ['end_phrase']
1219
+
1220
+ def check_following(self, value):
1221
+ """Checks if the response ends with the expected phrase."""
1222
+ value = value.strip().strip('"').lower()
1223
+ self._end_phrase = self._end_phrase.strip().lower()
1224
+ return value.endswith(self._end_phrase)
1225
+
1226
+
1227
+ class TitleChecker(Instruction):
1228
+ """Checks the response for a title."""
1229
+
1230
+ def build_description(self):
1231
+ """Build the instruction description."""
1232
+ self._description_pattern = ('Your answer must contain a title, wrapped in double angular brackets,'
1233
+ ' such as <<poem of joy>>.')
1234
+ return self._description_pattern
1235
+
1236
+ def get_instruction_args(self):
1237
+ return None
1238
+
1239
+ def get_instruction_args_keys(self):
1240
+ """Returns the args keys of `build_description`."""
1241
+ return []
1242
+
1243
+ def check_following(self, value):
1244
+ """Checks if the response contains a title."""
1245
+ pattern = r'<<[^\n]+>>'
1246
+ re_pattern = re.compile(pattern)
1247
+ titles = re.findall(re_pattern, value)
1248
+
1249
+ for title in titles:
1250
+ if title.lstrip('<').rstrip('>').strip():
1251
+ return True
1252
+ return False
1253
+
1254
+
1255
+ class LetterFrequencyChecker(Instruction):
1256
+ """Checks letter frequency."""
1257
+
1258
+ def build_description(self, *, letter=None, let_frequency=None, let_relation=None):
1259
+ """Build the instruction description.
1260
+
1261
+ Args:
1262
+ letter: A string representing a letter that is expected in the response.
1263
+ let_frequency: An integer specifying the number of times `keyword` is
1264
+ expected to appear in the response.
1265
+ let_relation: A string in (`less than`, `at least`), defining the
1266
+ relational operator for comparison. Two relational comparisons are
1267
+ supported for now; if 'less than', the actual number of
1268
+ occurrences < frequency; if 'at least', the actual number of
1269
+ occurrences >= frequency.
1270
+
1271
+ Returns:
1272
+ A string representing the instruction description.
1273
+ """
1274
+ if (not letter or len(letter) > 1 or ord(letter.lower()) < 97 or ord(letter.lower()) > 122):
1275
+ self._letter = random.choice(list(string.ascii_letters))
1276
+ else:
1277
+ self._letter = letter.strip()
1278
+ self._letter = self._letter.lower()
1279
+
1280
+ self._frequency = let_frequency
1281
+ if self._frequency is None or self._frequency < 0:
1282
+ self._frequency = random.randint(1, _LETTER_FREQUENCY)
1283
+
1284
+ if let_relation is None:
1285
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1286
+ elif let_relation not in _COMPARISON_RELATION:
1287
+ raise ValueError('The supported relation for comparison must be in '
1288
+ f'{_COMPARISON_RELATION}, but {let_relation} is given.')
1289
+ else:
1290
+ self._comparison_relation = let_relation
1291
+
1292
+ self._description_pattern = ('In your response, the letter {letter} should appear {let_relation}'
1293
+ ' {let_frequency} times.')
1294
+
1295
+ return self._description_pattern.format(
1296
+ letter=self._letter,
1297
+ let_frequency=self._frequency,
1298
+ let_relation=self._comparison_relation,
1299
+ )
1300
+
1301
+ def get_instruction_args(self):
1302
+ """Returns the keyword args of build description."""
1303
+ return {
1304
+ 'letter': self._letter,
1305
+ 'let_frequency': self._frequency,
1306
+ 'let_relation': self._comparison_relation,
1307
+ }
1308
+
1309
+ def get_instruction_args_keys(self):
1310
+ """Returns the args keys of `build_description`."""
1311
+ return ['letter', 'let_frequency', 'let_relation']
1312
+
1313
+ def check_following(self, value):
1314
+ """Checks that the response contains the letter at the right frequency."""
1315
+ value = value.lower()
1316
+ letters = collections.Counter(value)
1317
+
1318
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1319
+ return letters[self._letter] < self._frequency
1320
+ else:
1321
+ return letters[self._letter] >= self._frequency
1322
+
1323
+
1324
+ class CapitalLettersEnglishChecker(Instruction):
1325
+ """Checks that the response is in english and is in all capital letters."""
1326
+
1327
+ def build_description(self):
1328
+ """Build the instruction description."""
1329
+ self._description_pattern = ('Your entire response should be in English, and in all capital letters.')
1330
+ return self._description_pattern
1331
+
1332
+ def get_instruction_args(self):
1333
+ return None
1334
+
1335
+ def get_instruction_args_keys(self):
1336
+ """Returns the args keys of `build_description`."""
1337
+ return []
1338
+
1339
+ def check_following(self, value):
1340
+ """Checks that the response is in English and in all capital letters."""
1341
+ assert isinstance(value, str)
1342
+
1343
+ try:
1344
+ return value.isupper() and langdetect.detect(value) == 'en'
1345
+ except langdetect.LangDetectException as e:
1346
+ # Count as instruction is followed.
1347
+ logging.error('Unable to detect language for text %s due to %s', value, e) # refex: disable=pytotw.037
1348
+ return True
1349
+
1350
+
1351
+ class LowercaseLettersEnglishChecker(Instruction):
1352
+ """Checks that the response is in english and is in all lowercase letters."""
1353
+
1354
+ def build_description(self):
1355
+ """Build the instruction description."""
1356
+ self._description_pattern = ('Your entire response should be in English, and in all lowercase'
1357
+ ' letters. No capital letters are allowed.')
1358
+ return self._description_pattern
1359
+
1360
+ def get_instruction_args(self):
1361
+ return None
1362
+
1363
+ def get_instruction_args_keys(self):
1364
+ """Returns the args keys of `build_description`."""
1365
+ return []
1366
+
1367
+ def check_following(self, value):
1368
+ """Checks that the response is in English and in all lowercase letters."""
1369
+ assert isinstance(value, str)
1370
+
1371
+ try:
1372
+ return value.islower() and langdetect.detect(value) == 'en'
1373
+ except langdetect.LangDetectException as e:
1374
+ # Count as instruction is followed.
1375
+ logging.error('Unable to detect language for text %s due to %s', value, e) # refex: disable=pytotw.037
1376
+ return True
1377
+
1378
+
1379
+ class CommaChecker(Instruction):
1380
+ """Checks the response for no commas."""
1381
+
1382
+ def build_description(self):
1383
+ """Build the instruction description."""
1384
+ self._description_pattern = ('In your entire response, refrain from the use of any commas.')
1385
+ return self._description_pattern
1386
+
1387
+ def get_instruction_args(self):
1388
+ return None
1389
+
1390
+ def get_instruction_args_keys(self):
1391
+ """Returns the args keys of `build_description`."""
1392
+ return []
1393
+
1394
+ def check_following(self, value):
1395
+ """Checks that the response does not contain commas."""
1396
+ return not re.search(r'\,', value)
1397
+
1398
+
1399
+ class CapitalWordFrequencyChecker(Instruction):
1400
+ """Checks frequency of words with all capital letters."""
1401
+
1402
+ def build_description(
1403
+ self,
1404
+ capital_frequency=None,
1405
+ capital_relation=None,
1406
+ ):
1407
+ """Build the instruction description.
1408
+
1409
+ Args:
1410
+ capital_frequency: An integer that represents the number of words that
1411
+ should be in all capital letters.
1412
+ capital_relation: A string that is 'at least' or 'at most' that refers to
1413
+ the frequency.
1414
+
1415
+ Returns:
1416
+ A string representing the instruction description.
1417
+ """
1418
+ self._frequency = capital_frequency
1419
+ if self._frequency is None:
1420
+ self._frequency = random.randint(1, _ALL_CAPITAL_WORD_FREQUENCY)
1421
+
1422
+ self._comparison_relation = capital_relation
1423
+ if capital_relation is None:
1424
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1425
+ elif capital_relation not in _COMPARISON_RELATION:
1426
+ raise ValueError('The supported relation for comparison must be in '
1427
+ f'{_COMPARISON_RELATION}, but {capital_relation} is given.')
1428
+
1429
+ self._description_pattern = ('In your response, words with all capital letters should appear'
1430
+ ' {relation} {frequency} times.')
1431
+
1432
+ return self._description_pattern.format(frequency=self._frequency, relation=self._comparison_relation)
1433
+
1434
+ def get_instruction_args(self):
1435
+ """Returns the keyword args of build description."""
1436
+ return {
1437
+ 'capital_frequency': self._frequency,
1438
+ 'capital_relation': self._comparison_relation,
1439
+ }
1440
+
1441
+ def get_instruction_args_keys(self):
1442
+ """Returns the args keys of `build_description`."""
1443
+ return ['capital_frequency', 'capital_relation']
1444
+
1445
+ def check_following(self, value):
1446
+ """Checks the frequency of words with all capital letters."""
1447
+ # Hyphenated words will count as one word
1448
+ words = instructions_util.nltk.word_tokenize(value)
1449
+ capital_words = [word for word in words if word.isupper()]
1450
+
1451
+ capital_words = len(capital_words)
1452
+
1453
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1454
+ return capital_words < self._frequency
1455
+ else:
1456
+ return capital_words >= self._frequency
1457
+
1458
+
1459
+ class QuotationChecker(Instruction):
1460
+ """Checks response is wrapped with double quotation marks."""
1461
+
1462
+ def build_description(self):
1463
+ """Build the instruction description."""
1464
+ self._description_pattern = ('Wrap your entire response with double quotation marks.')
1465
+ return self._description_pattern
1466
+
1467
+ def get_instruction_args(self):
1468
+ """Returns the keyword args of build description."""
1469
+ return None
1470
+
1471
+ def get_instruction_args_keys(self):
1472
+ """Returns the args keys of `build_description`."""
1473
+ return []
1474
+
1475
+ def check_following(self, value):
1476
+ """Checks if the response is wrapped with double quotation marks."""
1477
+ value = value.strip()
1478
+ return len(value) > 1 and value[0] == '"' and value[-1] == '"'