summaryrefslogtreecommitdiff
path: root/plugins/last30days/scripts/lib/normalize.py
blob: dc1124748b77f5ce60a068b90fc12307f21fbf51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""Normalization of raw API data to canonical schema."""

from typing import Any, TypeVar

from . import dates, schema

T = TypeVar("T", schema.RedditItem, schema.XItem, schema.WebSearchItem)


def filter_by_date_range(
    items: list[T],
    from_date: str,
    to_date: str,
    require_date: bool = False,
) -> list[T]:
    """Hard filter: Remove items outside the date range.

    This is the safety net - even if the prompt lets old content through,
    this filter will exclude it.

    Args:
        items: List of items to filter
        from_date: Start date (YYYY-MM-DD) - exclude items before this
        to_date: End date (YYYY-MM-DD) - exclude items after this
        require_date: If True, also remove items with no date

    Returns:
        Filtered list with only items in range (or unknown dates if not required)
    """
    result = []
    for item in items:
        if item.date is None:
            if not require_date:
                result.append(item)  # Keep unknown dates (with scoring penalty)
            continue

        # Hard filter: if date is before from_date, exclude
        if item.date < from_date:
            continue  # DROP - too old

        # Hard filter: if date is after to_date, exclude (likely parsing error)
        if item.date > to_date:
            continue  # DROP - future date

        result.append(item)

    return result


def normalize_reddit_items(
    items: list[dict[str, Any]],
    from_date: str,
    to_date: str,
) -> list[schema.RedditItem]:
    """Normalize raw Reddit items to schema.

    Args:
        items: Raw Reddit items from API
        from_date: Start of date range
        to_date: End of date range

    Returns:
        List of RedditItem objects
    """
    normalized = []

    for item in items:
        # Parse engagement
        engagement = None
        eng_raw = item.get("engagement")
        if isinstance(eng_raw, dict):
            engagement = schema.Engagement(
                score=eng_raw.get("score"),
                num_comments=eng_raw.get("num_comments"),
                upvote_ratio=eng_raw.get("upvote_ratio"),
            )

        # Parse comments
        top_comments = []
        for c in item.get("top_comments", []):
            top_comments.append(
                schema.Comment(
                    score=c.get("score", 0),
                    date=c.get("date"),
                    author=c.get("author", ""),
                    excerpt=c.get("excerpt", ""),
                    url=c.get("url", ""),
                )
            )

        # Determine date confidence
        date_str = item.get("date")
        date_confidence = dates.get_date_confidence(date_str, from_date, to_date)

        normalized.append(
            schema.RedditItem(
                id=item.get("id", ""),
                title=item.get("title", ""),
                url=item.get("url", ""),
                subreddit=item.get("subreddit", ""),
                date=date_str,
                date_confidence=date_confidence,
                engagement=engagement,
                top_comments=top_comments,
                comment_insights=item.get("comment_insights", []),
                relevance=item.get("relevance", 0.5),
                why_relevant=item.get("why_relevant", ""),
            )
        )

    return normalized


def normalize_x_items(
    items: list[dict[str, Any]],
    from_date: str,
    to_date: str,
) -> list[schema.XItem]:
    """Normalize raw X items to schema.

    Args:
        items: Raw X items from API
        from_date: Start of date range
        to_date: End of date range

    Returns:
        List of XItem objects
    """
    normalized = []

    for item in items:
        # Parse engagement
        engagement = None
        eng_raw = item.get("engagement")
        if isinstance(eng_raw, dict):
            engagement = schema.Engagement(
                likes=eng_raw.get("likes"),
                reposts=eng_raw.get("reposts"),
                replies=eng_raw.get("replies"),
                quotes=eng_raw.get("quotes"),
            )

        # Determine date confidence
        date_str = item.get("date")
        date_confidence = dates.get_date_confidence(date_str, from_date, to_date)

        normalized.append(
            schema.XItem(
                id=item.get("id", ""),
                text=item.get("text", ""),
                url=item.get("url", ""),
                author_handle=item.get("author_handle", ""),
                date=date_str,
                date_confidence=date_confidence,
                engagement=engagement,
                relevance=item.get("relevance", 0.5),
                why_relevant=item.get("why_relevant", ""),
            )
        )

    return normalized


def items_to_dicts(items: list) -> list[dict[str, Any]]:
    """Convert schema items to dicts for JSON serialization."""
    return [item.to_dict() for item in items]