Matheel 0.3.3__tar.gz → 0.3.4__tar.gz

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 (35) hide show
  1. {matheel-0.3.3 → matheel-0.3.4}/PKG-INFO +6 -3
  2. {matheel-0.3.3 → matheel-0.3.4}/README.md +5 -2
  3. {matheel-0.3.3 → matheel-0.3.4}/matheel/cli.py +1 -1
  4. {matheel-0.3.3 → matheel-0.3.4}/matheel/code_metrics.py +258 -63
  5. matheel-0.3.4/matheel/native_codebleu.py +1071 -0
  6. {matheel-0.3.3 → matheel-0.3.4}/matheel/preprocessing.py +243 -8
  7. {matheel-0.3.3 → matheel-0.3.4}/matheel.egg-info/PKG-INFO +6 -3
  8. {matheel-0.3.3 → matheel-0.3.4}/matheel.egg-info/SOURCES.txt +1 -0
  9. {matheel-0.3.3 → matheel-0.3.4}/pyproject.toml +1 -1
  10. matheel-0.3.4/tests/test_code_metrics.py +518 -0
  11. matheel-0.3.4/tests/test_preprocessing.py +574 -0
  12. matheel-0.3.3/tests/test_code_metrics.py +0 -256
  13. matheel-0.3.3/tests/test_preprocessing.py +0 -67
  14. {matheel-0.3.3 → matheel-0.3.4}/LICENSE +0 -0
  15. {matheel-0.3.3 → matheel-0.3.4}/matheel/__init__.py +0 -0
  16. {matheel-0.3.3 → matheel-0.3.4}/matheel/chunking.py +0 -0
  17. {matheel-0.3.3 → matheel-0.3.4}/matheel/comparison_suite.py +0 -0
  18. {matheel-0.3.3 → matheel-0.3.4}/matheel/feature_weights.py +0 -0
  19. {matheel-0.3.3 → matheel-0.3.4}/matheel/model_routing.py +0 -0
  20. {matheel-0.3.3 → matheel-0.3.4}/matheel/similarity.py +0 -0
  21. {matheel-0.3.3 → matheel-0.3.4}/matheel/vectors.py +0 -0
  22. {matheel-0.3.3 → matheel-0.3.4}/matheel.egg-info/dependency_links.txt +0 -0
  23. {matheel-0.3.3 → matheel-0.3.4}/matheel.egg-info/entry_points.txt +0 -0
  24. {matheel-0.3.3 → matheel-0.3.4}/matheel.egg-info/requires.txt +0 -0
  25. {matheel-0.3.3 → matheel-0.3.4}/matheel.egg-info/top_level.txt +0 -0
  26. {matheel-0.3.3 → matheel-0.3.4}/setup.cfg +0 -0
  27. {matheel-0.3.3 → matheel-0.3.4}/tests/test_chunking.py +0 -0
  28. {matheel-0.3.3 → matheel-0.3.4}/tests/test_cli.py +0 -0
  29. {matheel-0.3.3 → matheel-0.3.4}/tests/test_comparison_suite.py +0 -0
  30. {matheel-0.3.3 → matheel-0.3.4}/tests/test_feature_weights.py +0 -0
  31. {matheel-0.3.3 → matheel-0.3.4}/tests/test_gradio_app.py +0 -0
  32. {matheel-0.3.3 → matheel-0.3.4}/tests/test_model_routing.py +0 -0
  33. {matheel-0.3.3 → matheel-0.3.4}/tests/test_real_models.py +0 -0
  34. {matheel-0.3.3 → matheel-0.3.4}/tests/test_similarity.py +0 -0
  35. {matheel-0.3.3 → matheel-0.3.4}/tests/test_vectors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: matheel
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Matheel: A CLI and Python package for source-code similarity detection.
5
5
  Author: Fahad Ebrahim
6
6
  License-Expression: MIT
@@ -81,6 +81,8 @@ pip install "matheel[dev]"
81
81
 
82
82
  `matheel[all]` installs the currently supported optional backends in one command: Chonkie code chunking, metrics runtime dependencies (RUBY graph/tree, TSED, CodeBERTScore), model2vec, PyLate, and the Gradio app dependencies.
83
83
 
84
+ Matheel now ships a native CodeBLEU implementation that uses `tree_sitter_language_pack` for parser resolution, so real syntax/dataflow scoring no longer depends on installing the pip `codebleu` package. The pip package is still useful for validation/comparison work if you want to cross-check the native scores on selected examples; Matheel does not currently claim exact pip parity on every possible input.
85
+
84
86
  ## Quick Start
85
87
 
86
88
  The repository root includes `sample_pairs.zip`, a small Java archive with:
@@ -128,8 +130,9 @@ print(round(score, 4))
128
130
 
129
131
  Supported languages:
130
132
 
131
- - Chunking and preprocessing are text-first and can run on any source text.
132
- - Code-aware metrics are currently scoped to `Java`, `Python`, `C`, and `C++`.
133
+ - Chunking remains text-first and can run on any source text.
134
+ - Preprocessing heuristics and code-aware metrics are now regression-tested for a unified 20-language scope: `Java`, `Python`, `C`, `C++`, `Go`, `JavaScript`, `TypeScript`, `Kotlin`, `Scala`, `Swift`, `Solidity`, `Dart`, `PHP`, `Ruby`, `Rust`, `C#`, `Lua`, `Julia`, `R`, and `Objective-C` (`objc`).
135
+ - Native CodeBLEU with real syntax/dataflow now covers that same 20-language scope.
133
136
 
134
137
  Similarity features:
135
138
 
@@ -33,6 +33,8 @@ pip install "matheel[dev]"
33
33
 
34
34
  `matheel[all]` installs the currently supported optional backends in one command: Chonkie code chunking, metrics runtime dependencies (RUBY graph/tree, TSED, CodeBERTScore), model2vec, PyLate, and the Gradio app dependencies.
35
35
 
36
+ Matheel now ships a native CodeBLEU implementation that uses `tree_sitter_language_pack` for parser resolution, so real syntax/dataflow scoring no longer depends on installing the pip `codebleu` package. The pip package is still useful for validation/comparison work if you want to cross-check the native scores on selected examples; Matheel does not currently claim exact pip parity on every possible input.
37
+
36
38
  ## Quick Start
37
39
 
38
40
  The repository root includes `sample_pairs.zip`, a small Java archive with:
@@ -80,8 +82,9 @@ print(round(score, 4))
80
82
 
81
83
  Supported languages:
82
84
 
83
- - Chunking and preprocessing are text-first and can run on any source text.
84
- - Code-aware metrics are currently scoped to `Java`, `Python`, `C`, and `C++`.
85
+ - Chunking remains text-first and can run on any source text.
86
+ - Preprocessing heuristics and code-aware metrics are now regression-tested for a unified 20-language scope: `Java`, `Python`, `C`, `C++`, `Go`, `JavaScript`, `TypeScript`, `Kotlin`, `Scala`, `Swift`, `Solidity`, `Dart`, `PHP`, `Ruby`, `Rust`, `C#`, `Lua`, `Julia`, `R`, and `Objective-C` (`objc`).
87
+ - Native CodeBLEU with real syntax/dataflow now covers that same 20-language scope.
85
88
 
86
89
  Similarity features:
87
90
 
@@ -64,7 +64,7 @@ def main():
64
64
  help='Optional code-level metric added to the final score.',
65
65
  )
66
66
  @click.option('--code-metric-weight', default=0.0, show_default=True, help='Weight applied to the selected code metric.')
67
- @click.option('--code-language', default='java', show_default=True, help='Language hint for code-level metrics. Official CodeBLEU scope: java, python, c, cpp.')
67
+ @click.option('--code-language', default='java', show_default=True, help='Language hint for code-level metrics. Native CodeBLEU, RUBY, and TSED support: java, python, c, cpp, go, javascript, typescript, kotlin, scala, swift, solidity, dart, php, ruby, rust, csharp, lua, julia, r, objc.')
68
68
  @click.option('--codebleu-component-weights', default='0.25,0.25,0.25,0.25', show_default=True, help='Comma-separated weights for ngram, weighted_ngram, syntax, dataflow.')
69
69
  @click.option('--crystalbleu-max-order', default=4, show_default=True, help='Maximum n-gram order for CrystalBLEU.')
70
70
  @click.option('--crystalbleu-trivial-ngram-count', default=50, show_default=True, help='How many frequent n-grams to ignore in CrystalBLEU.')
@@ -4,16 +4,15 @@ import time
4
4
  from collections import Counter
5
5
  from pathlib import Path
6
6
 
7
+ from .native_codebleu import AVAILABLE_LANGUAGES as NATIVE_CODEBLEU_LANGUAGES
8
+ from .native_codebleu import calc_codebleu as native_calc_codebleu
9
+ from .native_codebleu import native_runtime_available as native_codebleu_runtime_available
7
10
 
8
11
  try:
9
- from codebleu import bleu as package_codebleu_bleu
10
12
  from codebleu.codebleu import PACKAGE_DIR as codebleu_package_dir
11
- from codebleu import weighted_ngram_match as package_weighted_ngram_match
12
13
  from codebleu.utils import get_tree_sitter_language as codebleu_get_tree_sitter_language
13
14
  except ImportError: # pragma: no cover - optional dependency
14
- package_codebleu_bleu = None
15
15
  codebleu_package_dir = None
16
- package_weighted_ngram_match = None
17
16
  codebleu_get_tree_sitter_language = None
18
17
 
19
18
  try:
@@ -53,8 +52,10 @@ except ImportError: # pragma: no cover - optional dependency
53
52
 
54
53
  try:
55
54
  from tree_sitter_language_pack import get_parser as get_tree_sitter_parser
55
+ from tree_sitter_language_pack import get_language as get_tree_sitter_language_pack
56
56
  except ImportError: # pragma: no cover - optional dependency
57
57
  get_tree_sitter_parser = None
58
+ get_tree_sitter_language_pack = None
58
59
 
59
60
  try:
60
61
  import networkx as nx
@@ -74,7 +75,69 @@ _TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|\d+|[^\w\s]")
74
75
  _IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
75
76
  _RUBY_TRANX_SPLIT_RE = re.compile(r"([^A-Za-z0-9_])")
76
77
  _RUBY_TRANX_CAMEL_RE = re.compile(r"([a-z])([A-Z])")
77
- _SUPPORTED_CODE_LANGUAGES = ("java", "python", "c", "cpp")
78
+ _SUPPORTED_CODE_LANGUAGES = (
79
+ "java",
80
+ "python",
81
+ "c",
82
+ "cpp",
83
+ "go",
84
+ "javascript",
85
+ "typescript",
86
+ "kotlin",
87
+ "scala",
88
+ "swift",
89
+ "solidity",
90
+ "dart",
91
+ "php",
92
+ "ruby",
93
+ "rust",
94
+ "csharp",
95
+ "lua",
96
+ "julia",
97
+ "r",
98
+ "objc",
99
+ )
100
+ _SUPPORTED_REAL_CODEBLEU_LANGUAGES = NATIVE_CODEBLEU_LANGUAGES
101
+ _CODE_LANGUAGE_ALIASES = {
102
+ "py": "python",
103
+ "python3": "python",
104
+ "c++": "cpp",
105
+ "cc": "cpp",
106
+ "cxx": "cpp",
107
+ "hpp": "cpp",
108
+ "h++": "cpp",
109
+ "cpp": "cpp",
110
+ "c": "c",
111
+ "h": "c",
112
+ "java": "java",
113
+ "golang": "go",
114
+ "js": "javascript",
115
+ "node": "javascript",
116
+ "nodejs": "javascript",
117
+ "mjs": "javascript",
118
+ "cjs": "javascript",
119
+ "ts": "typescript",
120
+ "typescript": "typescript",
121
+ "kt": "kotlin",
122
+ "kts": "kotlin",
123
+ "sol": "solidity",
124
+ "rb": "ruby",
125
+ "rs": "rust",
126
+ "c#": "csharp",
127
+ "c_sharp": "csharp",
128
+ "cs": "csharp",
129
+ "lua": "lua",
130
+ "jl": "julia",
131
+ "objective-c": "objc",
132
+ "objectivec": "objc",
133
+ "obj-c": "objc",
134
+ }
135
+ _CODEBLEU_KEYWORD_LANGUAGE_NAMES = {
136
+ "csharp": "c_sharp",
137
+ }
138
+ _CODEBLEU_TREE_SITTER_LANGUAGE_NAMES = {
139
+ "csharp": "c_sharp",
140
+ }
78
141
  _CODEBLEU_KEYWORD_CACHE = {}
79
142
  _TREE_SITTER_PARSER_CACHE = {}
80
143
  _CODEBERTSCORE_SCORER_CACHE = {}
@@ -107,6 +170,138 @@ _KEYWORDS = {
107
170
  "public", "return", "short", "signed", "static", "struct", "switch", "template",
108
171
  "this", "throw", "true", "try", "typedef", "typename", "using", "void", "while",
109
172
  },
173
+ "go": {
174
+ "break", "case", "chan", "const", "continue", "default", "defer", "else", "false",
175
+ "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map",
176
+ "package", "range", "return", "select", "struct", "switch", "true", "type", "var",
177
+ },
178
+ "javascript": {
179
+ "await", "break", "case", "catch", "class", "const", "continue", "debugger",
180
+ "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally",
181
+ "for", "function", "if", "implements", "import", "in", "instanceof", "interface",
182
+ "let", "new", "null", "package", "private", "protected", "public", "return",
183
+ "static", "super", "switch", "this", "throw", "true", "try", "typeof", "var",
184
+ "void", "while", "with", "yield",
185
+ },
186
+ "typescript": {
187
+ "abstract", "any", "as", "asserts", "async", "await", "bigint", "boolean", "break",
188
+ "case", "catch", "class", "const", "constructor", "continue", "debugger", "declare",
189
+ "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally",
190
+ "for", "function", "get", "if", "implements", "import", "in", "infer", "instanceof",
191
+ "interface", "is", "keyof", "let", "module", "namespace", "never", "new", "null",
192
+ "number", "object", "override", "package", "private", "protected", "public",
193
+ "readonly", "return", "satisfies", "set", "static", "string", "super", "switch",
194
+ "symbol", "this", "throw", "true", "try", "type", "typeof", "undefined", "unique",
195
+ "unknown", "var", "void", "while", "with", "yield",
196
+ },
197
+ "kotlin": {
198
+ "abstract", "actual", "annotation", "as", "break", "by", "class", "companion", "const",
199
+ "constructor", "continue", "crossinline", "data", "delegate", "do", "dynamic", "else",
200
+ "enum", "expect", "external", "false", "field", "file", "final", "finally", "for",
201
+ "fun", "get", "if", "import", "in", "infix", "init", "inline", "inner", "interface",
202
+ "internal", "is", "lateinit", "noinline", "null", "object", "open", "operator", "out",
203
+ "override", "package", "private", "protected", "public", "reified", "return", "sealed",
204
+ "set", "super", "suspend", "tailrec", "this", "throw", "true", "try", "typealias",
205
+ "val", "var", "when", "where", "while",
206
+ },
207
+ "scala": {
208
+ "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", "final",
209
+ "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", "new", "null",
210
+ "object", "override", "package", "private", "protected", "return", "sealed", "super",
211
+ "this", "throw", "trait", "true", "try", "type", "val", "var", "while", "with", "yield",
212
+ },
213
+ "swift": {
214
+ "actor", "as", "associatedtype", "async", "await", "break", "case", "catch", "class",
215
+ "continue", "convenience", "default", "defer", "deinit", "didSet", "do", "dynamic",
216
+ "else", "enum", "extension", "fallthrough", "false", "fileprivate", "final", "for",
217
+ "func", "get", "guard", "if", "import", "in", "indirect", "infix", "init", "inout",
218
+ "internal", "is", "lazy", "let", "mutating", "nil", "nonmutating", "open", "operator",
219
+ "override", "postfix", "precedencegroup", "prefix", "private", "protocol", "public",
220
+ "repeat", "required", "rethrows", "return", "self", "set", "some", "static", "struct",
221
+ "subscript", "super", "switch", "throw", "throws", "true", "try", "typealias", "var",
222
+ "weak", "where", "while", "willSet",
223
+ },
224
+ "solidity": {
225
+ "abstract", "address", "anonymous", "as", "assembly", "bool", "break", "bytes", "calldata",
226
+ "constant", "constructor", "continue", "contract", "delete", "do", "else", "emit", "enum",
227
+ "error", "event", "external", "false", "fallback", "for", "function", "if", "immutable",
228
+ "import", "indexed", "interface", "internal", "is", "library", "mapping", "memory",
229
+ "modifier", "new", "override", "payable", "pragma", "private", "public", "pure", "return",
230
+ "returns", "revert", "storage", "struct", "true", "try", "type", "uint", "uint256",
231
+ "using", "view", "virtual", "while",
232
+ },
233
+ "dart": {
234
+ "abstract", "as", "assert", "async", "await", "base", "break", "case", "class", "const",
235
+ "continue", "covariant", "default", "deferred", "do", "dynamic", "else", "enum", "export",
236
+ "extends", "extension", "external", "factory", "false", "final", "for", "Function", "get",
237
+ "hide", "if", "implements", "import", "in", "interface", "is", "late", "library", "mixin",
238
+ "new", "null", "on", "operator", "part", "required", "rethrow", "return", "sealed", "set",
239
+ "show", "static", "super", "switch", "sync", "this", "throw", "true", "try", "typedef",
240
+ "var", "void", "when", "while", "with", "yield",
241
+ },
242
+ "php": {
243
+ "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case",
244
+ "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do",
245
+ "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif",
246
+ "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach",
247
+ "function", "global", "goto", "if", "implements", "include", "include_once",
248
+ "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or",
249
+ "print", "private", "protected", "public", "require", "require_once", "return",
250
+ "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor",
251
+ },
252
+ "ruby": {
253
+ "__ENCODING__", "__FILE__", "__LINE__", "BEGIN", "END", "alias", "and", "begin",
254
+ "break", "case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure",
255
+ "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue",
256
+ "retry", "return", "self", "super", "then", "true", "undef", "unless", "until",
257
+ "when", "while", "yield",
258
+ },
259
+ "rust": {
260
+ "as", "async", "await", "block", "bool", "break", "char", "const", "continue",
261
+ "crate", "default", "dyn", "else", "enum", "expr", "extern", "f32", "f64", "false",
262
+ "fn", "for", "i128", "i16", "i32", "i64", "i8", "ident", "if", "impl", "in", "isize",
263
+ "item", "let", "lifetime", "literal", "loop", "macro_rules!", "match", "meta", "mod",
264
+ "move", "mut", "pat", "path", "pub", "ref", "return", "self", "static", "stmt", "str",
265
+ "struct", "super", "trait", "true", "tt", "ty", "type", "u128", "u16", "u32", "u64",
266
+ "u8", "union", "unsafe", "use", "usize", "vis", "where", "while", "yield",
267
+ },
268
+ "csharp": {
269
+ "abstract", "add", "alias", "as", "ascending", "async", "await", "base", "bool",
270
+ "break", "byte", "by", "case", "catch", "char", "checked", "class", "const",
271
+ "continue", "decimal", "default", "delegate", "descending", "do", "double", "dynamic",
272
+ "else", "enum", "equals", "event", "explicit", "extern", "false", "finally", "fixed",
273
+ "float", "for", "foreach", "from", "get", "global", "goto", "group", "if", "implicit",
274
+ "in", "int", "interface", "internal", "into", "is", "join", "let", "lock", "long",
275
+ "nameof", "namespace", "new", "notnull", "null", "object", "on", "operator", "orderby",
276
+ "out", "override", "params", "partial", "private", "protected", "public", "readonly",
277
+ "ref", "remove", "return", "sbyte", "sealed", "select", "set", "short", "sizeof",
278
+ "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try",
279
+ "typeof", "uint", "ulong", "unchecked", "unmanaged", "unsafe", "ushort", "using",
280
+ "value", "var", "virtual", "void", "volatile", "when", "where", "while", "yield",
281
+ },
282
+ "lua": {
283
+ "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto",
284
+ "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until",
285
+ "while",
286
+ },
287
+ "julia": {
288
+ "abstract", "begin", "break", "catch", "const", "continue", "do", "else", "elseif",
289
+ "end", "false", "finally", "for", "function", "global", "if", "import", "in", "let",
290
+ "local", "macro", "module", "mutable", "quote", "return", "struct", "true", "try",
291
+ "using", "where", "while",
292
+ },
293
+ "r": {
294
+ "break", "else", "FALSE", "for", "function", "if", "in", "Inf", "NA", "NaN", "next",
295
+ "NULL", "repeat", "return", "TRUE", "while",
296
+ },
297
+ "objc": {
298
+ "break", "case", "catch", "char", "class", "const", "continue", "default", "do",
299
+ "double", "else", "enum", "extern", "float", "for", "goto", "id", "if",
300
+ "implementation", "import", "int", "interface", "long", "nil", "nonatomic",
301
+ "property", "protocol", "readonly", "return", "selector", "self", "short", "signed",
302
+ "static", "struct", "super", "switch", "typedef", "union", "unsigned", "void",
303
+ "volatile", "while",
304
+ },
110
305
  }
111
306
 
112
307
 
@@ -140,23 +335,39 @@ def available_code_metric_languages():
140
335
  return _SUPPORTED_CODE_LANGUAGES
141
336
 
142
337
 
338
+ def available_ast_metric_languages():
339
+ return _SUPPORTED_CODE_LANGUAGES
340
+
341
+
342
+ def available_codebleu_languages():
343
+ return _SUPPORTED_REAL_CODEBLEU_LANGUAGES
344
+
345
+
346
+ def codebleu_runtime_available():
347
+ return native_codebleu_runtime_available()
348
+
349
+
143
350
  def normalize_code_language(language):
144
351
  key = (language or "java").strip().lower()
145
- if key in ("py", "python3"):
146
- return "python"
147
- if key in ("c++", "cc", "cxx", "hpp", "h++", "cpp"):
148
- return "cpp"
149
- if key in ("c", "h"):
150
- return "c"
151
- if key == "java":
152
- return "java"
352
+ return _CODE_LANGUAGE_ALIASES.get(key, key)
353
+
354
+
355
+ def normalize_codebleu_language(language):
356
+ key = normalize_code_language(language)
357
+ if key not in _SUPPORTED_REAL_CODEBLEU_LANGUAGES:
358
+ supported = ", ".join(_SUPPORTED_REAL_CODEBLEU_LANGUAGES)
359
+ raise ValueError(
360
+ "CodeBLEU with real syntax/dataflow currently supports: "
361
+ f"{supported}. Got: {language}"
362
+ )
153
363
  return key
154
364
 
155
365
 
156
366
  def _load_package_keywords(language):
157
367
  if codebleu_package_dir is None:
158
368
  return None
159
- package_path = Path(codebleu_package_dir) / "keywords" / f"{language}.txt"
369
+ package_language = _CODEBLEU_KEYWORD_LANGUAGE_NAMES.get(language, language)
370
+ package_path = Path(codebleu_package_dir) / "keywords" / f"{package_language}.txt"
160
371
  if not package_path.exists():
161
372
  return None
162
373
  keywords = {
@@ -167,6 +378,12 @@ def _load_package_keywords(language):
167
378
  return keywords or None
168
379
 
169
380
 
381
+ def _fallback_keyword_set(language):
382
+ if language == "cpp":
383
+ return set(_KEYWORDS["c"]) | set(_KEYWORDS["cpp"])
384
+ return set(_KEYWORDS.get(language, set()))
385
+
386
+
170
387
  def keyword_set_for_language(language):
171
388
  key = normalize_code_language(language)
172
389
  if key not in _SUPPORTED_CODE_LANGUAGES:
@@ -174,15 +391,11 @@ def keyword_set_for_language(language):
174
391
  raise ValueError(f"Code metrics currently support: {supported}. Got: {language}")
175
392
  if key in _CODEBLEU_KEYWORD_CACHE:
176
393
  return _CODEBLEU_KEYWORD_CACHE[key]
394
+ keywords = _fallback_keyword_set(key)
177
395
  package_keywords = _load_package_keywords(key)
178
396
  if package_keywords is not None:
179
- _CODEBLEU_KEYWORD_CACHE[key] = package_keywords
180
- return package_keywords
181
- if key in ("c", "cpp"):
182
- _CODEBLEU_KEYWORD_CACHE["c"] = set(_KEYWORDS["c"])
183
- _CODEBLEU_KEYWORD_CACHE["cpp"] = set(_KEYWORDS["c"]) | set(_KEYWORDS["cpp"])
184
- return _CODEBLEU_KEYWORD_CACHE[key]
185
- _CODEBLEU_KEYWORD_CACHE[key] = set(_KEYWORDS[key])
397
+ keywords.update(package_keywords)
398
+ _CODEBLEU_KEYWORD_CACHE[key] = keywords
186
399
  return _CODEBLEU_KEYWORD_CACHE[key]
187
400
 
188
401
 
@@ -238,19 +451,6 @@ def _keyword_weighted_match_score(reference_tokens, hypothesis_tokens, keywords,
238
451
  if not hypothesis_tokens:
239
452
  return 0.0
240
453
 
241
- if package_weighted_ngram_match is not None:
242
- references = [[reference_tokens]]
243
- hypotheses = [hypothesis_tokens]
244
-
245
- def token_weights(tokens):
246
- return {token: 1.0 if token in keywords else 0.2 for token in tokens}
247
-
248
- refs_with_weights = [
249
- [[tokens, token_weights(tokens)] for tokens in reference]
250
- for reference in references
251
- ]
252
- return float(package_weighted_ngram_match.corpus_bleu(refs_with_weights, hypotheses))
253
-
254
454
  precisions = []
255
455
  max_order = len(weights)
256
456
  for n in range(1, max_order + 1):
@@ -333,8 +533,9 @@ def parse_component_weights(raw_weights=None):
333
533
 
334
534
 
335
535
  def codebleu_components(reference, prediction, language="java", component_weights=None):
336
- reference_tokens = tokenize_for_code_metrics(reference)
337
- hypothesis_tokens = tokenize_for_code_metrics(prediction)
536
+ normalized_language = normalize_codebleu_language(language)
537
+ reference_tokens = (reference or "").strip().split()
538
+ hypothesis_tokens = (prediction or "").strip().split()
338
539
  if not reference_tokens and not hypothesis_tokens:
339
540
  return {
340
541
  "codebleu": 1.0,
@@ -345,36 +546,24 @@ def codebleu_components(reference, prediction, language="java", component_weight
345
546
  }
346
547
 
347
548
  weights = parse_component_weights(component_weights)
348
- bleu_weights = (0.25, 0.25, 0.25, 0.25)
349
- keywords = keyword_set_for_language(language)
350
-
351
- if package_codebleu_bleu is not None:
352
- ngram_score = float(package_codebleu_bleu.corpus_bleu([[reference_tokens]], [hypothesis_tokens]))
353
- else:
354
- ngram_score = _weighted_match_score(reference_tokens, hypothesis_tokens, bleu_weights)
549
+ if not codebleu_runtime_available():
550
+ raise ImportError(
551
+ "CodeBLEU syntax/dataflow scoring requires tree-sitter and tree-sitter-language-pack."
552
+ )
355
553
 
356
- weighted_ngram_score = _keyword_weighted_match_score(reference_tokens, hypothesis_tokens, keywords, bleu_weights)
357
- syntax_score = _weighted_match_score(
358
- _syntax_shape_tokens(reference_tokens, keywords),
359
- _syntax_shape_tokens(hypothesis_tokens, keywords),
360
- bleu_weights,
361
- )
362
- dataflow_score = _identifier_overlap_score(reference_tokens, hypothesis_tokens, keywords)
363
-
364
- alpha, beta, gamma, theta = weights
365
- combined = float(
366
- (alpha * ngram_score)
367
- + (beta * weighted_ngram_score)
368
- + (gamma * syntax_score)
369
- + (theta * dataflow_score)
554
+ scores = native_calc_codebleu(
555
+ references=[(reference or "").strip()],
556
+ predictions=[(prediction or "").strip()],
557
+ lang=normalized_language,
558
+ weights=weights,
370
559
  )
371
560
 
372
561
  return {
373
- "codebleu": combined,
374
- "codebleu_ngram": float(ngram_score),
375
- "codebleu_weighted_ngram": float(weighted_ngram_score),
376
- "codebleu_syntax": float(syntax_score),
377
- "codebleu_dataflow": float(dataflow_score),
562
+ "codebleu": float(scores["codebleu"]),
563
+ "codebleu_ngram": float(scores["ngram_match_score"]),
564
+ "codebleu_weighted_ngram": float(scores["weighted_ngram_match_score"]),
565
+ "codebleu_syntax": float(scores["syntax_match_score"]),
566
+ "codebleu_dataflow": float(scores["dataflow_match_score"]),
378
567
  }
379
568
 
380
569
 
@@ -727,7 +916,9 @@ def _resolve_tsed_parser(language):
727
916
 
728
917
  if parser is None and TreeSitterParser is not None and codebleu_get_tree_sitter_language is not None:
729
918
  try:
730
- ts_language = codebleu_get_tree_sitter_language(normalized_language)
919
+ ts_language = codebleu_get_tree_sitter_language(
920
+ _CODEBLEU_TREE_SITTER_LANGUAGE_NAMES.get(normalized_language, normalized_language)
921
+ )
731
922
  try:
732
923
  parser = TreeSitterParser(ts_language)
733
924
  except TypeError:
@@ -1288,8 +1479,12 @@ def score_code_metric_pair(
1288
1479
  use_edge_cost=bool(ruby_graph_use_edge_cost),
1289
1480
  include_leaf_edges=bool(ruby_graph_include_leaf_edges),
1290
1481
  )
1482
+ if resolved_score is None and resolved_mode == "graph":
1483
+ raise RuntimeError("RUBY graph mode could not produce a structural score.")
1291
1484
  if resolved_score is None and resolved_mode in {"auto", "tree", "graph"}:
1292
1485
  resolved_score = _ruby_tree_similarity(left_tree, right_tree)
1486
+ if resolved_score is None and resolved_mode == "tree":
1487
+ raise RuntimeError("RUBY tree mode could not produce a structural score.")
1293
1488
  if resolved_score is None:
1294
1489
  resolved_score = _ruby_string_similarity_from_tokens(
1295
1490
  left_tokens,