Coverage for agentos/marketplace/skills/summarize/summarize.py: 78%

41 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-07-06 08:01 +0800

1""" 

2summarize — Text summarization using extractive and heuristic methods. 

3 

4Actions: summarize, extract_keywords, bullet_points, word_count 

5No external API required — pure Python. 

6""" 

7 

8from typing import Any 

9import re 

10from collections import Counter 

11 

12 

13def run(action: str = "summarize", text: str = "", file_path: str = "", ratio: float = 0.3, **kwargs: Any) -> str: 

14 content = text 

15 if file_path: 

16 try: 

17 with open(file_path, encoding="utf-8") as f: 

18 content = f.read() 

19 except FileNotFoundError: 

20 return f"[summarize] File not found: {file_path}" 

21 except Exception as e: 

22 return f"[summarize] Error reading file: {e}" 

23 

24 if not content: 

25 return "[summarize] No text provided." 

26 

27 if action == "word_count": 

28 words = re.findall(r'\b\w+\b', content.lower()) 

29 wc = len(words) 

30 sc = len(re.split(r'[.!?]+', content)) 

31 return f"Words: {wc}, Sentences: ~{sc}, Characters: {len(content)}" 

32 

33 if action == "extract_keywords": 

34 words = re.findall(r'\b[a-zA-Z]{3,}\b', content.lower()) 

35 stop = {"the","and","for","that","with","this","from","have","are","not","but","was","you","all","can","has", 

36 "had","been","will","they","its","their","them","our","than","then","also","into","just","about","more", 

37 "some","when","your","which","make","like","what","over","such","here","were","how","one","two"} 

38 filtered = [w for w in words if w not in stop] 

39 top = Counter(filtered).most_common(15) 

40 return "Top keywords: " + ", ".join(f"{w}({c})" for w, c in top) 

41 

42 if action == "bullet_points": 

43 sentences = re.split(r'(?<=[.!?])\s+', content) 

44 sentences = [s.strip() for s in sentences if len(s.strip()) > 20] 

45 n = max(3, int(len(sentences) * ratio)) 

46 return "[summarize] Bullet Points:\n" + "\n".join(f"- {s}" for s in sentences[:n]) 

47 

48 # Default: summarize (extractive) 

49 sentences = re.split(r'(?<=[.!?])\s+', content) 

50 sentences = [s.strip() for s in sentences if len(s.strip()) > 10] 

51 if not sentences: 

52 return content[:500] 

53 

54 n = max(2, int(len(sentences) * ratio)) 

55 summary = " ".join(sentences[:n]) 

56 if len(summary) > 1500: 

57 summary = summary[:1500] + "..." 

58 return summary 

59 

60 

61__all__ = ["run"]