Spaces:
Sleeping
Sleeping
Download code_name_suggester.py from KyrieChao/code-method-namer: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/spaces/KyrieChao/code-method-namer/resolve/main/code_name_suggester.py
- Command line
-
hf download hf://spaces/KyrieChao/code-method-namer/code_name_suggester.py
-
curl -L -o code_name_suggester.py https://huggingface.co/spaces/KyrieChao/code-method-namer/resolve/main/code_name_suggester.py
5.18 kB
| """ | |
| 代码片段 → 方法名建议工具 | |
| 基于 fine-tune 的 CodeT5-small + ONNX 加速 | |
| 支持 CPU,输出多个候选方法名 | |
| 调试开关默认关闭 | |
| 单例模式,避免重复加载模型 | |
| """ | |
| import threading | |
| import time | |
| from typing import List, Optional | |
| import torch | |
| from transformers import AutoTokenizer, T5ForConditionalGeneration | |
| from optimum.onnxruntime import ORTModelForSeq2SeqLM | |
| class CodeNameSuggester: | |
| _instance = None | |
| _lock = threading.Lock() | |
| _initialized = False | |
| def __new__(cls, *args, **kwargs): | |
| if cls._instance is None: | |
| with cls._lock: | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| return cls._instance | |
| def __init__( | |
| self, | |
| model_name_or_path: str = "KyrieChao/code-method-namer", | |
| device: str = "cpu", | |
| max_input_len: int = 256, | |
| max_output_len: int = 32, | |
| num_beams: int = 4, | |
| num_candidates: int = 3, | |
| debug: bool = False, | |
| force_reload: bool = False, | |
| ): | |
| if self._initialized and not force_reload: | |
| return | |
| with self._lock: | |
| if self._initialized and not force_reload: | |
| return | |
| print("🚀 首次加载模型...") | |
| self.device = device | |
| self.max_input_len = max_input_len | |
| self.max_output_len = max_output_len | |
| self.num_beams = num_beams | |
| self.num_candidates = num_candidates | |
| self.debug = debug | |
| self.ort_model = None | |
| self.pytorch_model = None | |
| self.tokenizer = None | |
| self._load_model(model_name_or_path) | |
| if self.tokenizer.pad_token_id is None: | |
| self.tokenizer.pad_token_id = self.tokenizer.eos_token_id or 0 | |
| if self.tokenizer.eos_token_id is None: | |
| self.tokenizer.eos_token_id = 1 | |
| self._initialized = True | |
| print("✅ 模型热加载完成") | |
| def _load_model(self, model_name_or_path: str): | |
| # 尝试 ONNX | |
| try: | |
| print(" 尝试 ONNX...") | |
| self.ort_model = ORTModelForSeq2SeqLM.from_pretrained( | |
| model_name_or_path, | |
| provider="CPUExecutionProvider" if self.device == "cpu" else "CUDAExecutionProvider", | |
| ) | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) | |
| print(" ✅ ONNX 加载成功") | |
| return | |
| except Exception as e: | |
| print(f" ONNX 失败: {e}") | |
| # 回退 PyTorch | |
| print(" 加载 PyTorch...") | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) | |
| self.pytorch_model = T5ForConditionalGeneration.from_pretrained(model_name_or_path) | |
| self.pytorch_model.to(self.device) | |
| self.pytorch_model.eval() | |
| print(" ✅ PyTorch 加载成功") | |
| def clean_name(name: str) -> str: | |
| name = name.strip().replace(" ", "_").replace("-", "_").strip("_") | |
| return name[:60] if len(name) >= 2 else "unknown_name" | |
| def suggest(self, code_snippet: str, num_candidates: Optional[int] = None) -> List[str]: | |
| use_num = min(num_candidates or self.num_candidates, self.num_beams) | |
| prompt = code_snippet.strip() | |
| start_time = time.time() | |
| inputs = self.tokenizer( | |
| prompt, | |
| max_length=self.max_input_len, | |
| truncation=True, | |
| return_tensors="pt", | |
| padding=True | |
| ) | |
| gen_kwargs = { | |
| "max_length": self.max_output_len, | |
| "num_beams": self.num_beams, | |
| "early_stopping": True, | |
| "no_repeat_ngram_size": 2, | |
| "pad_token_id": self.tokenizer.pad_token_id, | |
| "eos_token_id": self.tokenizer.eos_token_id, | |
| } | |
| # 关键:ONNX 只支持单序列生成 | |
| if self.ort_model: | |
| outputs = self.ort_model.generate(**inputs, **gen_kwargs) | |
| all_outputs = [outputs[0]] # 单条 | |
| else: | |
| gen_kwargs["num_return_sequences"] = use_num | |
| with torch.no_grad(): | |
| outputs = self.pytorch_model.generate( | |
| inputs.input_ids.to(self.device), | |
| attention_mask=inputs.attention_mask.to(self.device), | |
| **gen_kwargs | |
| ) | |
| all_outputs = outputs | |
| elapsed = time.time() - start_time | |
| suggestions = [] | |
| seen = set() | |
| for out in all_outputs: | |
| decoded = self.tokenizer.decode(out, skip_special_tokens=True).strip() | |
| cleaned = self.clean_name(decoded) | |
| if cleaned and cleaned not in seen and cleaned != "unknown_name": | |
| seen.add(cleaned) | |
| suggestions.append(cleaned) | |
| if len(suggestions) >= use_num: | |
| break | |
| print(f"⏱️ {elapsed:.3f}s | 建议: {suggestions}") | |
| return suggestions | |
| def get_suggester(model_name_or_path: str = "KyrieChao/code-method-namer", device: str = "cpu"): | |
| return CodeNameSuggester(model_name_or_path=model_name_or_path, device=device) |