| from transformers import pipeline |
| import torch |
|
|
| def score_article_titles(title_list, model_name="mrm8488/bert-mini-finetuned-age_news-classification"): |
| """ |
| 为文章标题列表打分,返回对应的分数列表 |
| |
| 参数: |
| title_list: 文章标题列表(list[str]) |
| model_name: Hugging Face 免费模型名称,默认使用轻量的BERT微调模型 |
| |
| 返回: |
| score_list: 分数列表(list[float]),分数范围0-1,越高代表标题质量越好 |
| """ |
| |
| if not title_list: |
| return [] |
| |
| |
| device = 0 if torch.cuda.is_available() else -1 |
| |
| |
| try: |
| |
| classifier = pipeline( |
| "text-classification", |
| model=model_name, |
| device=device, |
| top_k=None |
| ) |
| except Exception as e: |
| print(f"加载模型失败:{e}") |
| print("将使用默认的distilbert-base-uncased-emotion模型") |
| classifier = pipeline( |
| "text-classification", |
| model="distilbert-base-uncased-emotion", |
| device=device, |
| top_k=None |
| ) |
| |
| |
| score_list = [] |
| for title in title_list: |
| |
| if not title.strip(): |
| score_list.append(0.0) |
| continue |
| |
| |
| pipeline_output = classifier(title) |
| |
| |
| if isinstance(pipeline_output, list): |
| |
| if len(pipeline_output) > 0 and isinstance(pipeline_output[0], list): |
| results = pipeline_output[0] |
| |
| else: |
| results = pipeline_output |
| else: |
| |
| results = [pipeline_output] |
|
|
| |
| total_score = max([item["score"] for item in results]) |
| |
| normalized_score = round(max(0.0, min(1.0, total_score)), 4) |
| score_list.append(normalized_score) |
| |
| return score_list |