import json import sys import tqdm from pydantic import BaseModel class Sample(BaseModel): code: str size: int license: str def is_chinese_char(char): """Check if the char is a Chinese character.""" return char >= "\u4e00" and char <= "\u9fff" def is_chinese(text: str): """Check if the text is Chinese. We consider a text as Chinese if >20% of the text is Chinese characters.""" cn_count = 0 for char in text: if is_chinese_char(char): cn_count += 1 return True if cn_count * 50 > len(text) else False with open(sys.argv[1], "r") as inp: with open(sys.argv[2], "wb") as out: for line in tqdm.tqdm(inp): try: data = json.loads(line) except json.JSONDecodeError as e: print(f"Error: {e}") continue code, size, license = ( data["code"], data["size"], data["license"], ) if license not in [ "", "MIT", "Apache-2.0", "CC-BY-4.0", "CC-BY-3.0", "MIT-0", "CC0-1.0", "BSD-3-Clause", "BSD-2-Clause", "BSD-Source-Code", "EC", "Unlicense", ]: continue if is_chinese(code): encoded = Sample( code=code, size=size, license=license, ).model_dump_json() out.write(encoded.encode("utf-8") + b"\n")