test_download.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/env python
  2. """
  3. 快速测试脚本 - 下载单个领域的小样本验证链路
  4. 用法:
  5. python test_download.py
  6. """
  7. import os
  8. import re
  9. import json
  10. import random
  11. from pathlib import Path
  12. # 设置 HuggingFace 镜像
  13. os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
  14. from datasets import load_dataset
  15. def preprocess_text(text: str, lang: str = "en") -> str | None:
  16. """预处理文本"""
  17. text = text.strip()
  18. if not text:
  19. return None
  20. if lang == "en":
  21. text = re.sub(r'[^\w\s.,!?;:()"\']', '', text)
  22. words = text.split()
  23. if len(words) < 50 or len(words) > 200:
  24. return None
  25. text = ' '.join(words[:200]).strip()
  26. else:
  27. text = re.sub(r'[^\u4e00-\u9fff0-9.,!?;:()""\']', '', text)
  28. if len(text) < 100 or len(text) > 500:
  29. return None
  30. return text if text else None
  31. def main():
  32. print("=" * 50)
  33. print("快速测试:下载 CNN/DailyMail 英文新闻")
  34. print("=" * 50)
  35. # 加载数据集
  36. print("\n加载数据集...")
  37. ds = load_dataset("cnn_dailymail", "3.0.0", split="train")
  38. # 随机采样 20 条
  39. print("采样并预处理...")
  40. texts = [item["article"] for item in random.sample(list(ds), 20)]
  41. # 预处理
  42. corpus = []
  43. for text in texts:
  44. processed = preprocess_text(text, lang="en")
  45. if processed and processed not in corpus:
  46. corpus.append(processed)
  47. if len(corpus) >= 10:
  48. break
  49. print(f"成功提取 {len(corpus)} 条有效文本")
  50. # 保存
  51. output_path = Path("database/corpus/news_en_test/texts.jsonl")
  52. output_path.parent.mkdir(parents=True, exist_ok=True)
  53. with open(output_path, "w", encoding="utf-8") as f:
  54. for i, text in enumerate(corpus):
  55. record = {
  56. "text": text,
  57. "metadata": {"index": i, "domain": "news_en_test"}
  58. }
  59. f.write(json.dumps(record, ensure_ascii=False) + "\n")
  60. print(f"已保存至:{output_path}")
  61. # 验证读取
  62. print("\n验证读取...")
  63. with open(output_path, "r", encoding="utf-8") as f:
  64. for i, line in enumerate(f):
  65. record = json.loads(line)
  66. text = record["text"]
  67. print(f" [{i}] 长度:{len(text)} 字符")
  68. if i >= 2:
  69. break
  70. print("\n" + "=" * 50)
  71. print("测试完成!链路验证通过")
  72. print("=" * 50)
  73. if __name__ == "__main__":
  74. main()