evalscope 0.9.0__py3-none-any.whl → 0.10.1__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.

Potentially problematic release.


This version of evalscope might be problematic. Click here for more details.

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