utils.py 10.3 KB
Newer Older
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
1
import os
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
2
import re
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
3 4
from typing import *
from data_utils import stream_jsonl, LANGUAGE_TAG
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
5
from collections import Counter
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53


IMPORT_HELPER = {
    "python": [
        "import math",
        "import re",
        "import sys",
        "import copy",
        "import datetime",
        "import itertools",
        "import collections",
        "import heapq",
        "import statistics",
        "import functools",
        "import hashlib",
        "import numpy",
        "import numpy as np",
        "import string",
        "from typing import *",
        "from collections import *",
    ],
    "go"    : [
        "math",
        "strings",
        "fmt",
        "strconv",
        "time",
        "bytes",
        "regexp",
        "sort",
        "math/rand",
        "crypto/md5",
    ],
    "cpp"   : [
        "#include<stdlib.h>",
        "#include<algorithm>",
        "#include<math.h>",
        "#include<stdio.h>",
        "#include<vector>",
        "#include<string>",
        "#include<climits>",
        "#include<cstring>",
        "#include<iostream>",
    ],
}


def read_dataset(
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
54
    data_folder: str = None,
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
55 56 57 58 59 60 61
    dataset_type: str = "humaneval",
    language_type: str = "python",
    num_shot=None,
) -> Dict:
    if num_shot is not None:
        print(f"{num_shot}-shot setting...")
    if "humaneval" in dataset_type.lower():
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
62
        data_file = os.path.join(data_folder, language_type, "data", f"humaneval_{language_type}.jsonl.gz")
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        dataset = {task["task_id"]: task for task in stream_jsonl(data_file)}
    else:
        raise f"Dataset: {dataset_type} not supported."

    return dataset


def read_translation_dataset(
    data_file_src: str = None,
    data_file_tgt: str = None,
    lang_src: str = None,
    lang_tgt: str = None,
    dataset_type: str = "humaneval",
) -> Dict:
    if "humaneval" in dataset_type.lower():
        dataset_src = {task["task_id"]: task for task in stream_jsonl(data_file_src)}
        dataset_tgt = {task["task_id"].split("/")[-1]: task for task in stream_jsonl(data_file_tgt)}
        for k, sample in dataset_src.items():
            prompt = "code translation\n"
            if lang_src == "cpp":
                prompt += "C++:\n"
            elif lang_src == "js":
                prompt += "JavaScript:\n"
            else:
                prompt += f"{lang_src}:\n".capitalize()
            prompt += dataset_src[k]["declaration"] + "\n" + dataset_src[k]["canonical_solution"].rstrip() + "\n"
            if lang_tgt == "cpp":
                prompt += "C++:\n"
            elif lang_tgt == "js":
                prompt += "JavaScript:\n"
            else:
                prompt += f"{lang_tgt}:\n".capitalize()
            prompt += dataset_tgt[k.split("/")[-1]]["declaration"]
            dataset_src[k]["prompt"] = prompt
    else:
        raise f"Dataset: {dataset_type} not supported."

    return dataset_src


def process_extra_prompt(prompt: str, language_type: str = None) -> str:
    """
    Processes the extra prompt.
    """
    language = language_type.lower()
    if language in LANGUAGE_TAG:
        extra_prompt = LANGUAGE_TAG[language] + "\n"
    else:
        extra_prompt = ""

    return extra_prompt + prompt


def is_code_generation_finished(
    code: str,
    language_type: str = None,
    dataset: str = None,
):
    """
    Checks whether the generated code is finished.
    """
    if language_type is None or dataset is None:
        return False

    if "humaneval" in dataset.lower():
        if language_type.lower() == "python":
            for line in code.split("\n"):
                if len(line.strip()) > 0 and line[0] != ' ' and line[0] != '\t':
                    return True
            end_words = ["\ndef", "\nclass", "\nif", "\n#", "\nprint"]
            for w in end_words:
                if w in code:
                    return True
        elif language_type.lower() == "java":
            if code.count("{") + 1 == code.count("}"):
                return True
        elif language_type.lower() == "go":
            if code.count("{") + 1 == code.count("}"):
                return True
        elif language_type.lower() == "js":
            if code.count("{") + 1 == code.count("}"):
                return True
        elif language_type.lower() == "cpp":
            if code.count("{") + 1 == code.count("}"):
                return True

    return False


CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
def find_method_name(language_type, sample):
    """查找方法名"""
    if language_type.lower() == "python":
        declaration = sample["declaration"]
        ret = re.search("def (.*?)\\(", declaration)
        if ret is None:
            return None
        return ret.group(1).strip()
    elif language_type.lower() == "cpp":
        declaration = sample["declaration"]
        ret = re.search(" (.*?)\\(", declaration)
        if ret is None:
            return None
        method_name = ret.group(1).strip()
        if " " in method_name:
            return method_name[1]
        return method_name
    elif language_type.lower() == "java":
        declaration = sample["declaration"]
        ret = re.search(" (.*?)\\(", declaration)
        if ret is None:
            return None
        method_name = ret.group(1).strip()
        if " " in method_name:
            return method_name[1]
        return method_name
    elif language_type.lower() in ["js", "javascript"]:
        declaration = sample["declaration"]
        ret = re.search("const (.*?) ", declaration)
        if ret is None:
            return None
        method_name = ret.group(1).strip()
        return method_name
    elif language_type.lower() == "go":
        declaration = sample["declaration"]
        ret = re.search("func (.*?)\\(", declaration)
        if ret is None:
            return None
        return ret.group(1).strip()
    elif language_type == "rust":
        declaration = sample["declaration"]
        ret = re.search("fn (.*?)\\(", declaration)
        if ret is None:
            return None
        return ret.group(1).strip()
    else:
        return None


def extract_markdown_code(content):
    """提取markdown中的代码,即"```"中的内容"""
    codes = []
    rets = re.findall("```([\\s\\S]*?)```", content)
    if rets is None:
        return codes
    for ret in rets:
        if not ret.startswith("\n"):
            lines = ret.split("\n")
            codes.append("".join(lines[1:]))
        else:
            codes.append(ret.strip())

    return codes


def cleanup_code(code: str, sample, language_type: str = None):
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
218 219 220 221 222 223
    """
    Cleans up the generated code.
    """
    if language_type is None:
        return code

CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
224 225 226 227 228
    method_name = find_method_name(language_type, sample)
    if method_name is None:
        return code

    method_body = code
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
229
    if language_type.lower() == "python":
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
230 231 232 233 234 235 236 237 238 239 240 241
        method_lines = []
        for line in code.split("\n"):
            if f"def {method_name}" in line:
                method_lines.append(line)
                continue
            if method_lines:
                method_lines.append(line)
            if line.startswith("    return"):
                break
        if method_lines:
            method_body = "\n".join(method_lines[1:])

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
242
    elif language_type.lower() == "java":
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        method_lines = []
        bracket_left = 0
        bracket_right = 0
        for line in code.split("\n"):
            new_line = line.strip()
            counter = Counter(new_line)
            if new_line.startswith("public") and method_name in new_line:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
                continue
            if method_lines:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
            if bracket_left == bracket_right and bracket_right > 0:
                break

        if method_lines:
            method_lines.append("}")
            method_body = "\n".join(method_lines[1:])
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
264
    elif language_type.lower() == "go":
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        method_lines = []
        bracket_left = 0
        bracket_right = 0
        for line in code.split("\n"):
            counter = Counter(line)
            if f"func {method_name}" in line:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
                continue
            if method_lines:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
            if bracket_left == bracket_right and bracket_right > 0:
                break

        if method_lines:
            method_body = "\n".join(method_lines[1:])
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
284
            print(method_body)
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
285

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
286
    elif language_type.lower() == "cpp":
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
        method_lines = []
        bracket_left = 0
        bracket_right = 0
        for line in code.split("\n"):
            counter = Counter(line)
            if f" {method_name}(" in line:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
                continue
            if method_lines:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
            if bracket_left == bracket_right and bracket_right > 0:
                break

        if method_lines:
            method_body = "\n".join(method_lines[1:])

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
307
    elif language_type.lower() == "js":
CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        method_lines = []
        bracket_left = 0
        bracket_right = 0
        for line in code.split("\n"):
            counter = Counter(line)
            if f"const {method_name}" in line:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
                continue
            if method_lines:
                method_lines.append(line)
                bracket_left += counter["{"]
                bracket_right += counter["}"]
            if bracket_left == bracket_right and bracket_right > 0:
                break

        if method_lines:
            method_body = "\n".join(method_lines[1:])

    return method_body + "\n"


def exception_reconnect(funct):
    """异常重连"""
    def wrapper_func(*args, **kwargs):
        try:
            return funct(*args, **kwargs)
        except Exception as e:
            print(f"exception will reconnect: {str(e)}")
            return funct(*args, **kwargs)
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
339

CSDN-Ada助手's avatar
fix bug  
CSDN-Ada助手 已提交
340
    return wrapper_func