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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (606) hide show
  1. evalscope/__init__.py +4 -1
  2. evalscope/api/benchmark/__init__.py +11 -0
  3. evalscope/api/benchmark/adapters/__init__.py +7 -0
  4. evalscope/api/benchmark/adapters/agent_adapter.py +8 -0
  5. evalscope/api/benchmark/adapters/default_data_adapter.py +754 -0
  6. evalscope/api/benchmark/adapters/image_edit_adapter.py +82 -0
  7. evalscope/api/benchmark/adapters/multi_choice_adapter.py +86 -0
  8. evalscope/api/benchmark/adapters/ner_adapter.py +212 -0
  9. evalscope/api/benchmark/adapters/text2image_adapter.py +157 -0
  10. evalscope/api/benchmark/adapters/vision_language_adapter.py +8 -0
  11. evalscope/api/benchmark/benchmark.py +404 -0
  12. evalscope/api/benchmark/meta.py +124 -0
  13. evalscope/api/dataset/__init__.py +2 -0
  14. evalscope/api/dataset/dataset.py +370 -0
  15. evalscope/api/dataset/loader.py +266 -0
  16. evalscope/api/dataset/utils.py +143 -0
  17. evalscope/api/evaluator/__init__.py +3 -0
  18. evalscope/api/evaluator/cache.py +382 -0
  19. evalscope/api/evaluator/evaluator.py +61 -0
  20. evalscope/api/evaluator/state.py +280 -0
  21. evalscope/api/filter/__init__.py +1 -0
  22. evalscope/api/filter/filter.py +72 -0
  23. evalscope/api/messages/__init__.py +12 -0
  24. evalscope/api/messages/chat_message.py +248 -0
  25. evalscope/api/messages/content.py +102 -0
  26. evalscope/api/messages/utils.py +35 -0
  27. evalscope/api/metric/__init__.py +2 -0
  28. evalscope/api/metric/metric.py +60 -0
  29. evalscope/api/metric/scorer.py +113 -0
  30. evalscope/api/mixin/__init__.py +2 -0
  31. evalscope/api/mixin/llm_judge_mixin.py +170 -0
  32. evalscope/api/mixin/sandbox_mixin.py +182 -0
  33. evalscope/api/model/__init__.py +12 -0
  34. evalscope/api/model/generate_config.py +161 -0
  35. evalscope/api/model/model.py +386 -0
  36. evalscope/api/model/model_output.py +285 -0
  37. evalscope/api/registry.py +182 -0
  38. evalscope/api/tool/__init__.py +3 -0
  39. evalscope/api/tool/tool_call.py +101 -0
  40. evalscope/api/tool/tool_info.py +173 -0
  41. evalscope/api/tool/utils.py +64 -0
  42. evalscope/app/__init__.py +28 -0
  43. evalscope/app/app.py +38 -0
  44. evalscope/app/arguments.py +11 -0
  45. evalscope/app/constants.py +22 -0
  46. evalscope/app/ui/__init__.py +20 -0
  47. evalscope/app/ui/app_ui.py +53 -0
  48. evalscope/app/ui/multi_model.py +353 -0
  49. evalscope/app/ui/sidebar.py +42 -0
  50. evalscope/app/ui/single_model.py +220 -0
  51. evalscope/app/ui/visualization.py +36 -0
  52. evalscope/app/utils/data_utils.py +195 -0
  53. evalscope/app/utils/env_utils.py +12 -0
  54. evalscope/app/utils/localization.py +221 -0
  55. evalscope/app/utils/text_utils.py +119 -0
  56. evalscope/app/utils/visualization.py +96 -0
  57. evalscope/arguments.py +32 -9
  58. evalscope/backend/opencompass/api_meta_template.py +2 -1
  59. evalscope/backend/opencompass/backend_manager.py +10 -7
  60. evalscope/backend/rag_eval/__init__.py +1 -1
  61. evalscope/backend/rag_eval/backend_manager.py +23 -6
  62. evalscope/backend/rag_eval/clip_benchmark/dataset_builder.py +33 -21
  63. evalscope/backend/rag_eval/clip_benchmark/task_template.py +8 -4
  64. evalscope/backend/rag_eval/cmteb/arguments.py +14 -1
  65. evalscope/backend/rag_eval/cmteb/task_template.py +19 -3
  66. evalscope/backend/rag_eval/cmteb/tasks/CustomTask.py +1 -1
  67. evalscope/backend/rag_eval/ragas/arguments.py +0 -1
  68. evalscope/backend/rag_eval/ragas/task_template.py +2 -1
  69. evalscope/backend/rag_eval/ragas/tasks/build_distribution.py +2 -1
  70. evalscope/backend/rag_eval/ragas/tasks/build_transform.py +7 -4
  71. evalscope/backend/rag_eval/ragas/tasks/testset_generation.py +9 -3
  72. evalscope/backend/rag_eval/ragas/tasks/translate_prompt.py +2 -6
  73. evalscope/backend/rag_eval/utils/embedding.py +125 -32
  74. evalscope/backend/rag_eval/utils/llm.py +16 -16
  75. evalscope/backend/vlm_eval_kit/backend_manager.py +8 -3
  76. evalscope/benchmarks/__init__.py +17 -5
  77. evalscope/benchmarks/aa_lcr/__init__.py +0 -0
  78. evalscope/benchmarks/aa_lcr/aa_lcr_adapter.py +205 -0
  79. evalscope/benchmarks/ai2d/__init__.py +0 -0
  80. evalscope/benchmarks/ai2d/ai2d_adapter.py +54 -0
  81. evalscope/benchmarks/aime/__init__.py +0 -0
  82. evalscope/benchmarks/aime/aime24_adapter.py +55 -0
  83. evalscope/benchmarks/aime/aime25_adapter.py +181 -0
  84. evalscope/benchmarks/aime/grader.py +307 -0
  85. evalscope/{metrics/math_accuracy.py → benchmarks/aime/math_normalize.py} +61 -72
  86. evalscope/benchmarks/alpaca_eval/__init__.py +0 -0
  87. evalscope/benchmarks/alpaca_eval/alpaca_eval_adapter.py +133 -0
  88. evalscope/benchmarks/amc/__init__.py +0 -0
  89. evalscope/benchmarks/amc/amc_adapter.py +51 -0
  90. evalscope/benchmarks/arc/arc_adapter.py +34 -149
  91. evalscope/benchmarks/arena_hard/__init__.py +0 -0
  92. evalscope/benchmarks/arena_hard/arena_hard_adapter.py +149 -0
  93. evalscope/benchmarks/arena_hard/utils.py +186 -0
  94. evalscope/benchmarks/bbh/bbh_adapter.py +117 -157
  95. evalscope/benchmarks/bfcl/__init__.py +0 -0
  96. evalscope/benchmarks/bfcl/v3/__init__.py +0 -0
  97. evalscope/benchmarks/bfcl/v3/bfcl_v3_adapter.py +370 -0
  98. evalscope/benchmarks/bfcl/v3/generation.py +222 -0
  99. evalscope/benchmarks/bfcl/v3/utils.py +23 -0
  100. evalscope/benchmarks/bfcl/v4/__init__.py +0 -0
  101. evalscope/benchmarks/bfcl/v4/bfcl_v4_adapter.py +229 -0
  102. evalscope/benchmarks/bfcl/v4/utils.py +410 -0
  103. evalscope/benchmarks/biomix_qa/__init__.py +0 -0
  104. evalscope/benchmarks/biomix_qa/biomix_qa_adapter.py +36 -0
  105. evalscope/benchmarks/blink/__init__.py +0 -0
  106. evalscope/benchmarks/blink/blink_adapter.py +61 -0
  107. evalscope/benchmarks/ceval/ceval_adapter.py +93 -174
  108. evalscope/benchmarks/chartqa/__init__.py +0 -0
  109. evalscope/benchmarks/chartqa/chartqa_adapter.py +80 -0
  110. evalscope/benchmarks/chartqa/utils.py +38 -0
  111. evalscope/benchmarks/chinese_simple_qa/__init__.py +0 -0
  112. evalscope/benchmarks/chinese_simple_qa/csimple_qa_adapter.py +170 -0
  113. evalscope/benchmarks/cmmlu/cmmlu_adapter.py +34 -140
  114. evalscope/benchmarks/coin_flip/__init__.py +0 -0
  115. evalscope/benchmarks/coin_flip/coin_flip_adapter.py +128 -0
  116. evalscope/benchmarks/commonsense_qa/__init__.py +0 -0
  117. evalscope/benchmarks/commonsense_qa/commonsense_qa_adapter.py +32 -0
  118. evalscope/benchmarks/competition_math/competition_math_adapter.py +64 -112
  119. evalscope/benchmarks/data_collection/__init__.py +0 -0
  120. evalscope/benchmarks/data_collection/data_collection_adapter.py +215 -0
  121. evalscope/benchmarks/docmath/__init__.py +0 -0
  122. evalscope/benchmarks/docmath/docmath_adapter.py +143 -0
  123. evalscope/benchmarks/docmath/utils.py +219 -0
  124. evalscope/benchmarks/docvqa/__init__.py +0 -0
  125. evalscope/benchmarks/docvqa/docvqa_adapter.py +67 -0
  126. evalscope/benchmarks/drivelology/__init__.py +0 -0
  127. evalscope/benchmarks/drivelology/drivelology_binary_adapter.py +170 -0
  128. evalscope/benchmarks/drivelology/drivelology_multilabel_adapter.py +254 -0
  129. evalscope/benchmarks/drivelology/drivelology_selection_adapter.py +49 -0
  130. evalscope/benchmarks/drivelology/drivelology_writing_adapter.py +218 -0
  131. evalscope/benchmarks/drop/__init__.py +0 -0
  132. evalscope/benchmarks/drop/drop_adapter.py +155 -0
  133. evalscope/benchmarks/drop/utils.py +156 -0
  134. evalscope/benchmarks/frames/__init__.py +0 -0
  135. evalscope/benchmarks/frames/frames_adapter.py +175 -0
  136. evalscope/benchmarks/frames/utils.py +37 -0
  137. evalscope/benchmarks/general_arena/__init__.py +0 -0
  138. evalscope/benchmarks/general_arena/general_arena_adapter.py +454 -0
  139. evalscope/benchmarks/general_arena/utils.py +223 -0
  140. evalscope/benchmarks/general_mcq/__init__.py +0 -0
  141. evalscope/benchmarks/general_mcq/general_mcq_adapter.py +58 -0
  142. evalscope/benchmarks/general_qa/general_qa_adapter.py +75 -107
  143. evalscope/benchmarks/gpqa/__init__.py +0 -0
  144. evalscope/benchmarks/gpqa/gpqa_adapter.py +90 -0
  145. evalscope/benchmarks/gpqa/prompt.py +88 -0
  146. evalscope/benchmarks/gsm8k/gsm8k_adapter.py +77 -144
  147. evalscope/benchmarks/hallusion_bench/__init__.py +0 -0
  148. evalscope/benchmarks/hallusion_bench/hallusion_bench_adapter.py +159 -0
  149. evalscope/benchmarks/halu_eval/__init__.py +0 -0
  150. evalscope/benchmarks/halu_eval/halu_eval_adapter.py +128 -0
  151. evalscope/benchmarks/halu_eval/halu_eval_instructions.py +84 -0
  152. evalscope/benchmarks/healthbench/__init__.py +0 -0
  153. evalscope/benchmarks/healthbench/healthbench_adapter.py +282 -0
  154. evalscope/benchmarks/healthbench/utils.py +102 -0
  155. evalscope/benchmarks/hellaswag/hellaswag_adapter.py +36 -134
  156. evalscope/benchmarks/hle/__init__.py +0 -0
  157. evalscope/benchmarks/hle/hle_adapter.py +153 -0
  158. evalscope/benchmarks/humaneval/humaneval_adapter.py +80 -88
  159. evalscope/benchmarks/humaneval/utils.py +235 -0
  160. evalscope/benchmarks/ifeval/ifeval_adapter.py +71 -45
  161. evalscope/benchmarks/ifeval/instructions.py +112 -68
  162. evalscope/benchmarks/ifeval/instructions_registry.py +1 -1
  163. evalscope/benchmarks/ifeval/instructions_util.py +2 -3
  164. evalscope/benchmarks/ifeval/utils.py +6 -7
  165. evalscope/benchmarks/image_edit/__init__.py +0 -0
  166. evalscope/benchmarks/image_edit/gedit/__init__.py +0 -0
  167. evalscope/benchmarks/image_edit/gedit/gedit_adapter.py +138 -0
  168. evalscope/benchmarks/image_edit/gedit/utils.py +372 -0
  169. evalscope/benchmarks/image_edit/gedit/vie_prompts.py +406 -0
  170. evalscope/benchmarks/infovqa/__init__.py +0 -0
  171. evalscope/benchmarks/infovqa/infovqa_adapter.py +66 -0
  172. evalscope/benchmarks/iquiz/iquiz_adapter.py +30 -58
  173. evalscope/benchmarks/live_code_bench/__init__.py +0 -0
  174. evalscope/benchmarks/live_code_bench/evaluate_utils.py +195 -0
  175. evalscope/benchmarks/live_code_bench/extract_utils.py +70 -0
  176. evalscope/benchmarks/live_code_bench/live_code_bench_adapter.py +150 -0
  177. evalscope/benchmarks/live_code_bench/load_utils.py +63 -0
  178. evalscope/benchmarks/live_code_bench/pass_k_utils.py +56 -0
  179. evalscope/benchmarks/live_code_bench/prompts.py +207 -0
  180. evalscope/benchmarks/live_code_bench/sandbox_evaluate_utils.py +220 -0
  181. evalscope/benchmarks/live_code_bench/testing_util.py +544 -0
  182. evalscope/benchmarks/logi_qa/__int__.py +0 -0
  183. evalscope/benchmarks/logi_qa/logi_qa_adapter.py +41 -0
  184. evalscope/benchmarks/maritime_bench/__init__.py +0 -0
  185. evalscope/benchmarks/maritime_bench/maritime_bench_adapter.py +56 -0
  186. evalscope/benchmarks/math_500/__init__.py +0 -0
  187. evalscope/benchmarks/math_500/math_500_adapter.py +55 -0
  188. evalscope/benchmarks/math_qa/__init__.py +0 -0
  189. evalscope/benchmarks/math_qa/math_qa_adapter.py +35 -0
  190. evalscope/benchmarks/math_verse/__init__.py +0 -0
  191. evalscope/benchmarks/math_verse/math_verse_adapter.py +105 -0
  192. evalscope/benchmarks/math_vision/__init__.py +0 -0
  193. evalscope/benchmarks/math_vision/math_vision_adapter.py +116 -0
  194. evalscope/benchmarks/math_vista/__init__.py +0 -0
  195. evalscope/benchmarks/math_vista/math_vista_adapter.py +114 -0
  196. evalscope/benchmarks/med_mcqa/__init__.py +0 -0
  197. evalscope/benchmarks/med_mcqa/med_mcqa_adapter.py +32 -0
  198. evalscope/benchmarks/minerva_math/__init__.py +0 -0
  199. evalscope/benchmarks/minerva_math/minerva_math_adapter.py +53 -0
  200. evalscope/benchmarks/mm_bench/__init__.py +0 -0
  201. evalscope/benchmarks/mm_bench/mm_bench_adapter.py +99 -0
  202. evalscope/benchmarks/mm_star/__init__.py +0 -0
  203. evalscope/benchmarks/mm_star/mm_star_adapter.py +73 -0
  204. evalscope/benchmarks/mmlu/mmlu_adapter.py +32 -210
  205. evalscope/benchmarks/mmlu_pro/mmlu_pro_adapter.py +87 -103
  206. evalscope/benchmarks/mmlu_redux/__init__.py +0 -0
  207. evalscope/benchmarks/mmlu_redux/mmlu_redux_adapter.py +139 -0
  208. evalscope/benchmarks/mmmu/__init__.py +0 -0
  209. evalscope/benchmarks/mmmu/mmmu_adapter.py +159 -0
  210. evalscope/benchmarks/mmmu_pro/__init__.py +0 -0
  211. evalscope/benchmarks/mmmu_pro/mmmu_pro_adapter.py +124 -0
  212. evalscope/benchmarks/mri_mcqa/__init__.py +0 -0
  213. evalscope/benchmarks/mri_mcqa/mri_mcqa_adapter.py +34 -0
  214. evalscope/benchmarks/multi_if/__init__.py +0 -0
  215. evalscope/benchmarks/multi_if/ifeval.py +3354 -0
  216. evalscope/benchmarks/multi_if/metrics.py +120 -0
  217. evalscope/benchmarks/multi_if/multi_if_adapter.py +161 -0
  218. evalscope/benchmarks/music_trivia/__init__.py +0 -0
  219. evalscope/benchmarks/music_trivia/music_trivia_adapter.py +36 -0
  220. evalscope/benchmarks/musr/__init__.py +0 -0
  221. evalscope/benchmarks/musr/musr_adapter.py +43 -0
  222. evalscope/benchmarks/needle_haystack/__init__.py +0 -0
  223. evalscope/benchmarks/needle_haystack/needle_haystack_adapter.py +389 -0
  224. evalscope/benchmarks/needle_haystack/utils.py +79 -0
  225. evalscope/benchmarks/ner/__init__.py +0 -0
  226. evalscope/benchmarks/ner/broad_twitter_corpus_adapter.py +52 -0
  227. evalscope/benchmarks/ner/conll2003_adapter.py +48 -0
  228. evalscope/benchmarks/ner/copious_adapter.py +85 -0
  229. evalscope/benchmarks/ner/cross_ner_adapter.py +120 -0
  230. evalscope/benchmarks/ner/cross_ner_entities/__init__.py +0 -0
  231. evalscope/benchmarks/ner/cross_ner_entities/ai.py +54 -0
  232. evalscope/benchmarks/ner/cross_ner_entities/literature.py +36 -0
  233. evalscope/benchmarks/ner/cross_ner_entities/music.py +39 -0
  234. evalscope/benchmarks/ner/cross_ner_entities/politics.py +37 -0
  235. evalscope/benchmarks/ner/cross_ner_entities/science.py +58 -0
  236. evalscope/benchmarks/ner/genia_ner_adapter.py +66 -0
  237. evalscope/benchmarks/ner/harvey_ner_adapter.py +58 -0
  238. evalscope/benchmarks/ner/mit_movie_trivia_adapter.py +74 -0
  239. evalscope/benchmarks/ner/mit_restaurant_adapter.py +66 -0
  240. evalscope/benchmarks/ner/ontonotes5_adapter.py +87 -0
  241. evalscope/benchmarks/ner/wnut2017_adapter.py +61 -0
  242. evalscope/benchmarks/ocr_bench/__init__.py +0 -0
  243. evalscope/benchmarks/ocr_bench/ocr_bench/__init__.py +0 -0
  244. evalscope/benchmarks/ocr_bench/ocr_bench/ocr_bench_adapter.py +101 -0
  245. evalscope/benchmarks/ocr_bench/ocr_bench_v2/IoUscore_metric.py +87 -0
  246. evalscope/benchmarks/ocr_bench/ocr_bench_v2/TEDS_metric.py +963 -0
  247. evalscope/benchmarks/ocr_bench/ocr_bench_v2/__init__.py +0 -0
  248. evalscope/benchmarks/ocr_bench/ocr_bench_v2/ocr_bench_v2_adapter.py +161 -0
  249. evalscope/benchmarks/ocr_bench/ocr_bench_v2/page_ocr_metric.py +50 -0
  250. evalscope/benchmarks/ocr_bench/ocr_bench_v2/parallel.py +46 -0
  251. evalscope/benchmarks/ocr_bench/ocr_bench_v2/spotting_eval/__init__.py +0 -0
  252. evalscope/benchmarks/ocr_bench/ocr_bench_v2/spotting_eval/readme.txt +26 -0
  253. evalscope/benchmarks/ocr_bench/ocr_bench_v2/spotting_eval/rrc_evaluation_funcs_1_1.py +537 -0
  254. evalscope/benchmarks/ocr_bench/ocr_bench_v2/spotting_eval/script.py +481 -0
  255. evalscope/benchmarks/ocr_bench/ocr_bench_v2/spotting_metric.py +179 -0
  256. evalscope/benchmarks/ocr_bench/ocr_bench_v2/utils.py +433 -0
  257. evalscope/benchmarks/ocr_bench/ocr_bench_v2/vqa_metric.py +254 -0
  258. evalscope/benchmarks/olympiad_bench/__init__.py +0 -0
  259. evalscope/benchmarks/olympiad_bench/olympiad_bench_adapter.py +163 -0
  260. evalscope/benchmarks/olympiad_bench/utils.py +565 -0
  261. evalscope/benchmarks/omni_bench/__init__.py +0 -0
  262. evalscope/benchmarks/omni_bench/omni_bench_adapter.py +86 -0
  263. evalscope/benchmarks/omnidoc_bench/__init__.py +0 -0
  264. evalscope/benchmarks/omnidoc_bench/end2end_eval.py +349 -0
  265. evalscope/benchmarks/omnidoc_bench/metrics.py +547 -0
  266. evalscope/benchmarks/omnidoc_bench/omnidoc_bench_adapter.py +135 -0
  267. evalscope/benchmarks/omnidoc_bench/utils.py +1937 -0
  268. evalscope/benchmarks/piqa/__init__.py +0 -0
  269. evalscope/benchmarks/piqa/piqa_adapter.py +32 -0
  270. evalscope/benchmarks/poly_math/__init__.py +0 -0
  271. evalscope/benchmarks/poly_math/poly_math_adapter.py +132 -0
  272. evalscope/benchmarks/poly_math/utils/instruction.py +105 -0
  273. evalscope/benchmarks/pope/__init__.py +0 -0
  274. evalscope/benchmarks/pope/pope_adapter.py +112 -0
  275. evalscope/benchmarks/process_bench/__init__.py +0 -0
  276. evalscope/benchmarks/process_bench/process_bench_adapter.py +171 -0
  277. evalscope/benchmarks/pumed_qa/__init__.py +0 -0
  278. evalscope/benchmarks/pumed_qa/pubmed_qa_adapter.py +175 -0
  279. evalscope/benchmarks/qasc/__init__.py +0 -0
  280. evalscope/benchmarks/qasc/qasc_adapter.py +35 -0
  281. evalscope/benchmarks/race/race_adapter.py +33 -120
  282. evalscope/benchmarks/real_world_qa/__init__.py +0 -0
  283. evalscope/benchmarks/real_world_qa/real_world_qa_adapter.py +64 -0
  284. evalscope/benchmarks/sciq/__init__.py +0 -0
  285. evalscope/benchmarks/sciq/sciq_adapter.py +36 -0
  286. evalscope/benchmarks/seed_bench_2_plus/__init__.py +0 -0
  287. evalscope/benchmarks/seed_bench_2_plus/seed_bench_2_plus_adapter.py +72 -0
  288. evalscope/benchmarks/simple_qa/__init__.py +0 -0
  289. evalscope/benchmarks/simple_qa/simple_qa_adapter.py +169 -0
  290. evalscope/benchmarks/simple_vqa/__init__.py +0 -0
  291. evalscope/benchmarks/simple_vqa/simple_vqa_adapter.py +169 -0
  292. evalscope/benchmarks/siqa/__init__.py +0 -0
  293. evalscope/benchmarks/siqa/siqa_adapter.py +39 -0
  294. evalscope/benchmarks/super_gpqa/__init__.py +0 -0
  295. evalscope/benchmarks/super_gpqa/prompt.py +88 -0
  296. evalscope/benchmarks/super_gpqa/super_gpqa_adapter.py +165 -0
  297. evalscope/benchmarks/super_gpqa/utils.py +86 -0
  298. evalscope/benchmarks/tau_bench/__init__.py +0 -0
  299. evalscope/benchmarks/tau_bench/tau2_bench/__init__.py +0 -0
  300. evalscope/benchmarks/tau_bench/tau2_bench/generation.py +158 -0
  301. evalscope/benchmarks/tau_bench/tau2_bench/tau2_bench_adapter.py +146 -0
  302. evalscope/benchmarks/tau_bench/tau_bench/__init__.py +0 -0
  303. evalscope/benchmarks/tau_bench/tau_bench/generation.py +147 -0
  304. evalscope/benchmarks/tau_bench/tau_bench/tau_bench_adapter.py +168 -0
  305. evalscope/benchmarks/text2image/__init__.py +0 -0
  306. evalscope/benchmarks/text2image/evalmuse_adapter.py +78 -0
  307. evalscope/benchmarks/text2image/genai_bench_adapter.py +53 -0
  308. evalscope/benchmarks/text2image/general_t2i_adapter.py +42 -0
  309. evalscope/benchmarks/text2image/hpdv2_adapter.py +52 -0
  310. evalscope/benchmarks/text2image/tifa_adapter.py +27 -0
  311. evalscope/benchmarks/tool_bench/__init__.py +0 -0
  312. evalscope/benchmarks/tool_bench/tool_bench_adapter.py +102 -0
  313. evalscope/benchmarks/tool_bench/utils.py +203 -0
  314. evalscope/benchmarks/trivia_qa/trivia_qa_adapter.py +56 -118
  315. evalscope/benchmarks/truthful_qa/truthful_qa_adapter.py +70 -270
  316. evalscope/benchmarks/visu_logic/__init__.py +0 -0
  317. evalscope/benchmarks/visu_logic/visu_logic_adapter.py +75 -0
  318. evalscope/benchmarks/winogrande/__init__.py +0 -0
  319. evalscope/benchmarks/winogrande/winogrande_adapter.py +34 -0
  320. evalscope/benchmarks/wmt/__init__.py +0 -0
  321. evalscope/benchmarks/wmt/wmt24_adapter.py +294 -0
  322. evalscope/benchmarks/zerobench/__init__.py +0 -0
  323. evalscope/benchmarks/zerobench/zerobench_adapter.py +64 -0
  324. evalscope/cli/cli.py +2 -0
  325. evalscope/cli/start_app.py +12 -2
  326. evalscope/cli/start_eval.py +4 -3
  327. evalscope/cli/start_perf.py +10 -2
  328. evalscope/cli/start_server.py +6 -3
  329. evalscope/collections/__init__.py +27 -3
  330. evalscope/collections/sampler.py +12 -11
  331. evalscope/collections/schema.py +13 -12
  332. evalscope/config.py +218 -147
  333. evalscope/constants.py +78 -82
  334. evalscope/evaluator/__init__.py +1 -1
  335. evalscope/evaluator/evaluator.py +334 -318
  336. evalscope/filters/__init__.py +2 -0
  337. evalscope/filters/extraction.py +126 -0
  338. evalscope/filters/selection.py +57 -0
  339. evalscope/metrics/__init__.py +59 -3
  340. evalscope/metrics/bert_score/__init__.py +0 -0
  341. evalscope/metrics/bert_score/scorer.py +338 -0
  342. evalscope/metrics/bert_score/utils.py +697 -0
  343. evalscope/metrics/bundled_rouge_score/rouge_scorer.py +20 -15
  344. evalscope/metrics/llm_judge.py +211 -0
  345. evalscope/metrics/math_parser.py +545 -0
  346. evalscope/metrics/metric.py +611 -0
  347. evalscope/metrics/metrics.py +112 -23
  348. evalscope/metrics/rouge_metric.py +11 -13
  349. evalscope/metrics/t2v_metrics/__init__.py +0 -0
  350. evalscope/metrics/t2v_metrics/clipscore.py +14 -0
  351. evalscope/metrics/t2v_metrics/constants.py +12 -0
  352. evalscope/metrics/t2v_metrics/itmscore.py +14 -0
  353. evalscope/metrics/t2v_metrics/models/__init__.py +0 -0
  354. evalscope/metrics/t2v_metrics/models/clipscore_models/__init__.py +30 -0
  355. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/__init__.py +0 -0
  356. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/base_model.py +6 -0
  357. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/clip_model.py +134 -0
  358. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/cross_modeling.py +282 -0
  359. evalscope/metrics/t2v_metrics/models/clipscore_models/clip_model.py +115 -0
  360. evalscope/metrics/t2v_metrics/models/clipscore_models/hpsv2_model.py +87 -0
  361. evalscope/metrics/t2v_metrics/models/clipscore_models/mps_model.py +86 -0
  362. evalscope/metrics/t2v_metrics/models/clipscore_models/pickscore_model.py +62 -0
  363. evalscope/metrics/t2v_metrics/models/itmscore_models/__init__.py +26 -0
  364. evalscope/metrics/t2v_metrics/models/itmscore_models/blip2_itm_model.py +85 -0
  365. evalscope/metrics/t2v_metrics/models/itmscore_models/fga_blip2_model.py +99 -0
  366. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward/ImageReward.py +176 -0
  367. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward/__init__.py +0 -0
  368. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward/blip_pretrain.py +82 -0
  369. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward_model.py +74 -0
  370. evalscope/metrics/t2v_metrics/models/model.py +45 -0
  371. evalscope/metrics/t2v_metrics/models/utils.py +25 -0
  372. evalscope/metrics/t2v_metrics/models/vqascore_models/__init__.py +22 -0
  373. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/__init__.py +0 -0
  374. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/__init__.py +1 -0
  375. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/language_model/clip_t5.py +306 -0
  376. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/multimodal_encoder/builder.py +12 -0
  377. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/multimodal_encoder/clip_encoder.py +84 -0
  378. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/multimodal_projector/builder.py +50 -0
  379. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5_model.py +223 -0
  380. evalscope/metrics/t2v_metrics/models/vqascore_models/gpt4v_model.py +153 -0
  381. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/__init__.py +26 -0
  382. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/config.py +465 -0
  383. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/dist_utils.py +141 -0
  384. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/gradcam.py +24 -0
  385. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/logger.py +190 -0
  386. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/optims.py +100 -0
  387. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/registry.py +313 -0
  388. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/utils.py +416 -0
  389. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/vqa_tools/__init__.py +8 -0
  390. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/vqa_tools/vqa.py +192 -0
  391. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/vqa_tools/vqa_eval.py +320 -0
  392. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/default.yaml +10 -0
  393. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_caption_flant5xl.yaml +42 -0
  394. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_caption_opt2.7b.yaml +42 -0
  395. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_caption_opt6.7b.yaml +42 -0
  396. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_coco.yaml +36 -0
  397. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_flant5xl.yaml +43 -0
  398. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_flant5xxl.yaml +43 -0
  399. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_vicuna13b.yaml +43 -0
  400. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml +43 -0
  401. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain.yaml +36 -0
  402. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl.yaml +42 -0
  403. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl_iter_80k_total_100k_no_prefix.yaml +42 -0
  404. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl_iter_80k_total_100k_prefix.yaml +42 -0
  405. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl_vitL.yaml +43 -0
  406. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xxl.yaml +42 -0
  407. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_opt2.7b.yaml +42 -0
  408. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_opt6.7b.yaml +42 -0
  409. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_vitL.yaml +37 -0
  410. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_vicuna13b.yaml +43 -0
  411. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_vicuna7b.yaml +43 -0
  412. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/med_config.json +21 -0
  413. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/med_config_albef.json +22 -0
  414. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/med_large_config.json +21 -0
  415. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/__init__.py +212 -0
  416. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/base_model.py +231 -0
  417. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/Qformer.py +1111 -0
  418. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/__init__.py +0 -0
  419. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2.py +211 -0
  420. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_image_text_matching.py +109 -0
  421. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_qformer.py +457 -0
  422. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_t5.py +370 -0
  423. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_t5_instruct.py +765 -0
  424. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/fga_blip2.py +274 -0
  425. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/modeling_llama.py +896 -0
  426. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/modeling_t5.py +1876 -0
  427. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/__init__.py +83 -0
  428. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip.py +58 -0
  429. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_caption.py +212 -0
  430. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_classification.py +164 -0
  431. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_feature_extractor.py +202 -0
  432. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_image_text_matching.py +187 -0
  433. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_nlvr.py +179 -0
  434. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_outputs.py +115 -0
  435. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_pretrain.py +371 -0
  436. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_vqa.py +348 -0
  437. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/nlvr_encoder.py +870 -0
  438. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/clip_vit.py +273 -0
  439. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/eva_vit.py +514 -0
  440. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/med.py +1291 -0
  441. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/vit.py +476 -0
  442. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/__init__.py +35 -0
  443. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/base_processor.py +27 -0
  444. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/blip_processors.py +233 -0
  445. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/randaugment.py +393 -0
  446. evalscope/metrics/t2v_metrics/models/vqascore_models/mm_utils.py +129 -0
  447. evalscope/metrics/t2v_metrics/models/vqascore_models/vqa_model.py +18 -0
  448. evalscope/metrics/t2v_metrics/score.py +78 -0
  449. evalscope/metrics/t2v_metrics/vqascore.py +14 -0
  450. evalscope/models/__init__.py +23 -13
  451. evalscope/models/image_edit_model.py +125 -0
  452. evalscope/models/mockllm.py +65 -0
  453. evalscope/models/model_apis.py +69 -0
  454. evalscope/models/modelscope.py +455 -0
  455. evalscope/models/openai_compatible.py +144 -0
  456. evalscope/models/text2image_model.py +124 -0
  457. evalscope/models/utils/openai.py +708 -0
  458. evalscope/perf/__init__.py +0 -1
  459. evalscope/perf/arguments.py +103 -69
  460. evalscope/perf/benchmark.py +114 -163
  461. evalscope/perf/http_client.py +59 -89
  462. evalscope/perf/main.py +91 -18
  463. evalscope/perf/plugin/__init__.py +3 -2
  464. evalscope/perf/plugin/api/__init__.py +4 -3
  465. evalscope/perf/plugin/api/base.py +27 -7
  466. evalscope/perf/plugin/api/custom_api.py +170 -57
  467. evalscope/perf/plugin/api/dashscope_api.py +4 -10
  468. evalscope/perf/plugin/api/default_api.py +214 -0
  469. evalscope/perf/plugin/api/openai_api.py +120 -41
  470. evalscope/perf/plugin/datasets/__init__.py +10 -6
  471. evalscope/perf/plugin/datasets/base.py +43 -1
  472. evalscope/perf/plugin/datasets/custom.py +22 -3
  473. evalscope/perf/plugin/datasets/flickr8k.py +5 -27
  474. evalscope/perf/plugin/datasets/kontext_bench.py +28 -0
  475. evalscope/perf/plugin/datasets/line_by_line.py +7 -3
  476. evalscope/perf/plugin/datasets/longalpaca.py +7 -3
  477. evalscope/perf/plugin/datasets/openqa.py +13 -14
  478. evalscope/perf/plugin/datasets/random_dataset.py +67 -0
  479. evalscope/perf/plugin/datasets/random_vl_dataset.py +80 -0
  480. evalscope/perf/plugin/datasets/speed_benchmark.py +11 -0
  481. evalscope/perf/plugin/registry.py +36 -16
  482. evalscope/perf/utils/analysis_result.py +24 -23
  483. evalscope/perf/utils/benchmark_util.py +95 -55
  484. evalscope/perf/utils/db_util.py +115 -78
  485. evalscope/perf/utils/local_server.py +12 -47
  486. evalscope/perf/utils/log_utils.py +63 -0
  487. evalscope/perf/utils/rich_display.py +192 -0
  488. evalscope/report/__init__.py +46 -3
  489. evalscope/report/combinator.py +143 -32
  490. evalscope/report/generator.py +74 -34
  491. evalscope/report/report.py +238 -0
  492. evalscope/run.py +71 -46
  493. evalscope/summarizer.py +5 -5
  494. evalscope/third_party/longbench_write/infer.py +1 -1
  495. evalscope/third_party/thinkbench/__init__.py +3 -0
  496. evalscope/third_party/thinkbench/eval.py +441 -0
  497. evalscope/third_party/thinkbench/infer.py +130 -0
  498. evalscope/third_party/thinkbench/resources/critique_template.txt +17 -0
  499. evalscope/third_party/thinkbench/resources/reformat_template.txt +31 -0
  500. evalscope/third_party/thinkbench/tools/__init__.py +0 -0
  501. evalscope/third_party/thinkbench/tools/llm.py +48 -0
  502. evalscope/third_party/thinkbench/tools/utils.py +13 -0
  503. evalscope/third_party/toolbench_static/llm/swift_infer.py +46 -20
  504. evalscope/third_party/toolbench_static/toolbench_static.py +2 -1
  505. evalscope/utils/__init__.py +82 -2
  506. evalscope/utils/argument_utils.py +64 -0
  507. evalscope/utils/chat_service.py +8 -6
  508. evalscope/utils/deprecation_utils.py +53 -0
  509. evalscope/utils/function_utils.py +266 -0
  510. evalscope/utils/import_utils.py +154 -0
  511. evalscope/utils/io_utils.py +336 -8
  512. evalscope/utils/json_schema.py +231 -0
  513. evalscope/utils/logger.py +121 -31
  514. evalscope/utils/model_utils.py +57 -1
  515. evalscope/utils/multi_choices.py +303 -0
  516. evalscope/utils/ner.py +377 -0
  517. evalscope/utils/url_utils.py +65 -0
  518. evalscope/version.py +2 -2
  519. evalscope-1.2.0.dist-info/METADATA +553 -0
  520. evalscope-1.2.0.dist-info/RECORD +628 -0
  521. {evalscope-0.10.0.dist-info → evalscope-1.2.0.dist-info}/WHEEL +1 -1
  522. {evalscope-0.10.0.dist-info → evalscope-1.2.0.dist-info}/top_level.txt +0 -1
  523. evalscope/backend/vlm_eval_kit/custom_dataset.py +0 -46
  524. evalscope/benchmarks/arc/ai2_arc.py +0 -151
  525. evalscope/benchmarks/benchmark.py +0 -76
  526. evalscope/benchmarks/ceval/ceval_exam.py +0 -146
  527. evalscope/benchmarks/ceval/samples.jsonl +0 -1
  528. evalscope/benchmarks/cmmlu/cmmlu.py +0 -161
  529. evalscope/benchmarks/cmmlu/samples.jsonl +0 -5
  530. evalscope/benchmarks/competition_math/competition_math.py +0 -79
  531. evalscope/benchmarks/data_adapter.py +0 -291
  532. evalscope/benchmarks/gsm8k/gsm8k.py +0 -121
  533. evalscope/benchmarks/hellaswag/hellaswag.py +0 -112
  534. evalscope/benchmarks/humaneval/humaneval.py +0 -79
  535. evalscope/benchmarks/mmlu/mmlu.py +0 -160
  536. evalscope/benchmarks/mmlu/samples.jsonl +0 -5
  537. evalscope/benchmarks/race/race.py +0 -104
  538. evalscope/benchmarks/race/samples.jsonl +0 -5
  539. evalscope/benchmarks/trivia_qa/trivia_qa.py +0 -89
  540. evalscope/benchmarks/truthful_qa/truthful_qa.py +0 -163
  541. evalscope/collections/evaluator.py +0 -198
  542. evalscope/evaluator/rating_eval.py +0 -157
  543. evalscope/evaluator/reviewer/__init__.py +0 -1
  544. evalscope/evaluator/reviewer/auto_reviewer.py +0 -391
  545. evalscope/metrics/code_metric.py +0 -98
  546. evalscope/metrics/named_metrics.py +0 -17
  547. evalscope/metrics/resources/gpt2-zhcn3-v4.bpe +0 -58485
  548. evalscope/metrics/resources/gpt2-zhcn3-v4.json +0 -1
  549. evalscope/models/base_adapter.py +0 -52
  550. evalscope/models/chat_adapter.py +0 -138
  551. evalscope/models/choice_adapter.py +0 -211
  552. evalscope/models/custom/__init__.py +0 -3
  553. evalscope/models/custom/custom_model.py +0 -53
  554. evalscope/models/custom/dummy_model.py +0 -63
  555. evalscope/models/custom_adapter.py +0 -67
  556. evalscope/models/local_model.py +0 -74
  557. evalscope/models/model.py +0 -229
  558. evalscope/models/server_adapter.py +0 -111
  559. evalscope/registry/__init__.py +0 -1
  560. evalscope/registry/config/cfg_arena.yaml +0 -77
  561. evalscope/registry/config/cfg_arena_zhihu.yaml +0 -63
  562. evalscope/registry/config/cfg_pairwise_baseline.yaml +0 -83
  563. evalscope/registry/config/cfg_single.yaml +0 -78
  564. evalscope/registry/data/prompt_template/lmsys_v2.jsonl +0 -8
  565. evalscope/registry/data/prompt_template/prompt_templates.jsonl +0 -8
  566. evalscope/registry/data/qa_browser/battle.jsonl +0 -634
  567. evalscope/registry/data/qa_browser/category_mapping.yaml +0 -10
  568. evalscope/registry/data/question.jsonl +0 -80
  569. evalscope/registry/tasks/arc.yaml +0 -28
  570. evalscope/registry/tasks/bbh.yaml +0 -26
  571. evalscope/registry/tasks/bbh_mini.yaml +0 -26
  572. evalscope/registry/tasks/ceval.yaml +0 -27
  573. evalscope/registry/tasks/ceval_mini.yaml +0 -26
  574. evalscope/registry/tasks/cmmlu.yaml +0 -27
  575. evalscope/registry/tasks/eval_qwen-7b-chat_v100.yaml +0 -28
  576. evalscope/registry/tasks/general_qa.yaml +0 -27
  577. evalscope/registry/tasks/gsm8k.yaml +0 -29
  578. evalscope/registry/tasks/mmlu.yaml +0 -29
  579. evalscope/registry/tasks/mmlu_mini.yaml +0 -27
  580. evalscope/report/app.py +0 -506
  581. evalscope/report/utils.py +0 -133
  582. evalscope/run_arena.py +0 -202
  583. evalscope/utils/arena_utils.py +0 -217
  584. evalscope/utils/completion_parsers.py +0 -82
  585. evalscope/utils/utils.py +0 -301
  586. evalscope-0.10.0.dist-info/METADATA +0 -565
  587. evalscope-0.10.0.dist-info/RECORD +0 -286
  588. tests/__init__.py +0 -1
  589. tests/cli/__init__.py +0 -1
  590. tests/cli/test_collection.py +0 -57
  591. tests/cli/test_run.py +0 -165
  592. tests/perf/__init__.py +0 -1
  593. tests/perf/test_perf.py +0 -101
  594. tests/rag/test_clip_benchmark.py +0 -85
  595. tests/rag/test_mteb.py +0 -138
  596. tests/rag/test_ragas.py +0 -120
  597. tests/swift/__init__.py +0 -1
  598. tests/swift/test_run_swift_eval.py +0 -145
  599. tests/swift/test_run_swift_vlm_eval.py +0 -127
  600. tests/swift/test_run_swift_vlm_jugde_eval.py +0 -156
  601. tests/test_run_all.py +0 -12
  602. tests/vlm/__init__.py +0 -1
  603. tests/vlm/test_vlmeval.py +0 -60
  604. {tests/rag → evalscope/api}/__init__.py +0 -0
  605. {evalscope-0.10.0.dist-info → evalscope-1.2.0.dist-info}/entry_points.txt +0 -0
  606. {evalscope-0.10.0.dist-info → evalscope-1.2.0.dist-info/licenses}/LICENSE +0 -0
@@ -0,0 +1,3354 @@
1
+ # flake8: noqa
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import collections
17
+ import functools
18
+ import json
19
+ import random
20
+ import re
21
+ import string
22
+ from types import MappingProxyType
23
+ from typing import Dict, Iterable, Optional, Sequence, Union
24
+
25
+ from evalscope.utils import get_logger
26
+
27
+ try:
28
+ import langdetect
29
+ except ImportError:
30
+ langdetect = None
31
+ try:
32
+ import emoji
33
+ except ImportError:
34
+ emoji = None
35
+ import nltk
36
+
37
+ logger = get_logger()
38
+
39
+ WORD_LIST = [
40
+ 'western',
41
+ 'sentence',
42
+ 'signal',
43
+ 'dump',
44
+ 'spot',
45
+ 'opposite',
46
+ 'bottom',
47
+ 'potato',
48
+ 'administration',
49
+ 'working',
50
+ 'welcome',
51
+ 'morning',
52
+ 'good',
53
+ 'agency',
54
+ 'primary',
55
+ 'wish',
56
+ 'responsibility',
57
+ 'press',
58
+ 'problem',
59
+ 'president',
60
+ 'steal',
61
+ 'brush',
62
+ 'read',
63
+ 'type',
64
+ 'beat',
65
+ 'trainer',
66
+ 'growth',
67
+ 'lock',
68
+ 'bone',
69
+ 'case',
70
+ 'equal',
71
+ 'comfortable',
72
+ 'region',
73
+ 'replacement',
74
+ 'performance',
75
+ 'mate',
76
+ 'walk',
77
+ 'medicine',
78
+ 'film',
79
+ 'thing',
80
+ 'rock',
81
+ 'tap',
82
+ 'total',
83
+ 'competition',
84
+ 'ease',
85
+ 'south',
86
+ 'establishment',
87
+ 'gather',
88
+ 'parking',
89
+ 'world',
90
+ 'plenty',
91
+ 'breath',
92
+ 'claim',
93
+ 'alcohol',
94
+ 'trade',
95
+ 'dear',
96
+ 'highlight',
97
+ 'street',
98
+ 'matter',
99
+ 'decision',
100
+ 'mess',
101
+ 'agreement',
102
+ 'studio',
103
+ 'coach',
104
+ 'assist',
105
+ 'brain',
106
+ 'wing',
107
+ 'style',
108
+ 'private',
109
+ 'top',
110
+ 'brown',
111
+ 'leg',
112
+ 'buy',
113
+ 'procedure',
114
+ 'method',
115
+ 'speed',
116
+ 'high',
117
+ 'company',
118
+ 'valuable',
119
+ 'pie',
120
+ 'analyst',
121
+ 'session',
122
+ 'pattern',
123
+ 'district',
124
+ 'pleasure',
125
+ 'dinner',
126
+ 'swimming',
127
+ 'joke',
128
+ 'order',
129
+ 'plate',
130
+ 'department',
131
+ 'motor',
132
+ 'cell',
133
+ 'spend',
134
+ 'cabinet',
135
+ 'difference',
136
+ 'power',
137
+ 'examination',
138
+ 'engine',
139
+ 'horse',
140
+ 'dimension',
141
+ 'pay',
142
+ 'toe',
143
+ 'curve',
144
+ 'literature',
145
+ 'bother',
146
+ 'fire',
147
+ 'possibility',
148
+ 'debate',
149
+ 'activity',
150
+ 'passage',
151
+ 'hello',
152
+ 'cycle',
153
+ 'background',
154
+ 'quiet',
155
+ 'author',
156
+ 'effect',
157
+ 'actor',
158
+ 'page',
159
+ 'bicycle',
160
+ 'error',
161
+ 'throat',
162
+ 'attack',
163
+ 'character',
164
+ 'phone',
165
+ 'tea',
166
+ 'increase',
167
+ 'outcome',
168
+ 'file',
169
+ 'specific',
170
+ 'inspector',
171
+ 'internal',
172
+ 'potential',
173
+ 'staff',
174
+ 'building',
175
+ 'employer',
176
+ 'shoe',
177
+ 'hand',
178
+ 'direction',
179
+ 'garden',
180
+ 'purchase',
181
+ 'interview',
182
+ 'study',
183
+ 'recognition',
184
+ 'member',
185
+ 'spiritual',
186
+ 'oven',
187
+ 'sandwich',
188
+ 'weird',
189
+ 'passenger',
190
+ 'particular',
191
+ 'response',
192
+ 'reaction',
193
+ 'size',
194
+ 'variation',
195
+ 'a',
196
+ 'cancel',
197
+ 'candy',
198
+ 'exit',
199
+ 'guest',
200
+ 'condition',
201
+ 'fly',
202
+ 'price',
203
+ 'weakness',
204
+ 'convert',
205
+ 'hotel',
206
+ 'great',
207
+ 'mouth',
208
+ 'mind',
209
+ 'song',
210
+ 'sugar',
211
+ 'suspect',
212
+ 'telephone',
213
+ 'ear',
214
+ 'roof',
215
+ 'paint',
216
+ 'refrigerator',
217
+ 'organization',
218
+ 'jury',
219
+ 'reward',
220
+ 'engineering',
221
+ 'day',
222
+ 'possession',
223
+ 'crew',
224
+ 'bar',
225
+ 'road',
226
+ 'description',
227
+ 'celebration',
228
+ 'score',
229
+ 'mark',
230
+ 'letter',
231
+ 'shower',
232
+ 'suggestion',
233
+ 'sir',
234
+ 'luck',
235
+ 'national',
236
+ 'progress',
237
+ 'hall',
238
+ 'stroke',
239
+ 'theory',
240
+ 'offer',
241
+ 'story',
242
+ 'tax',
243
+ 'definition',
244
+ 'history',
245
+ 'ride',
246
+ 'medium',
247
+ 'opening',
248
+ 'glass',
249
+ 'elevator',
250
+ 'stomach',
251
+ 'question',
252
+ 'ability',
253
+ 'leading',
254
+ 'village',
255
+ 'computer',
256
+ 'city',
257
+ 'grand',
258
+ 'confidence',
259
+ 'candle',
260
+ 'priest',
261
+ 'recommendation',
262
+ 'point',
263
+ 'necessary',
264
+ 'body',
265
+ 'desk',
266
+ 'secret',
267
+ 'horror',
268
+ 'noise',
269
+ 'culture',
270
+ 'warning',
271
+ 'water',
272
+ 'round',
273
+ 'diet',
274
+ 'flower',
275
+ 'bus',
276
+ 'tough',
277
+ 'permission',
278
+ 'week',
279
+ 'prompt',
280
+ 'connection',
281
+ 'abuse',
282
+ 'height',
283
+ 'save',
284
+ 'corner',
285
+ 'border',
286
+ 'stress',
287
+ 'drive',
288
+ 'stop',
289
+ 'rip',
290
+ 'meal',
291
+ 'listen',
292
+ 'confusion',
293
+ 'girlfriend',
294
+ 'living',
295
+ 'relation',
296
+ 'significance',
297
+ 'plan',
298
+ 'creative',
299
+ 'atmosphere',
300
+ 'blame',
301
+ 'invite',
302
+ 'housing',
303
+ 'paper',
304
+ 'drink',
305
+ 'roll',
306
+ 'silver',
307
+ 'drunk',
308
+ 'age',
309
+ 'damage',
310
+ 'smoke',
311
+ 'environment',
312
+ 'pack',
313
+ 'savings',
314
+ 'influence',
315
+ 'tourist',
316
+ 'rain',
317
+ 'post',
318
+ 'sign',
319
+ 'grandmother',
320
+ 'run',
321
+ 'profit',
322
+ 'push',
323
+ 'clerk',
324
+ 'final',
325
+ 'wine',
326
+ 'swim',
327
+ 'pause',
328
+ 'stuff',
329
+ 'singer',
330
+ 'funeral',
331
+ 'average',
332
+ 'source',
333
+ 'scene',
334
+ 'tradition',
335
+ 'personal',
336
+ 'snow',
337
+ 'nobody',
338
+ 'distance',
339
+ 'sort',
340
+ 'sensitive',
341
+ 'animal',
342
+ 'major',
343
+ 'negotiation',
344
+ 'click',
345
+ 'mood',
346
+ 'period',
347
+ 'arrival',
348
+ 'expression',
349
+ 'holiday',
350
+ 'repeat',
351
+ 'dust',
352
+ 'closet',
353
+ 'gold',
354
+ 'bad',
355
+ 'sail',
356
+ 'combination',
357
+ 'clothes',
358
+ 'emphasis',
359
+ 'duty',
360
+ 'black',
361
+ 'step',
362
+ 'school',
363
+ 'jump',
364
+ 'document',
365
+ 'professional',
366
+ 'lip',
367
+ 'chemical',
368
+ 'front',
369
+ 'wake',
370
+ 'while',
371
+ 'inside',
372
+ 'watch',
373
+ 'row',
374
+ 'subject',
375
+ 'penalty',
376
+ 'balance',
377
+ 'possible',
378
+ 'adult',
379
+ 'aside',
380
+ 'sample',
381
+ 'appeal',
382
+ 'wedding',
383
+ 'depth',
384
+ 'king',
385
+ 'award',
386
+ 'wife',
387
+ 'blow',
388
+ 'site',
389
+ 'camp',
390
+ 'music',
391
+ 'safe',
392
+ 'gift',
393
+ 'fault',
394
+ 'guess',
395
+ 'act',
396
+ 'shame',
397
+ 'drama',
398
+ 'capital',
399
+ 'exam',
400
+ 'stupid',
401
+ 'record',
402
+ 'sound',
403
+ 'swing',
404
+ 'novel',
405
+ 'minimum',
406
+ 'ratio',
407
+ 'machine',
408
+ 'shape',
409
+ 'lead',
410
+ 'operation',
411
+ 'salary',
412
+ 'cloud',
413
+ 'affair',
414
+ 'hit',
415
+ 'chapter',
416
+ 'stage',
417
+ 'quantity',
418
+ 'access',
419
+ 'army',
420
+ 'chain',
421
+ 'traffic',
422
+ 'kick',
423
+ 'analysis',
424
+ 'airport',
425
+ 'time',
426
+ 'vacation',
427
+ 'philosophy',
428
+ 'ball',
429
+ 'chest',
430
+ 'thanks',
431
+ 'place',
432
+ 'mountain',
433
+ 'advertising',
434
+ 'red',
435
+ 'past',
436
+ 'rent',
437
+ 'return',
438
+ 'tour',
439
+ 'house',
440
+ 'construction',
441
+ 'net',
442
+ 'native',
443
+ 'war',
444
+ 'figure',
445
+ 'fee',
446
+ 'spray',
447
+ 'user',
448
+ 'dirt',
449
+ 'shot',
450
+ 'task',
451
+ 'stick',
452
+ 'friend',
453
+ 'software',
454
+ 'promotion',
455
+ 'interaction',
456
+ 'surround',
457
+ 'block',
458
+ 'purpose',
459
+ 'practice',
460
+ 'conflict',
461
+ 'routine',
462
+ 'requirement',
463
+ 'bonus',
464
+ 'hole',
465
+ 'state',
466
+ 'junior',
467
+ 'sweet',
468
+ 'catch',
469
+ 'tear',
470
+ 'fold',
471
+ 'wall',
472
+ 'editor',
473
+ 'life',
474
+ 'position',
475
+ 'pound',
476
+ 'respect',
477
+ 'bathroom',
478
+ 'coat',
479
+ 'script',
480
+ 'job',
481
+ 'teach',
482
+ 'birth',
483
+ 'view',
484
+ 'resolve',
485
+ 'theme',
486
+ 'employee',
487
+ 'doubt',
488
+ 'market',
489
+ 'education',
490
+ 'serve',
491
+ 'recover',
492
+ 'tone',
493
+ 'harm',
494
+ 'miss',
495
+ 'union',
496
+ 'understanding',
497
+ 'cow',
498
+ 'river',
499
+ 'association',
500
+ 'concept',
501
+ 'training',
502
+ 'recipe',
503
+ 'relationship',
504
+ 'reserve',
505
+ 'depression',
506
+ 'proof',
507
+ 'hair',
508
+ 'revenue',
509
+ 'independent',
510
+ 'lift',
511
+ 'assignment',
512
+ 'temporary',
513
+ 'amount',
514
+ 'loss',
515
+ 'edge',
516
+ 'track',
517
+ 'check',
518
+ 'rope',
519
+ 'estimate',
520
+ 'pollution',
521
+ 'stable',
522
+ 'message',
523
+ 'delivery',
524
+ 'perspective',
525
+ 'mirror',
526
+ 'assistant',
527
+ 'representative',
528
+ 'witness',
529
+ 'nature',
530
+ 'judge',
531
+ 'fruit',
532
+ 'tip',
533
+ 'devil',
534
+ 'town',
535
+ 'emergency',
536
+ 'upper',
537
+ 'drop',
538
+ 'stay',
539
+ 'human',
540
+ 'neck',
541
+ 'speaker',
542
+ 'network',
543
+ 'sing',
544
+ 'resist',
545
+ 'league',
546
+ 'trip',
547
+ 'signature',
548
+ 'lawyer',
549
+ 'importance',
550
+ 'gas',
551
+ 'choice',
552
+ 'engineer',
553
+ 'success',
554
+ 'part',
555
+ 'external',
556
+ 'worker',
557
+ 'simple',
558
+ 'quarter',
559
+ 'student',
560
+ 'heart',
561
+ 'pass',
562
+ 'spite',
563
+ 'shift',
564
+ 'rough',
565
+ 'lady',
566
+ 'grass',
567
+ 'community',
568
+ 'garage',
569
+ 'youth',
570
+ 'standard',
571
+ 'skirt',
572
+ 'promise',
573
+ 'blind',
574
+ 'television',
575
+ 'disease',
576
+ 'commission',
577
+ 'positive',
578
+ 'energy',
579
+ 'calm',
580
+ 'presence',
581
+ 'tune',
582
+ 'basis',
583
+ 'preference',
584
+ 'head',
585
+ 'common',
586
+ 'cut',
587
+ 'somewhere',
588
+ 'presentation',
589
+ 'current',
590
+ 'thought',
591
+ 'revolution',
592
+ 'effort',
593
+ 'master',
594
+ 'implement',
595
+ 'republic',
596
+ 'floor',
597
+ 'principle',
598
+ 'stranger',
599
+ 'shoulder',
600
+ 'grade',
601
+ 'button',
602
+ 'tennis',
603
+ 'police',
604
+ 'collection',
605
+ 'account',
606
+ 'register',
607
+ 'glove',
608
+ 'divide',
609
+ 'professor',
610
+ 'chair',
611
+ 'priority',
612
+ 'combine',
613
+ 'peace',
614
+ 'extension',
615
+ 'maybe',
616
+ 'evening',
617
+ 'frame',
618
+ 'sister',
619
+ 'wave',
620
+ 'code',
621
+ 'application',
622
+ 'mouse',
623
+ 'match',
624
+ 'counter',
625
+ 'bottle',
626
+ 'half',
627
+ 'cheek',
628
+ 'resolution',
629
+ 'back',
630
+ 'knowledge',
631
+ 'make',
632
+ 'discussion',
633
+ 'screw',
634
+ 'length',
635
+ 'accident',
636
+ 'battle',
637
+ 'dress',
638
+ 'knee',
639
+ 'log',
640
+ 'package',
641
+ 'it',
642
+ 'turn',
643
+ 'hearing',
644
+ 'newspaper',
645
+ 'layer',
646
+ 'wealth',
647
+ 'profile',
648
+ 'imagination',
649
+ 'answer',
650
+ 'weekend',
651
+ 'teacher',
652
+ 'appearance',
653
+ 'meet',
654
+ 'bike',
655
+ 'rise',
656
+ 'belt',
657
+ 'crash',
658
+ 'bowl',
659
+ 'equivalent',
660
+ 'support',
661
+ 'image',
662
+ 'poem',
663
+ 'risk',
664
+ 'excitement',
665
+ 'remote',
666
+ 'secretary',
667
+ 'public',
668
+ 'produce',
669
+ 'plane',
670
+ 'display',
671
+ 'money',
672
+ 'sand',
673
+ 'situation',
674
+ 'punch',
675
+ 'customer',
676
+ 'title',
677
+ 'shake',
678
+ 'mortgage',
679
+ 'option',
680
+ 'number',
681
+ 'pop',
682
+ 'window',
683
+ 'extent',
684
+ 'nothing',
685
+ 'experience',
686
+ 'opinion',
687
+ 'departure',
688
+ 'dance',
689
+ 'indication',
690
+ 'boy',
691
+ 'material',
692
+ 'band',
693
+ 'leader',
694
+ 'sun',
695
+ 'beautiful',
696
+ 'muscle',
697
+ 'farmer',
698
+ 'variety',
699
+ 'fat',
700
+ 'handle',
701
+ 'director',
702
+ 'opportunity',
703
+ 'calendar',
704
+ 'outside',
705
+ 'pace',
706
+ 'bath',
707
+ 'fish',
708
+ 'consequence',
709
+ 'put',
710
+ 'owner',
711
+ 'go',
712
+ 'doctor',
713
+ 'information',
714
+ 'share',
715
+ 'hurt',
716
+ 'protection',
717
+ 'career',
718
+ 'finance',
719
+ 'force',
720
+ 'golf',
721
+ 'garbage',
722
+ 'aspect',
723
+ 'kid',
724
+ 'food',
725
+ 'boot',
726
+ 'milk',
727
+ 'respond',
728
+ 'objective',
729
+ 'reality',
730
+ 'raw',
731
+ 'ring',
732
+ 'mall',
733
+ 'one',
734
+ 'impact',
735
+ 'area',
736
+ 'news',
737
+ 'international',
738
+ 'series',
739
+ 'impress',
740
+ 'mother',
741
+ 'shelter',
742
+ 'strike',
743
+ 'loan',
744
+ 'month',
745
+ 'seat',
746
+ 'anything',
747
+ 'entertainment',
748
+ 'familiar',
749
+ 'clue',
750
+ 'year',
751
+ 'glad',
752
+ 'supermarket',
753
+ 'natural',
754
+ 'god',
755
+ 'cost',
756
+ 'conversation',
757
+ 'tie',
758
+ 'ruin',
759
+ 'comfort',
760
+ 'earth',
761
+ 'storm',
762
+ 'percentage',
763
+ 'assistance',
764
+ 'budget',
765
+ 'strength',
766
+ 'beginning',
767
+ 'sleep',
768
+ 'other',
769
+ 'young',
770
+ 'unit',
771
+ 'fill',
772
+ 'store',
773
+ 'desire',
774
+ 'hide',
775
+ 'value',
776
+ 'cup',
777
+ 'maintenance',
778
+ 'nurse',
779
+ 'function',
780
+ 'tower',
781
+ 'role',
782
+ 'class',
783
+ 'camera',
784
+ 'database',
785
+ 'panic',
786
+ 'nation',
787
+ 'basket',
788
+ 'ice',
789
+ 'art',
790
+ 'spirit',
791
+ 'chart',
792
+ 'exchange',
793
+ 'feedback',
794
+ 'statement',
795
+ 'reputation',
796
+ 'search',
797
+ 'hunt',
798
+ 'exercise',
799
+ 'nasty',
800
+ 'notice',
801
+ 'male',
802
+ 'yard',
803
+ 'annual',
804
+ 'collar',
805
+ 'date',
806
+ 'platform',
807
+ 'plant',
808
+ 'fortune',
809
+ 'passion',
810
+ 'friendship',
811
+ 'spread',
812
+ 'cancer',
813
+ 'ticket',
814
+ 'attitude',
815
+ 'island',
816
+ 'active',
817
+ 'object',
818
+ 'service',
819
+ 'buyer',
820
+ 'bite',
821
+ 'card',
822
+ 'face',
823
+ 'steak',
824
+ 'proposal',
825
+ 'patient',
826
+ 'heat',
827
+ 'rule',
828
+ 'resident',
829
+ 'broad',
830
+ 'politics',
831
+ 'west',
832
+ 'knife',
833
+ 'expert',
834
+ 'girl',
835
+ 'design',
836
+ 'salt',
837
+ 'baseball',
838
+ 'grab',
839
+ 'inspection',
840
+ 'cousin',
841
+ 'couple',
842
+ 'magazine',
843
+ 'cook',
844
+ 'dependent',
845
+ 'security',
846
+ 'chicken',
847
+ 'version',
848
+ 'currency',
849
+ 'ladder',
850
+ 'scheme',
851
+ 'kitchen',
852
+ 'employment',
853
+ 'local',
854
+ 'attention',
855
+ 'manager',
856
+ 'fact',
857
+ 'cover',
858
+ 'sad',
859
+ 'guard',
860
+ 'relative',
861
+ 'county',
862
+ 'rate',
863
+ 'lunch',
864
+ 'program',
865
+ 'initiative',
866
+ 'gear',
867
+ 'bridge',
868
+ 'breast',
869
+ 'talk',
870
+ 'dish',
871
+ 'guarantee',
872
+ 'beer',
873
+ 'vehicle',
874
+ 'reception',
875
+ 'woman',
876
+ 'substance',
877
+ 'copy',
878
+ 'lecture',
879
+ 'advantage',
880
+ 'park',
881
+ 'cold',
882
+ 'death',
883
+ 'mix',
884
+ 'hold',
885
+ 'scale',
886
+ 'tomorrow',
887
+ 'blood',
888
+ 'request',
889
+ 'green',
890
+ 'cookie',
891
+ 'church',
892
+ 'strip',
893
+ 'forever',
894
+ 'beyond',
895
+ 'debt',
896
+ 'tackle',
897
+ 'wash',
898
+ 'following',
899
+ 'feel',
900
+ 'maximum',
901
+ 'sector',
902
+ 'sea',
903
+ 'property',
904
+ 'economics',
905
+ 'menu',
906
+ 'bench',
907
+ 'try',
908
+ 'language',
909
+ 'start',
910
+ 'call',
911
+ 'solid',
912
+ 'address',
913
+ 'income',
914
+ 'foot',
915
+ 'senior',
916
+ 'honey',
917
+ 'few',
918
+ 'mixture',
919
+ 'cash',
920
+ 'grocery',
921
+ 'link',
922
+ 'map',
923
+ 'form',
924
+ 'factor',
925
+ 'pot',
926
+ 'model',
927
+ 'writer',
928
+ 'farm',
929
+ 'winter',
930
+ 'skill',
931
+ 'anywhere',
932
+ 'birthday',
933
+ 'policy',
934
+ 'release',
935
+ 'husband',
936
+ 'lab',
937
+ 'hurry',
938
+ 'mail',
939
+ 'equipment',
940
+ 'sink',
941
+ 'pair',
942
+ 'driver',
943
+ 'consideration',
944
+ 'leather',
945
+ 'skin',
946
+ 'blue',
947
+ 'boat',
948
+ 'sale',
949
+ 'brick',
950
+ 'two',
951
+ 'feed',
952
+ 'square',
953
+ 'dot',
954
+ 'rush',
955
+ 'dream',
956
+ 'location',
957
+ 'afternoon',
958
+ 'manufacturer',
959
+ 'control',
960
+ 'occasion',
961
+ 'trouble',
962
+ 'introduction',
963
+ 'advice',
964
+ 'bet',
965
+ 'eat',
966
+ 'kill',
967
+ 'category',
968
+ 'manner',
969
+ 'office',
970
+ 'estate',
971
+ 'pride',
972
+ 'awareness',
973
+ 'slip',
974
+ 'crack',
975
+ 'client',
976
+ 'nail',
977
+ 'shoot',
978
+ 'membership',
979
+ 'soft',
980
+ 'anybody',
981
+ 'web',
982
+ 'official',
983
+ 'individual',
984
+ 'pizza',
985
+ 'interest',
986
+ 'bag',
987
+ 'spell',
988
+ 'profession',
989
+ 'queen',
990
+ 'deal',
991
+ 'resource',
992
+ 'ship',
993
+ 'guy',
994
+ 'chocolate',
995
+ 'joint',
996
+ 'formal',
997
+ 'upstairs',
998
+ 'car',
999
+ 'resort',
1000
+ 'abroad',
1001
+ 'dealer',
1002
+ 'associate',
1003
+ 'finger',
1004
+ 'surgery',
1005
+ 'comment',
1006
+ 'team',
1007
+ 'detail',
1008
+ 'crazy',
1009
+ 'path',
1010
+ 'tale',
1011
+ 'initial',
1012
+ 'arm',
1013
+ 'radio',
1014
+ 'demand',
1015
+ 'single',
1016
+ 'draw',
1017
+ 'yellow',
1018
+ 'contest',
1019
+ 'piece',
1020
+ 'quote',
1021
+ 'pull',
1022
+ 'commercial',
1023
+ 'shirt',
1024
+ 'contribution',
1025
+ 'cream',
1026
+ 'channel',
1027
+ 'suit',
1028
+ 'discipline',
1029
+ 'instruction',
1030
+ 'concert',
1031
+ 'speech',
1032
+ 'low',
1033
+ 'effective',
1034
+ 'hang',
1035
+ 'scratch',
1036
+ 'industry',
1037
+ 'breakfast',
1038
+ 'lay',
1039
+ 'join',
1040
+ 'metal',
1041
+ 'bedroom',
1042
+ 'minute',
1043
+ 'product',
1044
+ 'rest',
1045
+ 'temperature',
1046
+ 'many',
1047
+ 'give',
1048
+ 'argument',
1049
+ 'print',
1050
+ 'purple',
1051
+ 'laugh',
1052
+ 'health',
1053
+ 'credit',
1054
+ 'investment',
1055
+ 'sell',
1056
+ 'setting',
1057
+ 'lesson',
1058
+ 'egg',
1059
+ 'middle',
1060
+ 'marriage',
1061
+ 'level',
1062
+ 'evidence',
1063
+ 'phrase',
1064
+ 'love',
1065
+ 'self',
1066
+ 'benefit',
1067
+ 'guidance',
1068
+ 'affect',
1069
+ 'you',
1070
+ 'dad',
1071
+ 'anxiety',
1072
+ 'special',
1073
+ 'boyfriend',
1074
+ 'test',
1075
+ 'blank',
1076
+ 'payment',
1077
+ 'soup',
1078
+ 'obligation',
1079
+ 'reply',
1080
+ 'smile',
1081
+ 'deep',
1082
+ 'complaint',
1083
+ 'addition',
1084
+ 'review',
1085
+ 'box',
1086
+ 'towel',
1087
+ 'minor',
1088
+ 'fun',
1089
+ 'soil',
1090
+ 'issue',
1091
+ 'cigarette',
1092
+ 'internet',
1093
+ 'gain',
1094
+ 'tell',
1095
+ 'entry',
1096
+ 'spare',
1097
+ 'incident',
1098
+ 'family',
1099
+ 'refuse',
1100
+ 'branch',
1101
+ 'can',
1102
+ 'pen',
1103
+ 'grandfather',
1104
+ 'constant',
1105
+ 'tank',
1106
+ 'uncle',
1107
+ 'climate',
1108
+ 'ground',
1109
+ 'volume',
1110
+ 'communication',
1111
+ 'kind',
1112
+ 'poet',
1113
+ 'child',
1114
+ 'screen',
1115
+ 'mine',
1116
+ 'quit',
1117
+ 'gene',
1118
+ 'lack',
1119
+ 'charity',
1120
+ 'memory',
1121
+ 'tooth',
1122
+ 'fear',
1123
+ 'mention',
1124
+ 'marketing',
1125
+ 'reveal',
1126
+ 'reason',
1127
+ 'court',
1128
+ 'season',
1129
+ 'freedom',
1130
+ 'land',
1131
+ 'sport',
1132
+ 'audience',
1133
+ 'classroom',
1134
+ 'law',
1135
+ 'hook',
1136
+ 'win',
1137
+ 'carry',
1138
+ 'eye',
1139
+ 'smell',
1140
+ 'distribution',
1141
+ 'research',
1142
+ 'country',
1143
+ 'dare',
1144
+ 'hope',
1145
+ 'whereas',
1146
+ 'stretch',
1147
+ 'library',
1148
+ 'if',
1149
+ 'delay',
1150
+ 'college',
1151
+ 'plastic',
1152
+ 'book',
1153
+ 'present',
1154
+ 'use',
1155
+ 'worry',
1156
+ 'champion',
1157
+ 'goal',
1158
+ 'economy',
1159
+ 'march',
1160
+ 'election',
1161
+ 'reflection',
1162
+ 'midnight',
1163
+ 'slide',
1164
+ 'inflation',
1165
+ 'action',
1166
+ 'challenge',
1167
+ 'guitar',
1168
+ 'coast',
1169
+ 'apple',
1170
+ 'campaign',
1171
+ 'field',
1172
+ 'jacket',
1173
+ 'sense',
1174
+ 'way',
1175
+ 'visual',
1176
+ 'remove',
1177
+ 'weather',
1178
+ 'trash',
1179
+ 'cable',
1180
+ 'regret',
1181
+ 'buddy',
1182
+ 'beach',
1183
+ 'historian',
1184
+ 'courage',
1185
+ 'sympathy',
1186
+ 'truck',
1187
+ 'tension',
1188
+ 'permit',
1189
+ 'nose',
1190
+ 'bed',
1191
+ 'son',
1192
+ 'person',
1193
+ 'base',
1194
+ 'meat',
1195
+ 'usual',
1196
+ 'air',
1197
+ 'meeting',
1198
+ 'worth',
1199
+ 'game',
1200
+ 'independence',
1201
+ 'physical',
1202
+ 'brief',
1203
+ 'play',
1204
+ 'raise',
1205
+ 'board',
1206
+ 'she',
1207
+ 'key',
1208
+ 'writing',
1209
+ 'pick',
1210
+ 'command',
1211
+ 'party',
1212
+ 'yesterday',
1213
+ 'spring',
1214
+ 'candidate',
1215
+ 'physics',
1216
+ 'university',
1217
+ 'concern',
1218
+ 'development',
1219
+ 'change',
1220
+ 'string',
1221
+ 'target',
1222
+ 'instance',
1223
+ 'room',
1224
+ 'bitter',
1225
+ 'bird',
1226
+ 'football',
1227
+ 'normal',
1228
+ 'split',
1229
+ 'impression',
1230
+ 'wood',
1231
+ 'long',
1232
+ 'meaning',
1233
+ 'stock',
1234
+ 'cap',
1235
+ 'leadership',
1236
+ 'media',
1237
+ 'ambition',
1238
+ 'fishing',
1239
+ 'essay',
1240
+ 'salad',
1241
+ 'repair',
1242
+ 'today',
1243
+ 'designer',
1244
+ 'night',
1245
+ 'bank',
1246
+ 'drawing',
1247
+ 'inevitable',
1248
+ 'phase',
1249
+ 'vast',
1250
+ 'chip',
1251
+ 'anger',
1252
+ 'switch',
1253
+ 'cry',
1254
+ 'twist',
1255
+ 'personality',
1256
+ 'attempt',
1257
+ 'storage',
1258
+ 'being',
1259
+ 'preparation',
1260
+ 'bat',
1261
+ 'selection',
1262
+ 'white',
1263
+ 'technology',
1264
+ 'contract',
1265
+ 'side',
1266
+ 'section',
1267
+ 'station',
1268
+ 'till',
1269
+ 'structure',
1270
+ 'tongue',
1271
+ 'taste',
1272
+ 'truth',
1273
+ 'difficulty',
1274
+ 'group',
1275
+ 'limit',
1276
+ 'main',
1277
+ 'move',
1278
+ 'feeling',
1279
+ 'light',
1280
+ 'example',
1281
+ 'mission',
1282
+ 'might',
1283
+ 'wait',
1284
+ 'wheel',
1285
+ 'shop',
1286
+ 'host',
1287
+ 'classic',
1288
+ 'alternative',
1289
+ 'cause',
1290
+ 'agent',
1291
+ 'consist',
1292
+ 'table',
1293
+ 'airline',
1294
+ 'text',
1295
+ 'pool',
1296
+ 'craft',
1297
+ 'range',
1298
+ 'fuel',
1299
+ 'tool',
1300
+ 'partner',
1301
+ 'load',
1302
+ 'entrance',
1303
+ 'deposit',
1304
+ 'hate',
1305
+ 'article',
1306
+ 'video',
1307
+ 'summer',
1308
+ 'feature',
1309
+ 'extreme',
1310
+ 'mobile',
1311
+ 'hospital',
1312
+ 'flight',
1313
+ 'fall',
1314
+ 'pension',
1315
+ 'piano',
1316
+ 'fail',
1317
+ 'result',
1318
+ 'rub',
1319
+ 'gap',
1320
+ 'system',
1321
+ 'report',
1322
+ 'suck',
1323
+ 'ordinary',
1324
+ 'wind',
1325
+ 'nerve',
1326
+ 'ask',
1327
+ 'shine',
1328
+ 'note',
1329
+ 'line',
1330
+ 'mom',
1331
+ 'perception',
1332
+ 'brother',
1333
+ 'reference',
1334
+ 'bend',
1335
+ 'charge',
1336
+ 'treat',
1337
+ 'trick',
1338
+ 'term',
1339
+ 'homework',
1340
+ 'bake',
1341
+ 'bid',
1342
+ 'status',
1343
+ 'project',
1344
+ 'strategy',
1345
+ 'orange',
1346
+ 'let',
1347
+ 'enthusiasm',
1348
+ 'parent',
1349
+ 'concentrate',
1350
+ 'device',
1351
+ 'travel',
1352
+ 'poetry',
1353
+ 'business',
1354
+ 'society',
1355
+ 'kiss',
1356
+ 'end',
1357
+ 'vegetable',
1358
+ 'employ',
1359
+ 'schedule',
1360
+ 'hour',
1361
+ 'brave',
1362
+ 'focus',
1363
+ 'process',
1364
+ 'movie',
1365
+ 'illegal',
1366
+ 'general',
1367
+ 'coffee',
1368
+ 'ad',
1369
+ 'highway',
1370
+ 'chemistry',
1371
+ 'psychology',
1372
+ 'hire',
1373
+ 'bell',
1374
+ 'conference',
1375
+ 'relief',
1376
+ 'show',
1377
+ 'neat',
1378
+ 'funny',
1379
+ 'weight',
1380
+ 'quality',
1381
+ 'club',
1382
+ 'daughter',
1383
+ 'zone',
1384
+ 'touch',
1385
+ 'tonight',
1386
+ 'shock',
1387
+ 'burn',
1388
+ 'excuse',
1389
+ 'name',
1390
+ 'survey',
1391
+ 'landscape',
1392
+ 'advance',
1393
+ 'satisfaction',
1394
+ 'bread',
1395
+ 'disaster',
1396
+ 'item',
1397
+ 'hat',
1398
+ 'prior',
1399
+ 'shopping',
1400
+ 'visit',
1401
+ 'east',
1402
+ 'photo',
1403
+ 'home',
1404
+ 'idea',
1405
+ 'father',
1406
+ 'comparison',
1407
+ 'cat',
1408
+ 'pipe',
1409
+ 'winner',
1410
+ 'count',
1411
+ 'lake',
1412
+ 'fight',
1413
+ 'prize',
1414
+ 'foundation',
1415
+ 'dog',
1416
+ 'keep',
1417
+ 'ideal',
1418
+ 'fan',
1419
+ 'struggle',
1420
+ 'peak',
1421
+ 'safety',
1422
+ 'solution',
1423
+ 'hell',
1424
+ 'conclusion',
1425
+ 'population',
1426
+ 'strain',
1427
+ 'alarm',
1428
+ 'measurement',
1429
+ 'second',
1430
+ 'train',
1431
+ 'race',
1432
+ 'due',
1433
+ 'insurance',
1434
+ 'boss',
1435
+ 'tree',
1436
+ 'monitor',
1437
+ 'sick',
1438
+ 'course',
1439
+ 'drag',
1440
+ 'appointment',
1441
+ 'slice',
1442
+ 'still',
1443
+ 'care',
1444
+ 'patience',
1445
+ 'rich',
1446
+ 'escape',
1447
+ 'emotion',
1448
+ 'royal',
1449
+ 'female',
1450
+ 'childhood',
1451
+ 'government',
1452
+ 'picture',
1453
+ 'will',
1454
+ 'sock',
1455
+ 'big',
1456
+ 'gate',
1457
+ 'oil',
1458
+ 'cross',
1459
+ 'pin',
1460
+ 'improvement',
1461
+ 'championship',
1462
+ 'silly',
1463
+ 'help',
1464
+ 'sky',
1465
+ 'pitch',
1466
+ 'man',
1467
+ 'diamond',
1468
+ 'most',
1469
+ 'transition',
1470
+ 'work',
1471
+ 'science',
1472
+ 'committee',
1473
+ 'moment',
1474
+ 'fix',
1475
+ 'teaching',
1476
+ 'dig',
1477
+ 'specialist',
1478
+ 'complex',
1479
+ 'guide',
1480
+ 'people',
1481
+ 'dead',
1482
+ 'voice',
1483
+ 'original',
1484
+ 'break',
1485
+ 'topic',
1486
+ 'data',
1487
+ 'degree',
1488
+ 'reading',
1489
+ 'recording',
1490
+ 'bunch',
1491
+ 'reach',
1492
+ 'judgment',
1493
+ 'lie',
1494
+ 'regular',
1495
+ 'set',
1496
+ 'painting',
1497
+ 'mode',
1498
+ 'list',
1499
+ 'player',
1500
+ 'bear',
1501
+ 'north',
1502
+ 'wonder',
1503
+ 'carpet',
1504
+ 'heavy',
1505
+ 'officer',
1506
+ 'negative',
1507
+ 'clock',
1508
+ 'unique',
1509
+ 'baby',
1510
+ 'pain',
1511
+ 'assumption',
1512
+ 'disk',
1513
+ 'iron',
1514
+ 'bill',
1515
+ 'drawer',
1516
+ 'look',
1517
+ 'double',
1518
+ 'mistake',
1519
+ 'finish',
1520
+ 'future',
1521
+ 'brilliant',
1522
+ 'contact',
1523
+ 'math',
1524
+ 'rice',
1525
+ 'leave',
1526
+ 'restaurant',
1527
+ 'discount',
1528
+ 'sex',
1529
+ 'virus',
1530
+ 'bit',
1531
+ 'trust',
1532
+ 'event',
1533
+ 'wear',
1534
+ 'juice',
1535
+ 'failure',
1536
+ 'bug',
1537
+ 'context',
1538
+ 'mud',
1539
+ 'whole',
1540
+ 'wrap',
1541
+ 'intention',
1542
+ 'draft',
1543
+ 'pressure',
1544
+ 'cake',
1545
+ 'dark',
1546
+ 'explanation',
1547
+ 'space',
1548
+ 'angle',
1549
+ 'word',
1550
+ 'efficiency',
1551
+ 'management',
1552
+ 'habit',
1553
+ 'star',
1554
+ 'chance',
1555
+ 'finding',
1556
+ 'transportation',
1557
+ 'stand',
1558
+ 'criticism',
1559
+ 'flow',
1560
+ 'door',
1561
+ 'injury',
1562
+ 'insect',
1563
+ 'surprise',
1564
+ 'apartment',
1565
+ ] # pylint: disable=line-too-long
1566
+
1567
+ # ISO 639-1 codes to language names.
1568
+ LANGUAGE_CODES = MappingProxyType({
1569
+ 'en': 'English',
1570
+ 'es': 'Spanish',
1571
+ 'pt': 'Portuguese',
1572
+ 'ar': 'Arabic',
1573
+ 'hi': 'Hindi',
1574
+ 'fr': 'French',
1575
+ 'ru': 'Russian',
1576
+ 'de': 'German',
1577
+ 'ja': 'Japanese',
1578
+ 'it': 'Italian',
1579
+ 'bn': 'Bengali',
1580
+ 'uk': 'Ukrainian',
1581
+ 'th': 'Thai',
1582
+ 'ur': 'Urdu',
1583
+ 'ta': 'Tamil',
1584
+ 'te': 'Telugu',
1585
+ 'bg': 'Bulgarian',
1586
+ 'ko': 'Korean',
1587
+ 'pl': 'Polish',
1588
+ 'he': 'Hebrew',
1589
+ 'fa': 'Persian',
1590
+ 'vi': 'Vietnamese',
1591
+ 'ne': 'Nepali',
1592
+ 'sw': 'Swahili',
1593
+ 'kn': 'Kannada',
1594
+ 'mr': 'Marathi',
1595
+ 'gu': 'Gujarati',
1596
+ 'pa': 'Punjabi',
1597
+ 'ml': 'Malayalam',
1598
+ 'fi': 'Finnish',
1599
+ })
1600
+
1601
+ # Chinese characters
1602
+ _CHINESE_CHARS_PATTERN = r'[\u4E00-\u9FFF\u3400-\u4DBF]'
1603
+ # Japanese Hiragana & Katakana
1604
+ _JAPANESE_CHARS_PATTERN = r'[\u3040-\u309f\u30a0-\u30ff]'
1605
+ # Korean (Hangul Syllables)
1606
+ _KOREAN_CHARS_PATTERN = r'[\uAC00-\uD7AF]'
1607
+ _ALPHABETS = '([A-Za-z])'
1608
+ _PREFIXES = '(Mr|St|Mrs|Ms|Dr)[.]'
1609
+ _SUFFIXES = '(Inc|Ltd|Jr|Sr|Co)'
1610
+ _STARTERS = r'(Mr|Mrs|Ms|Dr|Prof|Capt|Cpt|Lt|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)'
1611
+ _ACRONYMS = '([A-Z][.][A-Z][.](?:[A-Z][.])?)'
1612
+ _WEBSITES = '[.](com|net|org|io|gov|edu|me)'
1613
+ _DIGITS = '([0-9])'
1614
+ _MULTIPLE_DOTS = r'\.{2,}'
1615
+
1616
+
1617
+ # Util functions
1618
+ def split_into_sentences(text):
1619
+ """Split the text into sentences.
1620
+
1621
+ Args:
1622
+ text: A string that consists of more than or equal to one sentences.
1623
+
1624
+ Returns:
1625
+ A list of strings where each string is a sentence.
1626
+ """
1627
+ text = ' ' + text + ' '
1628
+ text = text.replace('\n', ' ')
1629
+ text = re.sub(_PREFIXES, '\\1<prd>', text)
1630
+ text = re.sub(_WEBSITES, '<prd>\\1', text)
1631
+ text = re.sub(_DIGITS + '[.]' + _DIGITS, '\\1<prd>\\2', text)
1632
+ text = re.sub(
1633
+ _MULTIPLE_DOTS,
1634
+ lambda match: '<prd>' * len(match.group(0)) + '<stop>',
1635
+ text,
1636
+ )
1637
+ if 'Ph.D' in text:
1638
+ text = text.replace('Ph.D.', 'Ph<prd>D<prd>')
1639
+ text = re.sub(r'\s' + _ALPHABETS + '[.] ', ' \\1<prd> ', text)
1640
+ text = re.sub(_ACRONYMS + ' ' + _STARTERS, '\\1<stop> \\2', text)
1641
+ text = re.sub(
1642
+ _ALPHABETS + '[.]' + _ALPHABETS + '[.]' + _ALPHABETS + '[.]',
1643
+ '\\1<prd>\\2<prd>\\3<prd>',
1644
+ text,
1645
+ )
1646
+ text = re.sub(_ALPHABETS + '[.]' + _ALPHABETS + '[.]', '\\1<prd>\\2<prd>', text)
1647
+ text = re.sub(' ' + _SUFFIXES + '[.] ' + _STARTERS, ' \\1<stop> \\2', text)
1648
+ text = re.sub(' ' + _SUFFIXES + '[.]', ' \\1<prd>', text)
1649
+ text = re.sub(' ' + _ALPHABETS + '[.]', ' \\1<prd>', text)
1650
+ if '”' in text:
1651
+ text = text.replace('.”', '”.')
1652
+ if '"' in text:
1653
+ text = text.replace('."', '".')
1654
+ if '!' in text:
1655
+ text = text.replace('!"', '"!')
1656
+ if '?' in text:
1657
+ text = text.replace('?"', '"?')
1658
+ text = text.replace('.', '.<stop>')
1659
+ text = text.replace('?', '?<stop>')
1660
+ text = text.replace('!', '!<stop>')
1661
+ text = text.replace('<prd>', '.')
1662
+ sentences = text.split('<stop>')
1663
+ sentences = [s.strip() for s in sentences]
1664
+ if sentences and not sentences[-1]:
1665
+ sentences = sentences[:-1]
1666
+ return sentences
1667
+
1668
+
1669
+ def count_words(text):
1670
+ """Counts the number of words."""
1671
+ try:
1672
+ tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
1673
+ tokens = tokenizer.tokenize(text)
1674
+ num_words = len(tokens)
1675
+ except:
1676
+ print('Failed to count for', text)
1677
+ return 0
1678
+ return num_words
1679
+
1680
+
1681
+ def split_chinese_japanese(lines: str) -> Iterable[str]:
1682
+ """
1683
+ Split Chinese and Japanese text into sentences.
1684
+ From https://stackoverflow.com/questions/27441191/splitting-chinese-document-into-sentences
1685
+ Special question/exclamation marks were added upon inspection of our raw data
1686
+ Also supports multiple lines.
1687
+ """
1688
+ for line in lines.splitlines():
1689
+ for sent in re.findall(r'[^!?。\.\!\?\!\?\.\n]+[!?。\.\!\?\!\?\.\n]?', line.strip(), flags=re.U):
1690
+ yield sent
1691
+
1692
+
1693
+ def count_words_chinese_japanese(text: str) -> int:
1694
+ """Counts the number of words for Chinese and Japanese and Korean.
1695
+ Can be extended to additional languages.
1696
+ Source: https://stackoverflow.com/questions/49164507/how-to-count-the-number-of-chinese-korean-and-english-words withadditional modifications
1697
+ Example:
1698
+ >In: count_words_chinese_japanese('こんにちは、ジェイソンさん、Jason? Nice to meet you☺ ❤')
1699
+ >Out: 19
1700
+ """
1701
+ # Non alpha numeric patterns in latin and asian languages.
1702
+ non_alphanumeric_patterns = (r"[\\.\!\?\.\/_,\{\}<>:;$%^&*(+\"\'+——!,。?、`~@#¥……():;《)《》“”()\[\]»〔〕\-「」]+")
1703
+ text = re.sub(non_alphanumeric_patterns, '', text)
1704
+ if emoji:
1705
+ emoji_cnt = emoji.emoji_count(text) # count emojis
1706
+ text = emoji.replace_emoji(text, '') # remove emojis
1707
+ else:
1708
+ emoji_cnt = 0
1709
+ foreign_chars_patterns = '|'.join([_CHINESE_CHARS_PATTERN, _JAPANESE_CHARS_PATTERN, _KOREAN_CHARS_PATTERN])
1710
+ asian_chars = re.findall(foreign_chars_patterns, text)
1711
+ asian_chars_cnt = len(asian_chars)
1712
+ non_asian_chars = re.sub(foreign_chars_patterns, ' ', text)
1713
+ non_asian_words_cnt = len(non_asian_chars.split())
1714
+ return non_asian_words_cnt + asian_chars_cnt + emoji_cnt
1715
+
1716
+
1717
+ @functools.lru_cache(maxsize=None)
1718
+ def _get_sentence_tokenizer():
1719
+ return nltk.data.load('nltk:tokenizers/punkt/english.pickle')
1720
+
1721
+
1722
+ def count_sentences(text):
1723
+ """Count the number of sentences."""
1724
+ tokenizer = _get_sentence_tokenizer()
1725
+ tokenized_sentences = tokenizer.tokenize(text)
1726
+ return len(tokenized_sentences)
1727
+
1728
+
1729
+ def count_hindi_num_sentences(text):
1730
+ sentences = re.split(r'(?<=[।!?])\s*', text)
1731
+ return len([s for s in sentences if s.strip()])
1732
+
1733
+
1734
+ def generate_keywords(num_keywords):
1735
+ """Randomly generates a few keywords."""
1736
+ return random.sample(WORD_LIST, k=num_keywords)
1737
+
1738
+
1739
+ """Library of instructions"""
1740
+ _InstructionArgsDtype = Optional[Dict[str, Union[int, str, Sequence[str]]]]
1741
+
1742
+ _LANGUAGES = LANGUAGE_CODES
1743
+
1744
+ # The relational operation for comparison.
1745
+ _COMPARISON_RELATION = ('less than', 'at least')
1746
+
1747
+ # The maximum number of sentences.
1748
+ _MAX_NUM_SENTENCES = 20
1749
+
1750
+ # The number of placeholders.
1751
+ _NUM_PLACEHOLDERS = 4
1752
+
1753
+ # The number of bullet lists.
1754
+ _NUM_BULLETS = 5
1755
+
1756
+ # The options of constrained response.
1757
+ _CONSTRAINED_RESPONSE_OPTIONS = (
1758
+ 'My answer is yes.',
1759
+ 'My answer is no.',
1760
+ 'My answer is maybe.',
1761
+ )
1762
+
1763
+ # The options of starter keywords.
1764
+ _STARTER_OPTIONS = (
1765
+ 'I would say',
1766
+ 'My answer is',
1767
+ 'I believe',
1768
+ 'In my opinion',
1769
+ 'I think',
1770
+ 'I reckon',
1771
+ 'I feel',
1772
+ 'From my perspective',
1773
+ 'As I see it',
1774
+ 'According to me',
1775
+ "As far as I'm concerned",
1776
+ 'To my understanding',
1777
+ 'In my view',
1778
+ 'My take on it is',
1779
+ 'As per my perception',
1780
+ )
1781
+
1782
+ # The options of ending keywords.
1783
+ # TODO(jeffreyzhou) add more ending options
1784
+ _ENDING_OPTIONS = ('Any other questions?', 'Is there anything else I can help with?')
1785
+
1786
+ # The number of highlighted sections.
1787
+ _NUM_HIGHLIGHTED_SECTIONS = 4
1788
+
1789
+ # The section spliter.
1790
+ _SECTION_SPLITER = ('Section', 'SECTION')
1791
+
1792
+ # The number of sections.
1793
+ _NUM_SECTIONS = 5
1794
+
1795
+ # The number of paragraphs.
1796
+ _NUM_PARAGRAPHS = 5
1797
+
1798
+ # The postscript marker.
1799
+ _POSTSCRIPT_MARKER = ('P.S.', 'P.P.S')
1800
+
1801
+ # The number of keywords.
1802
+ _NUM_KEYWORDS = 2
1803
+
1804
+ # The occurrences of a single keyword.
1805
+ _KEYWORD_FREQUENCY = 3
1806
+
1807
+ # The occurrences of a single letter.
1808
+ _LETTER_FREQUENCY = 10
1809
+
1810
+ # The occurrences of words with all capital letters.
1811
+ _ALL_CAPITAL_WORD_FREQUENCY = 20
1812
+
1813
+ # The number of words in the response.
1814
+ _NUM_WORDS_LOWER_LIMIT = 100
1815
+ _NUM_WORDS_UPPER_LIMIT = 500
1816
+
1817
+
1818
+ class Instruction:
1819
+ """An instruction template."""
1820
+
1821
+ def __init__(self, instruction_id):
1822
+ self.id = instruction_id
1823
+
1824
+ def build_description(self, **kwargs):
1825
+ raise NotImplementedError('`build_description` not implemented.')
1826
+
1827
+ def get_instruction_args(self):
1828
+ raise NotImplementedError('`get_instruction_args` not implemented.')
1829
+
1830
+ def get_instruction_args_keys(self):
1831
+ raise NotImplementedError('`get_instruction_args_keys` not implemented.')
1832
+
1833
+ def check_following(self, value):
1834
+ raise NotImplementedError('`check_following` not implemented.')
1835
+
1836
+
1837
+ class ResponseLanguageChecker(Instruction):
1838
+ """Check the language of the entire response."""
1839
+
1840
+ def build_description(self, *, language=None):
1841
+ """Build the instruction description.
1842
+
1843
+ Args:
1844
+ language: A string representing the expected language of the response. The
1845
+ language has to comply to the 97 types defined in
1846
+ `langid.py` (https://pypi.org/project/langid/1.1.5/), which follows
1847
+ ISO 639-1 codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes);
1848
+ for example, `en` for English, `zh` for Chinese, `fr` for French.
1849
+
1850
+ Returns:
1851
+ A string representing the instruction description.
1852
+ """
1853
+ self._language = language
1854
+ if self._language is None:
1855
+ self._language = random.choice(list(_LANGUAGES.keys()))
1856
+ # TODO(tianjianlu): opens the description generation to more choices.
1857
+ self._description_pattern = (
1858
+ 'Your ENTIRE response should be in {language} language, no other ' + 'language is allowed.'
1859
+ )
1860
+ return self._description_pattern.format(language=_LANGUAGES[self._language])
1861
+
1862
+ def get_instruction_args(self):
1863
+ """Returns the keyward args of `build_description`."""
1864
+ return {'language': self._language}
1865
+
1866
+ def get_instruction_args_keys(self):
1867
+ """Returns the args keys of `build_description`."""
1868
+ return ['language']
1869
+
1870
+ def check_following(self, value):
1871
+ """Check if the language of the entire response follows the instruction.
1872
+
1873
+ Args:
1874
+ value: A string representing the response.
1875
+
1876
+ Returns:
1877
+ True if the language of `value` follows instruction; otherwise False.
1878
+ """
1879
+ try:
1880
+ assert isinstance(value, str)
1881
+ except:
1882
+ print('Failed for assertion, got non str type input,', value)
1883
+ return False
1884
+
1885
+ try:
1886
+ return langdetect.detect(value) == self._language
1887
+ except langdetect.LangDetectException as e:
1888
+ # Count as instruction is followed.
1889
+ logger.info('Unable to detect language for text %s due to %s', value, e) # refex: disable=pytotw.037
1890
+ return True
1891
+
1892
+
1893
+ class NumberOfSentences(Instruction):
1894
+ """Check the number of sentences."""
1895
+
1896
+ def build_description(self, *, num_sentences=None, relation=None):
1897
+ """Build the instruction description.
1898
+
1899
+ Args:
1900
+ num_sentences: An integer specifying the number of sentences as a
1901
+ threshold.
1902
+ relation: A string in (`less than`, `at least`), defining the relational
1903
+ operator for comparison.
1904
+ Two relational comparisons are supported for now:
1905
+ if 'less than', the actual number of sentences < the threshold;
1906
+ if 'at least', the actual number of sentences >= the threshold.
1907
+
1908
+ Returns:
1909
+ A string representing the instruction description.
1910
+ """
1911
+ # The number of sentences as a threshold for comparison.
1912
+ self._num_sentences_threshold = num_sentences
1913
+ if self._num_sentences_threshold is None or self._num_sentences_threshold < 0:
1914
+ self._num_sentences_threshold = random.randint(1, _MAX_NUM_SENTENCES)
1915
+
1916
+ if relation is None:
1917
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1918
+ elif relation not in _COMPARISON_RELATION:
1919
+ raise ValueError(
1920
+ 'The supported relation for comparison must be in '
1921
+ f'{_COMPARISON_RELATION}, but {relation} is given.'
1922
+ )
1923
+ else:
1924
+ self._comparison_relation = relation
1925
+
1926
+ self._description_pattern = ('Your response should contain {relation} {num_sentences} sentences.')
1927
+ return self._description_pattern.format(
1928
+ relation=self._comparison_relation,
1929
+ num_sentences=self._num_sentences_threshold,
1930
+ )
1931
+
1932
+ def get_instruction_args(self):
1933
+ """Returns the keyward args of `build_description`."""
1934
+ return {
1935
+ 'num_sentences': self._num_sentences_threshold,
1936
+ 'relation': self._comparison_relation,
1937
+ }
1938
+
1939
+ def get_instruction_args_keys(self):
1940
+ """Returns the args keys of `build_description`."""
1941
+ return ['num_sentences', 'relation']
1942
+
1943
+ def check_following(self, value):
1944
+ """Check if the number of sentences follows the instruction.
1945
+
1946
+ Args:
1947
+ value: A string representing the response.
1948
+
1949
+ Returns:
1950
+ True if the response follows the instruction.
1951
+
1952
+ Raise:
1953
+ ValueError if the string in `instruction_args` is not in
1954
+ [`less_than`, `at_least`].
1955
+ """
1956
+ try:
1957
+ lang = langdetect.detect(value)
1958
+ except:
1959
+ print('Failed to detect language, got value:', value)
1960
+ lang = 'en'
1961
+ if lang == 'th':
1962
+ from pythainlp.tokenize import sent_tokenize as sent_tokenize_thai
1963
+
1964
+ # print(f"shervin1. lang is {lang}")
1965
+ # print(value)
1966
+ # Newline also counts as a new sentence:
1967
+ num_sentences = sum([len(sent_tokenize_thai(line)) for line in value.splitlines()])
1968
+ # print(f"num sentences: {num_sentences}")
1969
+ elif lang == 'hi':
1970
+ num_sentences = count_hindi_num_sentences(value)
1971
+ elif lang in ['zh', 'zh-cn', 'zh-tw', 'ja']:
1972
+ # print(f"shervin2. lang is {lang}")
1973
+ # print(value)
1974
+ num_sentences = len(list(split_chinese_japanese(value)))
1975
+ # print(f"num sentences: {num_sentences}")
1976
+ else:
1977
+ # print(f"shervin3: lang is {lang}")
1978
+ num_sentences = count_sentences(value)
1979
+ # print(f"num sentences: {num_sentences}")
1980
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1981
+ return num_sentences < self._num_sentences_threshold
1982
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
1983
+ return num_sentences >= self._num_sentences_threshold
1984
+
1985
+
1986
+ class PlaceholderChecker(Instruction):
1987
+ """Check the placeholders in template writing."""
1988
+
1989
+ def build_description(self, *, num_placeholders=None):
1990
+ """Build the instruction description.
1991
+
1992
+ Args:
1993
+ num_placeholders: An integer denoting the minimum number of
1994
+ placeholders required in the response.
1995
+
1996
+ Returns:
1997
+ A string representing the instruction description.
1998
+ """
1999
+ self._num_placeholders = num_placeholders
2000
+ if self._num_placeholders is None or self._num_placeholders < 0:
2001
+ self._num_placeholders = random.randint(1, _NUM_PLACEHOLDERS)
2002
+ self._description_pattern = (
2003
+ 'The response must contain at least {num_placeholders} placeholders '
2004
+ + 'represented by square brackets, such as [address].'
2005
+ )
2006
+ return self._description_pattern.format(num_placeholders=self._num_placeholders)
2007
+
2008
+ def get_instruction_args(self):
2009
+ """Returns the keyward args of `build_description`."""
2010
+ return {'num_placeholders': self._num_placeholders}
2011
+
2012
+ def get_instruction_args_keys(self):
2013
+ """Returns the args keys of `build_description`."""
2014
+ return ['num_placeholders']
2015
+
2016
+ def check_following(self, value):
2017
+ """Check if the number of placeholders follows the instruction.
2018
+
2019
+ Args:
2020
+ value: A string representing the response.
2021
+
2022
+ Returns:
2023
+ True if the actual number of placeholders in the response is greater than
2024
+ or equal to `num_placeholders`; otherwise, False.
2025
+ """
2026
+ placeholders = re.findall(r'\[.*?\]', value)
2027
+ num_placeholders = len(placeholders)
2028
+ return num_placeholders >= self._num_placeholders
2029
+
2030
+
2031
+ class BulletListChecker(Instruction):
2032
+ """Checks the bullet list in the prompt."""
2033
+
2034
+ def build_description(self, *, num_bullets=None):
2035
+ """Build the instruction description.
2036
+
2037
+ Args:
2038
+ num_bullets: An integer specifying the exact number of bullet lists
2039
+ that is required to appear in the response.
2040
+
2041
+ Returns:
2042
+ A string representing the instruction description.
2043
+ """
2044
+ self._num_bullets = num_bullets
2045
+ if self._num_bullets is None or self._num_bullets < 0:
2046
+ self._num_bullets = random.randint(1, _NUM_BULLETS)
2047
+ self._description_pattern = (
2048
+ 'Your answer must contain exactly {num_bullets} bullet points. '
2049
+ + 'Use the markdown bullet points such as:\n' + '* This is point 1. \n' + '* This is point 2'
2050
+ )
2051
+ return self._description_pattern.format(num_bullets=self._num_bullets)
2052
+
2053
+ def get_instruction_args(self):
2054
+ """Returns the keyward args of `build_description`."""
2055
+ return {'num_bullets': self._num_bullets}
2056
+
2057
+ def get_instruction_args_keys(self):
2058
+ """Returns the args keys of `build_description`."""
2059
+ return ['num_bullets']
2060
+
2061
+ def check_following(self, value):
2062
+ r"""Check if the number of bullet lists meets the requirement.
2063
+
2064
+ Args:
2065
+ value: A string representing the response. The response is expected to
2066
+ contain some bullet lists that start with `\*`.
2067
+
2068
+ Returns:
2069
+ True if the actual number of bullet lists in the response meets the
2070
+ requirement.
2071
+ """
2072
+ bullet_lists = re.findall(r'^\s*\*[^\*].*$', value, flags=re.MULTILINE)
2073
+ bullet_lists_2 = re.findall(r'^\s*-.*$', value, flags=re.MULTILINE)
2074
+ num_bullet_lists = len(bullet_lists) + len(bullet_lists_2)
2075
+ return num_bullet_lists == self._num_bullets
2076
+
2077
+
2078
+ class ConstrainedResponseChecker(Instruction):
2079
+ """Checks the constrained response."""
2080
+
2081
+ def build_description(self):
2082
+ """Build the instruction description."""
2083
+ # A sequence of string(s) representing the options of the expected response.
2084
+ self._constrained_responses = _CONSTRAINED_RESPONSE_OPTIONS
2085
+ self._description_pattern = ('Answer with one of the following options: {response_options}')
2086
+ return self._description_pattern.format(response_options=self._constrained_responses)
2087
+
2088
+ def get_instruction_args(self):
2089
+ """Returns the keyward args of `build_description`."""
2090
+ return None
2091
+
2092
+ def get_instruction_args_keys(self):
2093
+ """Returns the args keys of `build_description`."""
2094
+ return []
2095
+
2096
+ def check_following(self, value):
2097
+ """Checks if the response matches the constrained options.
2098
+
2099
+ Args:
2100
+ value: A string representing the response.
2101
+
2102
+ Returns:
2103
+ True if the actual response contains one of the options in the constrained
2104
+ responses; otherwise False.
2105
+ """
2106
+ value = value.strip()
2107
+ for constrained_response in self._constrained_responses:
2108
+ if constrained_response in value:
2109
+ return True
2110
+ return False
2111
+
2112
+
2113
+ class ConstrainedStartChecker(Instruction):
2114
+ """Checks the response start."""
2115
+
2116
+ def build_description(self, *, starter=None):
2117
+ """Build the instruction description.
2118
+
2119
+ Args:
2120
+ starter: A string representing the keyward that the response should start
2121
+ with.
2122
+
2123
+ Returns:
2124
+ A string representing the instruction description.
2125
+ """
2126
+ self._starter = starter.strip() if isinstance(starter, str) else starter
2127
+ if self._starter is None:
2128
+ self._starter = random.choice(_STARTER_OPTIONS)
2129
+ self._description_pattern = (
2130
+ 'During the conversation, when it is your turn, ' + 'please always start with {starter}'
2131
+ )
2132
+ return self._description_pattern.format(starter=self._starter)
2133
+
2134
+ def get_instruction_args(self):
2135
+ """Returns the keyward args of `build_description`."""
2136
+ return {'starter': self._starter}
2137
+
2138
+ def get_instruction_args_keys(self):
2139
+ """Returns the args keys of `build_description`."""
2140
+ return ['starter']
2141
+
2142
+ def check_following(self, value):
2143
+ """Checks if the response starts with the constrained keyword or phrase.
2144
+
2145
+ Args:
2146
+ value: A string representing the response.
2147
+
2148
+ Returns:
2149
+ True if the response starts with the given phrase or keyword that is
2150
+ contained in `instruction_args`; otherwise, False.
2151
+ """
2152
+ response_pattern = r'^\s*' + self._starter + r'.*$'
2153
+ response_with_constrained_start = re.search(response_pattern, value, flags=re.MULTILINE)
2154
+ return True if response_with_constrained_start else False
2155
+
2156
+
2157
+ class HighlightSectionChecker(Instruction):
2158
+ """Checks the highlighted section."""
2159
+
2160
+ def build_description(self, *, num_highlights=None):
2161
+ """Build the instruction description.
2162
+
2163
+ Args:
2164
+ num_highlights: An integer specifying the minimum number of highlighted
2165
+ sections.
2166
+
2167
+ Returns:
2168
+ A string representing the instruction description.
2169
+ """
2170
+ self._num_highlights = num_highlights
2171
+ if self._num_highlights is None or self._num_highlights < 0:
2172
+ self._num_highlights = random.randint(1, _NUM_HIGHLIGHTED_SECTIONS)
2173
+
2174
+ self._description_pattern = (
2175
+ 'Highlight at least {num_highlights} sections in your answer with '
2176
+ + 'markdown, i.e. *highlighted section*.'
2177
+ )
2178
+
2179
+ return self._description_pattern.format(num_highlights=self._num_highlights)
2180
+
2181
+ def get_instruction_args(self):
2182
+ """Returns the keyward args of `build_description`."""
2183
+ return {'num_highlights': self._num_highlights}
2184
+
2185
+ def get_instruction_args_keys(self):
2186
+ """Returns the args keys of `build_description`."""
2187
+ return ['num_highlights']
2188
+
2189
+ def check_following(self, value):
2190
+ """Checks if the number of highlighted sections meets the requirement.
2191
+
2192
+ Args:
2193
+ value: a string repesenting the response. The response is expected to
2194
+ contain highlighted sections in the format of *highlighted*.
2195
+
2196
+ Returns:
2197
+ True if the actual number of highlighted sections in the format of
2198
+ *highlighed sections* meets the minimum requirement; otherwise False.
2199
+ """
2200
+ num_highlights = 0
2201
+ try:
2202
+ highlights = re.findall(r'\*[^\n\*]*\*', value)
2203
+ except:
2204
+ print('Failed for highlights, got value: ', value)
2205
+ return False
2206
+ double_highlights = re.findall(r'\*\*[^\n\*]*\*\*', value)
2207
+ for highlight in highlights:
2208
+ if highlight.strip('*').strip():
2209
+ num_highlights += 1
2210
+ for highlight in double_highlights:
2211
+ if highlight.removeprefix('**').removesuffix('**').strip():
2212
+ num_highlights += 1
2213
+
2214
+ return num_highlights >= self._num_highlights
2215
+
2216
+
2217
+ class SectionChecker(Instruction):
2218
+ """Checks the sections."""
2219
+
2220
+ def build_description(self, *, section_spliter=None, num_sections=None):
2221
+ """Build the instruction description.
2222
+
2223
+ Args:
2224
+ section_spliter: A string represents the section spliter keyword that
2225
+ marks a new section, i.e., `Section` or `SECTION`.
2226
+ num_sections: An integer specifying the number of sections.
2227
+
2228
+ Returns:
2229
+ A string representing the instruction description.
2230
+ """
2231
+ self._section_spliter = (section_spliter.strip() if isinstance(section_spliter, str) else section_spliter)
2232
+ if self._section_spliter is None:
2233
+ self._section_spliter = random.choice(_SECTION_SPLITER)
2234
+
2235
+ self._num_sections = num_sections
2236
+ if self._num_sections is None or self._num_sections < 0:
2237
+ self._num_sections = random.randint(1, _NUM_SECTIONS)
2238
+
2239
+ self._description_pattern = (
2240
+ 'Your response must have {num_sections} sections. Mark the beginning '
2241
+ + 'of each section with {section_spliter} X, such as:\n' + '{section_spliter} 1\n'
2242
+ + '[content of section 1]\n' + '{section_spliter} 2\n' + '[content of section 2]'
2243
+ )
2244
+
2245
+ return self._description_pattern.format(num_sections=self._num_sections, section_spliter=self._section_spliter)
2246
+
2247
+ def get_instruction_args(self):
2248
+ """Returns the keyward args of `build_description`."""
2249
+ return {
2250
+ 'section_spliter': self._section_spliter,
2251
+ 'num_sections': self._num_sections,
2252
+ }
2253
+
2254
+ def get_instruction_args_keys(self):
2255
+ """Returns the args keys of `build_description`."""
2256
+ return ['section_spliter', 'num_sections']
2257
+
2258
+ def check_following(self, value):
2259
+ """Checks the response contains multiple sections.
2260
+
2261
+ Args:
2262
+ value: A string representing the response. The response is expected
2263
+ to contain multiple sections (number of sections is greater than 1).
2264
+ A new section starts with `Section 1`, where the number denotes the
2265
+ section index.
2266
+
2267
+ Returns:
2268
+ True if the number of sections in the response is greater than or equal to
2269
+ the minimum number of sections; otherwise, False.
2270
+ """
2271
+ section_splitter_patten = r'\s?' + self._section_spliter + r'\s?\d+\s?'
2272
+ sections = re.split(section_splitter_patten, value)
2273
+ num_sections = len(sections) - 1
2274
+ return num_sections >= self._num_sections
2275
+
2276
+
2277
+ class ParagraphChecker(Instruction):
2278
+ """Checks the paragraphs."""
2279
+
2280
+ def build_description(self, *, num_paragraphs=None):
2281
+ """Build the instruction description.
2282
+
2283
+ Args:
2284
+ num_paragraphs: An integer specifying the number of paragraphs.
2285
+
2286
+ Returns:
2287
+ A string representing the instruction description.
2288
+ """
2289
+ self._num_paragraphs = num_paragraphs
2290
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
2291
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
2292
+
2293
+ self._description_pattern = (
2294
+ 'There should be {num_paragraphs} paragraphs. ' + 'Paragraphs are separated with the markdown divider: ***'
2295
+ )
2296
+
2297
+ return self._description_pattern.format(num_paragraphs=self._num_paragraphs)
2298
+
2299
+ def get_instruction_args(self):
2300
+ """Returns the keyward args of `build_description`."""
2301
+ return {'num_paragraphs': self._num_paragraphs}
2302
+
2303
+ def get_instruction_args_keys(self):
2304
+ """Returns the args keys of `build_description`."""
2305
+ return ['num_paragraphs']
2306
+
2307
+ def check_following(self, value):
2308
+ """Checks the response contains required number of paragraphs.
2309
+
2310
+ Args:
2311
+ value: A string representing the response. The response may contain
2312
+ paragraphs that are separated by the markdown divider: `***`.
2313
+
2314
+ Returns:
2315
+ True if the actual number of paragraphs is the same as required;
2316
+ otherwise, False.
2317
+ """
2318
+ paragraphs = re.split(r'\s?\*\*\*\s?', value)
2319
+ num_paragraphs = len(paragraphs)
2320
+
2321
+ for index, paragraph in enumerate(paragraphs):
2322
+ if not paragraph.strip():
2323
+ if index == 0 or index == len(paragraphs) - 1:
2324
+ num_paragraphs -= 1
2325
+ else:
2326
+ return False
2327
+
2328
+ return num_paragraphs == self._num_paragraphs
2329
+
2330
+
2331
+ class PostscriptChecker(Instruction):
2332
+ """Checks the postscript."""
2333
+
2334
+ def build_description(self, *, postscript_marker=None):
2335
+ """Build the instruction description.
2336
+
2337
+ Args:
2338
+ postscript_marker: A string containing the keyword that marks the start
2339
+ of the postscript section.
2340
+
2341
+ Returns:
2342
+ A string representing the instruction description.
2343
+ """
2344
+ self._postscript_marker = (
2345
+ postscript_marker.strip() if isinstance(postscript_marker, str) else postscript_marker
2346
+ )
2347
+ if self._postscript_marker is None:
2348
+ self._postscript_marker = random.choice(_POSTSCRIPT_MARKER)
2349
+
2350
+ self._description_pattern = (
2351
+ 'At the end of your response, please explicitly add a postscript ' + 'starting with {postscript}'
2352
+ )
2353
+
2354
+ return self._description_pattern.format(postscript=self._postscript_marker)
2355
+
2356
+ def get_instruction_args(self):
2357
+ """Returns the keyward args of `build_description`."""
2358
+ return {'postscript_marker': self._postscript_marker}
2359
+
2360
+ def get_instruction_args_keys(self):
2361
+ """Returns the args keys of `build_description`."""
2362
+ return ['postscript_marker']
2363
+
2364
+ def check_following(self, value):
2365
+ """Checks if the response follows the postscript format.
2366
+
2367
+ Args:
2368
+ value: a string representing the response. The response is expected to
2369
+ contain a postscript section.
2370
+
2371
+ Returns:
2372
+ True if the response contains a postscript section starting with
2373
+ the keyword containing in the `instruction_args`; otherwise False.
2374
+ """
2375
+ value = value.lower()
2376
+ if self._postscript_marker == 'P.P.S':
2377
+ postscript_pattern = r'\s*p\.\s?p\.\s?s.*$'
2378
+ elif self._postscript_marker == 'P.S.':
2379
+ postscript_pattern = r'\s*p\.\s?s\..*$'
2380
+ else:
2381
+ postscript_pattern = r'\s*' + self._postscript_marker.lower() + r'.*$'
2382
+ postscript = re.findall(postscript_pattern, value, flags=re.MULTILINE)
2383
+ return True if postscript else False
2384
+
2385
+
2386
+ class RephraseChecker(Instruction):
2387
+ """Checks the repharse."""
2388
+
2389
+ def build_description(self, *, original_message):
2390
+ """Build the instruction description.
2391
+
2392
+ Args:
2393
+ original_message: A string representing the original message. The
2394
+ rephrased response should only change its words/sentences in between
2395
+ its two asterisks, for example, *change me*. Both original and rephrased
2396
+ messages should contain the changes in the form of *change me*.
2397
+
2398
+ Returns:
2399
+ A string representing the instruction description.
2400
+ """
2401
+ if not self.is_change(original_message):
2402
+ raise ValueError(f'Message {original_message} does not contain changes '
2403
+ 'in the form of *change me*.')
2404
+
2405
+ self._reference_without_change = original_message
2406
+ self._description = (
2407
+ 'Rephrasing: Your rephrased response should only' + 'change the words/sentences in between two asterisks'
2408
+ + 'such as *change me*.'
2409
+ )
2410
+ return self._description
2411
+
2412
+ def get_instruction_args(self):
2413
+ """Returns the keyward args of `build_description`."""
2414
+ return {'original_message': self._reference_without_change}
2415
+
2416
+ def get_instruction_args_keys(self):
2417
+ """Returns the args keys of `build_description`."""
2418
+ return ['original_message']
2419
+
2420
+ def check_following(self, value):
2421
+ r"""Checks if the rephrasing follows the instruction.
2422
+
2423
+ Args:
2424
+ value: A string representing the response, which is expected to rephras
2425
+ the string of `instruction_args`.
2426
+
2427
+ Returns:
2428
+ True if `value` and `instruction_args` only differ by the words/sentences
2429
+ in between two asterisks such as *change me*; otherwise, False.
2430
+ """
2431
+
2432
+ if not self.is_change(value):
2433
+ raise ValueError(f'value {value} does not contain '
2434
+ 'changes in the form of *change me*.')
2435
+
2436
+ response_without_changes = self.strip_changes(value)
2437
+ reference_without_changes = self.strip_changes(self._reference_without_change)
2438
+
2439
+ return response_without_changes == reference_without_changes
2440
+
2441
+ def is_change(self, response):
2442
+ """Check if there is change in the response in the form of *change me*."""
2443
+ return re.search(r'\*.*\*', response)
2444
+
2445
+ def strip_changes(self, response):
2446
+ """Strips off the changes."""
2447
+ return re.sub(r'\*.*\*', '', response)
2448
+
2449
+
2450
+ class KeywordChecker(Instruction):
2451
+ """Check the exisitence of certain keywords."""
2452
+
2453
+ def build_description(self, *, keywords=None):
2454
+ """Build the instruction description.
2455
+
2456
+ Args:
2457
+ keywords: A sequence of strings representing the keywords that are
2458
+ expected in the response.
2459
+
2460
+ Returns:
2461
+ A string representing the instruction description.
2462
+ """
2463
+
2464
+ if not keywords:
2465
+ self._keywords = generate_keywords(num_keywords=_NUM_KEYWORDS)
2466
+ else:
2467
+ self._keywords = keywords
2468
+ self._keywords = sorted(self._keywords)
2469
+
2470
+ self._description_pattern = 'Include keywords {keywords} in the response.'
2471
+
2472
+ return self._description_pattern.format(keywords=self._keywords)
2473
+
2474
+ def get_instruction_args(self):
2475
+ """Returns the keyward args of `build_description`."""
2476
+ return {'keywords': self._keywords}
2477
+
2478
+ def get_instruction_args_keys(self):
2479
+ """Returns the args keys of `build_description`."""
2480
+ return ['keywords']
2481
+
2482
+ def check_following(self, value):
2483
+ """Check if the response contain the expected keywords."""
2484
+ for keyword in self._keywords:
2485
+ if not re.search(keyword, value, flags=re.IGNORECASE):
2486
+ return False
2487
+ return True
2488
+
2489
+
2490
+ class KeywordFrequencyChecker(Instruction):
2491
+ """Check the keyword frequency."""
2492
+
2493
+ def build_description(self, *, keyword=None, frequency=None, relation=None):
2494
+ """Build the instruction description.
2495
+
2496
+ Args:
2497
+ keyword: A string representing a keyword that is expected in the response.
2498
+ frequency: An integer specifying the number of times `keyword` is expected
2499
+ to appear in the response.
2500
+ relation: A string in (`less than`, `at least`), defining the relational
2501
+ operator for comparison.
2502
+ Two relational comparisons are supported for now:
2503
+ if 'less than', the actual number of occurrences < frequency;
2504
+ if 'at least', the actual number of occurrences >= frequency.
2505
+
2506
+ Returns:
2507
+ A string representing the instruction description.
2508
+ """
2509
+ if not keyword:
2510
+ self._keyword = generate_keywords(num_keywords=1)[0]
2511
+ else:
2512
+ self._keyword = keyword.strip()
2513
+
2514
+ self._frequency = frequency
2515
+ if self._frequency is None or self._frequency < 0:
2516
+ self._frequency = random.randint(1, _KEYWORD_FREQUENCY)
2517
+
2518
+ if relation is None:
2519
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
2520
+ elif relation not in _COMPARISON_RELATION:
2521
+ raise ValueError(
2522
+ 'The supported relation for comparison must be in '
2523
+ f'{_COMPARISON_RELATION}, but {relation} is given.'
2524
+ )
2525
+ else:
2526
+ self._comparison_relation = relation
2527
+
2528
+ self._description_pattern = (
2529
+ 'In your response, the word {keyword} should appear {relation} ' + '{frequency} times.'
2530
+ )
2531
+
2532
+ return self._description_pattern.format(
2533
+ keyword=self._keyword,
2534
+ relation=self._comparison_relation,
2535
+ frequency=self._frequency,
2536
+ )
2537
+
2538
+ def get_instruction_args(self):
2539
+ """Returns the keyward args of `build_description`."""
2540
+ return {
2541
+ 'keyword': self._keyword,
2542
+ 'frequency': self._frequency,
2543
+ 'relation': self._comparison_relation,
2544
+ }
2545
+
2546
+ def get_instruction_args_keys(self):
2547
+ """Returns the args keys of `build_description`."""
2548
+ return ['keyword', 'frequency', 'relation']
2549
+
2550
+ def check_following(self, value):
2551
+ """Checks if the response contain the keyword with required frequency."""
2552
+ try:
2553
+ actual_occurrences = len(re.findall(self._keyword, value, flags=re.IGNORECASE))
2554
+ except:
2555
+ print('Failed to parse for', value)
2556
+ return False
2557
+
2558
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
2559
+ return actual_occurrences < self._frequency
2560
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
2561
+ return actual_occurrences >= self._frequency
2562
+
2563
+
2564
+ class NumberOfWords(Instruction):
2565
+ """Checks the number of words."""
2566
+
2567
+ def build_description(self, *, num_words=None, relation=None):
2568
+ """Build the instruction description.
2569
+
2570
+ Args:
2571
+ num_words: An integer specifying the number of words contained in the
2572
+ response.
2573
+ relation: A string in (`less than`, `at least`), defining the relational
2574
+ operator for comparison.
2575
+ Two relational comparisons are supported for now:
2576
+ if 'less than', the actual number of words < num_words;
2577
+ if 'at least', the actual number of words >= num_words.
2578
+
2579
+ Returns:
2580
+ A string representing the instruction description.
2581
+ """
2582
+
2583
+ self._num_words = num_words
2584
+ if self._num_words is None or self._num_words < 0:
2585
+ self._num_words = random.randint(_NUM_WORDS_LOWER_LIMIT, _NUM_WORDS_UPPER_LIMIT)
2586
+
2587
+ if relation is None:
2588
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
2589
+ elif relation not in _COMPARISON_RELATION:
2590
+ raise ValueError(
2591
+ 'The supported relation for comparison must be in '
2592
+ f'{_COMPARISON_RELATION}, but {relation} is given.'
2593
+ )
2594
+ else:
2595
+ self._comparison_relation = relation
2596
+
2597
+ self._description_pattern = 'Answer with {relation} {num_words} words.'
2598
+
2599
+ return self._description_pattern.format(relation=self._comparison_relation, num_words=self._num_words)
2600
+
2601
+ def get_instruction_args(self):
2602
+ """Returns the keyward args of `build_description`."""
2603
+ return {'num_words': self._num_words, 'relation': self._comparison_relation}
2604
+
2605
+ def get_instruction_args_keys(self):
2606
+ """Returns the args keys of `build_description`."""
2607
+ return ['num_words', 'relation']
2608
+
2609
+ def check_following(self, value):
2610
+ """Checks if the response contains the expected number of words."""
2611
+ try:
2612
+ lang = langdetect.detect(value)
2613
+ except:
2614
+ print('Failed to detect language, got value:', value)
2615
+ lang = 'en'
2616
+ if lang == 'th':
2617
+ from pythainlp.tokenize import word_tokenize as word_tokenize_thai
2618
+
2619
+ # print(f"shervin4. lang is {lang}")
2620
+ # print(value)
2621
+ num_words = len(word_tokenize_thai(value))
2622
+ # print(f"num words: {num_words}")
2623
+ elif lang in ['zh', 'zh-cn', 'zh-tw', 'ja']:
2624
+ # print(f"shervin5. lang is {lang}")
2625
+ # print(value)
2626
+ num_words = count_words_chinese_japanese(value)
2627
+ # print(f"num words: {num_words}")
2628
+ else:
2629
+ # print(f"shervin6. lang is {lang}")
2630
+ # print(value)
2631
+ num_words = count_words(value)
2632
+ # print(f"num words: {num_words}")
2633
+
2634
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
2635
+ return num_words < self._num_words
2636
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
2637
+ return num_words >= self._num_words
2638
+
2639
+
2640
+ class JsonFormat(Instruction):
2641
+ """Check the Json format."""
2642
+
2643
+ def build_description(self):
2644
+ self._description_pattern = (
2645
+ 'Entire output should be wrapped in JSON format. You can use markdown'
2646
+ ' ticks such as ```.'
2647
+ )
2648
+ return self._description_pattern
2649
+
2650
+ def get_instruction_args(self):
2651
+ """Returns the keyward args of `build_description`."""
2652
+ return None
2653
+
2654
+ def get_instruction_args_keys(self):
2655
+ """Returns the args keys of `build_description`."""
2656
+ return []
2657
+
2658
+ def check_following(self, value):
2659
+ value = (
2660
+ value.strip().removeprefix('```json').removeprefix('```Json').removeprefix('```JSON').removeprefix('```').
2661
+ removesuffix('```').strip()
2662
+ )
2663
+ try:
2664
+ json.loads(value)
2665
+ except ValueError as _:
2666
+ return False
2667
+ return True
2668
+
2669
+
2670
+ class ParagraphFirstWordCheck(Instruction):
2671
+ """Check the paragraph and the first word of the nth paragraph."""
2672
+
2673
+ def build_description(self, num_paragraphs=None, nth_paragraph=None, first_word=None):
2674
+ r"""Build the instruction description.
2675
+
2676
+ Args:
2677
+ num_paragraphs: An integer indicating the number of paragraphs expected
2678
+ in the response. A paragraph is a subset of the string that is
2679
+ expected to be separated by '\n\n'.
2680
+ nth_paragraph: An integer indicating the paragraph number that we look at.
2681
+ Note that n starts from 1.
2682
+ first_word: A string that represent the first word of the bth paragraph.
2683
+
2684
+ Returns:
2685
+ A string representing the instruction description.
2686
+ """
2687
+ self._num_paragraphs = num_paragraphs
2688
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
2689
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
2690
+
2691
+ self._nth_paragraph = nth_paragraph
2692
+ if (self._nth_paragraph is None or self._nth_paragraph <= 0 or self._nth_paragraph > self._num_paragraphs):
2693
+ self._nth_paragraph = random.randint(1, self._num_paragraphs + 1)
2694
+
2695
+ self._first_word = first_word
2696
+ if self._first_word is None:
2697
+ self._first_word = generate_keywords(num_keywords=1)[0]
2698
+ self._first_word = self._first_word.lower()
2699
+
2700
+ self._description_pattern = (
2701
+ 'There should be {num_paragraphs} paragraphs. '
2702
+ + 'Paragraphs and only paragraphs are separated with each other by two '
2703
+ + "new lines as if it was '\\n\\n' in python. "
2704
+ + 'Paragraph {nth_paragraph} must start with word {first_word}.'
2705
+ )
2706
+
2707
+ return self._description_pattern.format(
2708
+ num_paragraphs=self._num_paragraphs,
2709
+ nth_paragraph=self._nth_paragraph,
2710
+ first_word=self._first_word,
2711
+ )
2712
+
2713
+ def get_instruction_args(self):
2714
+ """Returns the keyward args of `build_description`."""
2715
+ return {
2716
+ 'num_paragraphs': self._num_paragraphs,
2717
+ 'nth_paragraph': self._nth_paragraph,
2718
+ 'first_word': self._first_word,
2719
+ }
2720
+
2721
+ def get_instruction_args_keys(self):
2722
+ """Returns the args keys of `build_description`."""
2723
+ return ['num_paragraphs', 'nth_paragraph', 'first_word']
2724
+
2725
+ def check_following(self, value):
2726
+ """Checks for required number of paragraphs and correct first word.
2727
+
2728
+ Args:
2729
+ value: a string representing the response. The response may contain
2730
+ paragraphs that are separated by two new lines and the first word of
2731
+ the nth paragraph will have to match a specified word.
2732
+
2733
+ Returns:
2734
+ True if the number of paragraphs is the same as required and the first
2735
+ word of the specified paragraph is the same as required. Otherwise, false.
2736
+ """
2737
+
2738
+ paragraphs = re.split(r'\n\n', value)
2739
+ num_paragraphs = len(paragraphs)
2740
+
2741
+ for paragraph in paragraphs:
2742
+ if not paragraph.strip():
2743
+ num_paragraphs -= 1
2744
+
2745
+ # check that index doesn't go out of bounds
2746
+ if self._nth_paragraph <= num_paragraphs:
2747
+ paragraph = paragraphs[self._nth_paragraph - 1].strip()
2748
+ if not paragraph:
2749
+ return False
2750
+ else:
2751
+ return False
2752
+
2753
+ first_word = ''
2754
+ punctuation = {'.', ',', '?', '!', "'", '"'}
2755
+
2756
+ # get first word and remove punctuation
2757
+ word = paragraph.split()[0].strip()
2758
+ # TODO(jeffrey): make more complex?
2759
+ word = word.lstrip("'")
2760
+ word = word.lstrip('"')
2761
+
2762
+ for letter in word:
2763
+ if letter in punctuation:
2764
+ break
2765
+ first_word += letter.lower()
2766
+
2767
+ return num_paragraphs == self._num_paragraphs and first_word == self._first_word
2768
+
2769
+
2770
+ # TODO(jeffrey) add relation - at least/at most?
2771
+ class KeySentenceChecker(Instruction):
2772
+ """Check the existence of certain key sentences."""
2773
+
2774
+ def build_description(self, key_sentences=None, num_sentences=None):
2775
+ """Build the instruction description.
2776
+
2777
+ Args:
2778
+ key_sentences: A sequences of strings representing the key sentences that
2779
+ are expected in the response.
2780
+ num_sentences: The number of key sentences that are expected to be seen in
2781
+ the response.
2782
+
2783
+ Returns:
2784
+ A string representing the instruction description.
2785
+ """
2786
+
2787
+ if not key_sentences:
2788
+ # TODO(jeffrey) make a generate sentences function? wonderwords package
2789
+ self._key_sentences = set(['For now, this is fine.'])
2790
+ else:
2791
+ self._key_sentences = key_sentences
2792
+
2793
+ if not num_sentences:
2794
+ self._num_sentences = random.randint(1, len(self._key_sentences))
2795
+ else:
2796
+ self._num_sentences = num_sentences
2797
+
2798
+ self._description_pattern = ('Include {num_sentences} of the following sentences {key_sentences}')
2799
+
2800
+ return self._description_pattern.format(num_sentences=self._num_sentences, key_sentences=self._key_sentences)
2801
+
2802
+ def get_instruction_args(self):
2803
+ """Returns the keyward args of `build_description`."""
2804
+ return {
2805
+ 'num_sentences': self._num_sentences,
2806
+ 'key_sentences': list(self._key_sentences),
2807
+ }
2808
+
2809
+ def get_instruction_args_keys(self):
2810
+ """Returns the args keys of `build_description`."""
2811
+ return ['num_sentences', 'key_sentences']
2812
+
2813
+ def check_following(self, value):
2814
+ """Checks if the response contains the expected key sentences."""
2815
+ count = 0
2816
+ sentences = split_into_sentences(value)
2817
+ for sentence in self._key_sentences:
2818
+ if sentence in sentences:
2819
+ count += 1
2820
+
2821
+ return count == self._num_sentences
2822
+
2823
+
2824
+ class ForbiddenWords(Instruction):
2825
+ """Checks that specified words are not used in response."""
2826
+
2827
+ def build_description(self, forbidden_words=None):
2828
+ """Build the instruction description.
2829
+
2830
+ Args:
2831
+ forbidden_words: A sequences of strings respresenting words that are not
2832
+ allowed in the response.
2833
+
2834
+ Returns:
2835
+ A string representing the instruction description.
2836
+ """
2837
+
2838
+ if not forbidden_words:
2839
+ self._forbidden_words = generate_keywords(num_keywords=_NUM_KEYWORDS)
2840
+ else:
2841
+ self._forbidden_words = list(set(forbidden_words))
2842
+ self._forbidden_words = sorted(self._forbidden_words)
2843
+ self._description_pattern = ('Do not include keywords {forbidden_words} in the response.')
2844
+
2845
+ return self._description_pattern.format(forbidden_words=self._forbidden_words)
2846
+
2847
+ def get_instruction_args(self):
2848
+ """Returns the keyward args of `build_description`."""
2849
+ return {'forbidden_words': self._forbidden_words}
2850
+
2851
+ def get_instruction_args_keys(self):
2852
+ """Returns the args keys of `build_description`."""
2853
+ return ['forbidden_words']
2854
+
2855
+ def check_following(self, value):
2856
+ """Check if the response does not contain the expected keywords."""
2857
+ for word in self._forbidden_words:
2858
+ if re.search(r'\b' + word + r'\b', value, flags=re.IGNORECASE):
2859
+ return False
2860
+ return True
2861
+
2862
+
2863
+ class RephraseParagraph(Instruction):
2864
+ """Checks that the paragraph is rephrased."""
2865
+
2866
+ def build_description(self, *, original_paragraph, low, high):
2867
+ """Builds the instruction description.
2868
+
2869
+ Args:
2870
+ original_paragraph: A string presenting the original paragraph. The
2871
+ rephrases response should have betweeb low-high words in common.
2872
+ low: An integer presenting the lower bound of similar words.
2873
+ high: An integer representing the upper bound of similar words.
2874
+
2875
+ Returns:
2876
+ A string representing the instruction description.
2877
+ """
2878
+ # TODO(jeffrey) make more encompassing
2879
+ self._original_paragraph = original_paragraph
2880
+ self._low = low
2881
+ self._high = high
2882
+
2883
+ self._description = (
2884
+ 'Rephrase the following paragraph: ' + '{original_paragraph}\nYour response should have '
2885
+ + 'between {low} and {high} of the same words. ' + 'Words are the same if and only if all of the '
2886
+ + 'letters, ignoring cases, are the same. For ' + "example, 'run' is the same as 'Run' but different "
2887
+ + "to 'ran'."
2888
+ )
2889
+
2890
+ return self._description.format(original_paragraph=original_paragraph, low=self._low, high=self._high)
2891
+
2892
+ def get_instruction_args(self):
2893
+ """Returns the keyward args of `build_description`."""
2894
+ return {
2895
+ 'original_paragraph': self._original_paragraph,
2896
+ 'low': self._low,
2897
+ 'high': self._high,
2898
+ }
2899
+
2900
+ def get_instruction_args_keys(self):
2901
+ """Returns the args keys of `build_description`."""
2902
+ return ['original_paragraph', 'low', 'high']
2903
+
2904
+ def check_following(self, value):
2905
+ val_words = re.findall(r'\w+', value.lower())
2906
+ original_words = re.findall(r'\w+', self._original_paragraph.lower())
2907
+ similar_words = 0
2908
+
2909
+ dict_val = collections.Counter(val_words)
2910
+ dict_original = collections.Counter(original_words)
2911
+
2912
+ for word in dict_original:
2913
+ similar_words += min(dict_original[word], dict_val[word])
2914
+
2915
+ return similar_words >= self._low and similar_words <= self._high
2916
+
2917
+
2918
+ class TwoResponsesChecker(Instruction):
2919
+ """Check that two responses were given."""
2920
+
2921
+ def build_description(self):
2922
+ """Build the instruction description."""
2923
+ self._description_pattern = (
2924
+ 'Give two different responses. Responses and only responses should'
2925
+ ' be separated by 6 asterisk symbols: ******.'
2926
+ )
2927
+ return self._description_pattern
2928
+
2929
+ def get_instruction_args(self):
2930
+ """Returns the keyward args of `build_description`."""
2931
+ return None
2932
+
2933
+ def get_instruction_args_keys(self):
2934
+ """Returns the args keys of `build_description`."""
2935
+ return []
2936
+
2937
+ def check_following(self, value):
2938
+ """Checks if the response has two different answers.
2939
+
2940
+ Args:
2941
+ value: A string representing the response.
2942
+
2943
+ Returns:
2944
+ True if two responses are detected and false otherwise.
2945
+ """
2946
+ valid_responses = list()
2947
+ responses = value.split('******')
2948
+ for index, response in enumerate(responses):
2949
+ if not response.strip():
2950
+ if index != 0 and index != len(responses) - 1:
2951
+ return False
2952
+ else:
2953
+ valid_responses.append(response)
2954
+ return (len(valid_responses) == 2 and valid_responses[0].strip() != valid_responses[1].strip())
2955
+
2956
+
2957
+ class RepeatPromptThenAnswer(Instruction):
2958
+ """Checks that Prompt is first repeated then answered."""
2959
+
2960
+ def build_description(self, *, prompt_to_repeat=None):
2961
+ """Build the instruction description.
2962
+
2963
+ Args:
2964
+ prompt_to_repeat: The prompt that is meant to be repeated.
2965
+
2966
+ Returns:
2967
+ A string representing the instruction description.
2968
+ """
2969
+ if not prompt_to_repeat:
2970
+ raise ValueError('prompt_to_repeat must be set.')
2971
+ else:
2972
+ self._prompt_to_repeat = prompt_to_repeat
2973
+ self._description_pattern = (
2974
+ 'First repeat the request word for word without change,'
2975
+ ' then give your answer (1. do not say any words or characters'
2976
+ ' before repeating the request; 2. the request you need to repeat'
2977
+ ' does not include this sentence)'
2978
+ )
2979
+ return self._description_pattern
2980
+
2981
+ def get_instruction_args(self):
2982
+ return {'prompt_to_repeat': self._prompt_to_repeat}
2983
+
2984
+ def get_instruction_args_keys(self):
2985
+ """Returns the args keys of `build_description`."""
2986
+ return ['prompt_to_repeat']
2987
+
2988
+ def check_following(self, value):
2989
+ if value.strip().lower().startswith(self._prompt_to_repeat.strip().lower()):
2990
+ return True
2991
+ return False
2992
+
2993
+
2994
+ class EndChecker(Instruction):
2995
+ """Checks that the prompt ends with a given phrase."""
2996
+
2997
+ def build_description(self, *, end_phrase=None):
2998
+ """Build the instruction description.
2999
+
3000
+ Args:
3001
+ end_phrase: A string representing the phrase the response should end with.
3002
+
3003
+ Returns:
3004
+ A string representing the instruction description.
3005
+ """
3006
+ self._end_phrase = (end_phrase.strip() if isinstance(end_phrase, str) else end_phrase)
3007
+ if self._end_phrase is None:
3008
+ self._end_phrase = random.choice(_ENDING_OPTIONS)
3009
+ self._description_pattern = (
3010
+ 'Finish your response with this exact phrase {ender}. '
3011
+ 'No other words should follow this phrase.'
3012
+ )
3013
+ return self._description_pattern.format(ender=self._end_phrase)
3014
+
3015
+ def get_instruction_args(self):
3016
+ return {'end_phrase': self._end_phrase}
3017
+
3018
+ def get_instruction_args_keys(self):
3019
+ """Returns the args keys of `build_description`."""
3020
+ return ['end_phrase']
3021
+
3022
+ def check_following(self, value):
3023
+ """Checks if the response ends with the expected phrase."""
3024
+ value = value.strip().strip('"').lower()
3025
+ self._end_phrase = self._end_phrase.strip().lower()
3026
+ return value.endswith(self._end_phrase)
3027
+
3028
+
3029
+ class TitleChecker(Instruction):
3030
+ """Checks the response for a title."""
3031
+
3032
+ def build_description(self):
3033
+ """Build the instruction description."""
3034
+ self._description_pattern = (
3035
+ 'Your answer must contain a title, wrapped in double angular brackets,'
3036
+ ' such as <<poem of joy>>.'
3037
+ )
3038
+ return self._description_pattern
3039
+
3040
+ def get_instruction_args(self):
3041
+ return None
3042
+
3043
+ def get_instruction_args_keys(self):
3044
+ """Returns the args keys of `build_description`."""
3045
+ return []
3046
+
3047
+ def check_following(self, value):
3048
+ """Checks if the response contains a title."""
3049
+ pattern = r'<<[^\n]+>>'
3050
+ re_pattern = re.compile(pattern)
3051
+ titles = re.findall(re_pattern, value)
3052
+
3053
+ for title in titles:
3054
+ if title.lstrip('<').rstrip('>').strip():
3055
+ return True
3056
+ return False
3057
+
3058
+
3059
+ class LetterFrequencyChecker(Instruction):
3060
+ """Checks letter frequency."""
3061
+
3062
+ def build_description(self, *, letter=None, let_frequency=None, let_relation=None):
3063
+ """Build the instruction description.
3064
+
3065
+ Args:
3066
+ letter: A string representing a letter that is expected in the response.
3067
+ let_frequency: An integer specifying the number of times `keyword` is
3068
+ expected to appear in the response.
3069
+ let_relation: A string in (`less than`, `at least`), defining the
3070
+ relational operator for comparison. Two relational comparisons are
3071
+ supported for now; if 'less than', the actual number of
3072
+ occurrences < frequency; if 'at least', the actual number of
3073
+ occurrences >= frequency.
3074
+
3075
+ Returns:
3076
+ A string representing the instruction description.
3077
+ """
3078
+ if (not letter or len(letter) > 1 or ord(letter.lower()) < 97 or ord(letter.lower()) > 122):
3079
+ self._letter = random.choice(list(string.ascii_letters))
3080
+ else:
3081
+ self._letter = letter.strip()
3082
+ self._letter = self._letter.lower()
3083
+
3084
+ self._frequency = let_frequency
3085
+ if self._frequency is None or self._frequency < 0:
3086
+ self._frequency = random.randint(1, _LETTER_FREQUENCY)
3087
+
3088
+ if let_relation is None:
3089
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
3090
+ elif let_relation not in _COMPARISON_RELATION:
3091
+ raise ValueError(
3092
+ 'The supported relation for comparison must be in '
3093
+ f'{_COMPARISON_RELATION}, but {let_relation} is given.'
3094
+ )
3095
+ else:
3096
+ self._comparison_relation = let_relation
3097
+
3098
+ self._description_pattern = (
3099
+ 'In your response, the letter {letter} should appear {let_relation}'
3100
+ ' {let_frequency} times.'
3101
+ )
3102
+
3103
+ return self._description_pattern.format(
3104
+ letter=self._letter,
3105
+ let_frequency=self._frequency,
3106
+ let_relation=self._comparison_relation,
3107
+ )
3108
+
3109
+ def get_instruction_args(self):
3110
+ """Returns the keyword args of build description."""
3111
+ return {
3112
+ 'letter': self._letter,
3113
+ 'let_frequency': self._frequency,
3114
+ 'let_relation': self._comparison_relation,
3115
+ }
3116
+
3117
+ def get_instruction_args_keys(self):
3118
+ """Returns the args keys of `build_description`."""
3119
+ return ['letter', 'let_frequency', 'let_relation']
3120
+
3121
+ def check_following(self, value):
3122
+ """Checks that the response contains the letter at the right frequency."""
3123
+ value = value.lower()
3124
+ letters = collections.Counter(value)
3125
+
3126
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
3127
+ return letters[self._letter] < self._frequency
3128
+ else:
3129
+ return letters[self._letter] >= self._frequency
3130
+
3131
+
3132
+ class CapitalLettersEnglishChecker(Instruction):
3133
+ """Checks that the response is in english and is in all capital letters."""
3134
+
3135
+ def build_description(self):
3136
+ """Build the instruction description."""
3137
+ self._description_pattern = ('Your entire response should be in English, and in all capital letters.')
3138
+ return self._description_pattern
3139
+
3140
+ def get_instruction_args(self):
3141
+ return None
3142
+
3143
+ def get_instruction_args_keys(self):
3144
+ """Returns the args keys of `build_description`."""
3145
+ return []
3146
+
3147
+ def check_following(self, value):
3148
+ """Checks that the response is in English and in all capital letters."""
3149
+ assert isinstance(value, str)
3150
+
3151
+ try:
3152
+ return value.isupper() and langdetect.detect(value) == 'en'
3153
+ except langdetect.LangDetectException as e:
3154
+ # Count as instruction is followed.
3155
+ logger.info('Unable to detect language for text %s due to %s', value, e) # refex: disable=pytotw.037
3156
+ return True
3157
+
3158
+
3159
+ class LowercaseLettersEnglishChecker(Instruction):
3160
+ """Checks that the response is in english and is in all lowercase letters."""
3161
+
3162
+ def build_description(self):
3163
+ """Build the instruction description."""
3164
+ self._description_pattern = (
3165
+ 'Your entire response should be in English, and in all lowercase'
3166
+ ' letters. No capital letters are allowed.'
3167
+ )
3168
+ return self._description_pattern
3169
+
3170
+ def get_instruction_args(self):
3171
+ return None
3172
+
3173
+ def get_instruction_args_keys(self):
3174
+ """Returns the args keys of `build_description`."""
3175
+ return []
3176
+
3177
+ def check_following(self, value):
3178
+ """Checks that the response is in English and in all lowercase letters."""
3179
+ assert isinstance(value, str)
3180
+
3181
+ try:
3182
+ return value.islower() and langdetect.detect(value) == 'en'
3183
+ except langdetect.LangDetectException as e:
3184
+ # Count as instruction is followed.
3185
+ logger.info('Unable to detect language for text %s due to %s', value, e) # refex: disable=pytotw.037
3186
+ return True
3187
+
3188
+
3189
+ class CommaChecker(Instruction):
3190
+ """Checks the response for no commas."""
3191
+
3192
+ def build_description(self):
3193
+ """Build the instruction description."""
3194
+ self._description_pattern = ('In your entire response, refrain from the use of any commas.')
3195
+ return self._description_pattern
3196
+
3197
+ def get_instruction_args(self):
3198
+ return None
3199
+
3200
+ def get_instruction_args_keys(self):
3201
+ """Returns the args keys of `build_description`."""
3202
+ return []
3203
+
3204
+ def check_following(self, value):
3205
+ """Checks that the response does not contain commas."""
3206
+ return not re.search(r'\,', value)
3207
+
3208
+
3209
+ class CapitalWordFrequencyChecker(Instruction):
3210
+ """Checks frequency of words with all capital letters."""
3211
+
3212
+ def build_description(
3213
+ self,
3214
+ capital_frequency=None,
3215
+ capital_relation=None,
3216
+ ):
3217
+ """Build the instruction description.
3218
+
3219
+ Args:
3220
+ capital_frequency: An integer that represents the number of words that
3221
+ should be in all capital letters.
3222
+ capital_relation: A string that is 'at least' or 'at most' that refers to
3223
+ the frequency.
3224
+
3225
+ Returns:
3226
+ A string representing the instruction description.
3227
+ """
3228
+ self._frequency = capital_frequency
3229
+ if self._frequency is None:
3230
+ self._frequency = random.randint(1, _ALL_CAPITAL_WORD_FREQUENCY)
3231
+
3232
+ self._comparison_relation = capital_relation
3233
+ if capital_relation is None:
3234
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
3235
+ elif capital_relation not in _COMPARISON_RELATION:
3236
+ raise ValueError(
3237
+ 'The supported relation for comparison must be in '
3238
+ f'{_COMPARISON_RELATION}, but {capital_relation} is given.'
3239
+ )
3240
+
3241
+ self._description_pattern = (
3242
+ 'In your response, words with all capital letters should appear'
3243
+ ' {relation} {frequency} times.'
3244
+ )
3245
+
3246
+ return self._description_pattern.format(frequency=self._frequency, relation=self._comparison_relation)
3247
+
3248
+ def get_instruction_args(self):
3249
+ """Returns the keyword args of build description."""
3250
+ return {
3251
+ 'capital_frequency': self._frequency,
3252
+ 'capital_relation': self._comparison_relation,
3253
+ }
3254
+
3255
+ def get_instruction_args_keys(self):
3256
+ """Returns the args keys of `build_description`."""
3257
+ return ['capital_frequency', 'capital_relation']
3258
+
3259
+ def check_following(self, value):
3260
+ """Checks the frequency of words with all capital letters."""
3261
+ # Hyphenated words will count as one word
3262
+ words = nltk.word_tokenize(value)
3263
+ capital_words = [word for word in words if word.isupper()]
3264
+
3265
+ capital_words = len(capital_words)
3266
+
3267
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
3268
+ return capital_words < self._frequency
3269
+ else:
3270
+ return capital_words >= self._frequency
3271
+
3272
+
3273
+ class QuotationChecker(Instruction):
3274
+ """Checks response is wrapped with double quotation marks."""
3275
+
3276
+ def build_description(self):
3277
+ """Build the instruction description."""
3278
+ self._description_pattern = ('Wrap your entire response with double quotation marks.')
3279
+ return self._description_pattern
3280
+
3281
+ def get_instruction_args(self):
3282
+ """Returns the keyword args of build description."""
3283
+ return None
3284
+
3285
+ def get_instruction_args_keys(self):
3286
+ """Returns the args keys of `build_description`."""
3287
+ return []
3288
+
3289
+ def check_following(self, value):
3290
+ """Checks if the response is wrapped with double quotation marks."""
3291
+ value = value.strip()
3292
+ return len(value) > 1 and (
3293
+ value[0] == '"' and value[-1] == '"' or # e.g., English
3294
+ value[0] == '“' and value[-1] == '”' or # e.g., Chinese
3295
+ value[0] == '「' and value[-1] == '」'
3296
+ ) # e.g., Japanese
3297
+
3298
+
3299
+ # Define instruction dicts
3300
+ _KEYWORD = 'keywords:'
3301
+ _LANGUAGE = 'language:'
3302
+ _LENGTH = 'length_constraints:'
3303
+ _CONTENT = 'detectable_content:'
3304
+ _FORMAT = 'detectable_format:'
3305
+ _MULTITURN = 'multi-turn:'
3306
+ _COMBINATION = 'combination:'
3307
+ _STARTEND = 'startend:'
3308
+ _CHANGE_CASES = 'change_case:'
3309
+ _PUNCTUATION = 'punctuation:'
3310
+
3311
+ INSTRUCTION_DICT = {
3312
+ _KEYWORD + 'existence': KeywordChecker,
3313
+ _KEYWORD + 'frequency': KeywordFrequencyChecker,
3314
+ # _KEYWORD + "key_sentences": KeySentenceChecker,
3315
+ _KEYWORD + 'forbidden_words': ForbiddenWords,
3316
+ _KEYWORD + 'letter_frequency': LetterFrequencyChecker,
3317
+ _LANGUAGE + 'response_language': ResponseLanguageChecker,
3318
+ _LENGTH + 'number_sentences': NumberOfSentences,
3319
+ _LENGTH + 'number_paragraphs': ParagraphChecker,
3320
+ _LENGTH + 'number_words': NumberOfWords,
3321
+ _LENGTH + 'nth_paragraph_first_word': ParagraphFirstWordCheck,
3322
+ _CONTENT + 'number_placeholders': PlaceholderChecker,
3323
+ _CONTENT + 'postscript': PostscriptChecker,
3324
+ _FORMAT + 'number_bullet_lists': BulletListChecker,
3325
+ # _CONTENT + "rephrase_paragraph": RephraseParagraph,
3326
+ _FORMAT + 'constrained_response': ConstrainedResponseChecker,
3327
+ _FORMAT + 'number_highlighted_sections': (HighlightSectionChecker),
3328
+ _FORMAT + 'multiple_sections': SectionChecker,
3329
+ # _FORMAT + "rephrase": RephraseChecker,
3330
+ _FORMAT + 'json_format': JsonFormat,
3331
+ _FORMAT + 'title': TitleChecker,
3332
+ # _MULTITURN + "constrained_start": ConstrainedStartChecker,
3333
+ _COMBINATION + 'two_responses': TwoResponsesChecker,
3334
+ _COMBINATION + 'repeat_prompt': RepeatPromptThenAnswer,
3335
+ _STARTEND + 'end_checker': EndChecker,
3336
+ _CHANGE_CASES + 'capital_word_frequency': CapitalWordFrequencyChecker,
3337
+ _CHANGE_CASES + 'english_capital': CapitalLettersEnglishChecker,
3338
+ _CHANGE_CASES + 'english_lowercase': LowercaseLettersEnglishChecker,
3339
+ _PUNCTUATION + 'no_comma': CommaChecker,
3340
+ _STARTEND + 'quotation': QuotationChecker,
3341
+ }
3342
+
3343
+ INSTRUCTION_LIST = list(INSTRUCTION_DICT.keys()) + [
3344
+ _KEYWORD[:-1],
3345
+ _LANGUAGE[:-1],
3346
+ _LENGTH[:-1],
3347
+ _CONTENT[:-1],
3348
+ _FORMAT[:-1],
3349
+ _MULTITURN[:-1],
3350
+ _COMBINATION[:-1],
3351
+ _STARTEND[:-1],
3352
+ _CHANGE_CASES[:-1],
3353
+ _PUNCTUATION[:-1],
3354
+ ]