File size: 6,044 Bytes
37ba1ba
 
 
 
 
eafa97a
37ba1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
eafa97a
5b96dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eafa97a
37ba1ba
 
5b96dd0
 
 
 
 
 
 
 
 
 
 
 
 
37ba1ba
 
5b96dd0
37ba1ba
 
 
 
 
 
 
5b96dd0
 
37ba1ba
 
5b96dd0
37ba1ba
 
 
 
5b96dd0
eafa97a
37ba1ba
eafa97a
37ba1ba
5b96dd0
37ba1ba
 
 
 
 
 
5b96dd0
37ba1ba
 
 
 
 
 
 
 
5b96dd0
37ba1ba
 
5b96dd0
 
37ba1ba
 
 
 
 
 
5b96dd0
37ba1ba
 
 
 
 
 
5b96dd0
 
 
 
37ba1ba
 
5b96dd0
37ba1ba
 
 
 
 
 
5b96dd0
37ba1ba
 
5b96dd0
37ba1ba
 
 
eafa97a
37ba1ba
 
 
 
 
eafa97a
37ba1ba
 
5b96dd0
37ba1ba
 
5b96dd0
37ba1ba
 
eafa97a
 
5b96dd0
37ba1ba
eafa97a
5b96dd0
 
 
 
 
 
 
 
eafa97a
5b96dd0
37ba1ba
eafa97a
5b96dd0
 
 
 
 
 
37ba1ba
5b96dd0
eafa97a
37ba1ba
5b96dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37ba1ba
 
 
 
 
 
 
 
 
5b96dd0
 
 
 
37ba1ba
 
5b96dd0
37ba1ba
 
 
 
5b96dd0
37ba1ba
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
from fasthtml.common import *
from datetime import datetime, timedelta
import requests
from datetime import datetime
import json
from markdown import markdown

from dotenv import load_dotenv

loaded = load_dotenv("./.env", override=True)
print("Loaded .env file:", loaded)

API_URL = os.getenv("API_URL")
API_KEY = os.getenv("MS_SEARCH_KEY")


css_content = open("styles.css").read()

app, rt = fast_app(hdrs=(Style(css_content),))


md_exts = "codehilite", "smarty", "extra", "sane_lists"


def Markdown(s, exts=md_exts, **kw):
    return Div(NotStr(markdown(s, extensions=exts)), **kw)


scroll_script = Script("""
document.addEventListener('DOMContentLoaded', function() {
    var scrollButton = document.getElementById('scroll-top-btn');
    
    window.onscroll = function() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            scrollButton.style.display = "block";
        } else {
            scrollButton.style.display = "none";
        }
    };

    scrollButton.onclick = function() {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    };
});
""")


def date_range_inputs(start_date, end_date):
    return Div(
        Input(
            type="date",
            name="start_date",
            value=start_date.strftime("%Y-%m-%d"),
            title="Start date",
        ),
        Input(
            type="date",
            name="end_date",
            value=end_date.strftime("%Y-%m-%d"),
            title="End date",
        ),
        cls="date-range",
    )


def search_form(start_date, end_date):
    return Form(
        Input(type="text", name="query", placeholder="Enter search query"),
        date_range_inputs(start_date, end_date),
        Button("Search", type="submit"),
        hx_post="/search",
        hx_target="#search-results",
        hx_trigger="submit",
        id="search-form",
    )


def iso_to_unix_timestamp(iso_string):
    dt = datetime.fromisoformat(iso_string)
    return int(dt.timestamp())


def unix_timestamp_to_nice_format(timestamp):
    dt = datetime.fromtimestamp(timestamp)
    return dt.strftime("%b %d, %Y")


def make_query(query, start_date, end_date, page=1, limit=10):
    url = f"{API_URL}/indexes/comments/search"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}",
    }

    after_timestamp = iso_to_unix_timestamp(start_date)
    before_timestamp = iso_to_unix_timestamp(end_date)

    query = {
        "q": query,
        "limit": limit,
        "offset": (page - 1) * limit,
        "filter": f"comment_updatedAt_timestamp >= {after_timestamp} AND comment_updatedAt_timestamp < {before_timestamp}",
        "attributesToCrop": ["comment_text"],
        "cropLength": 30,
        "attributesToHighlight": ["comment_text", "discussion_title"],
        "highlightPreTag": '<span class="highlight">',
        "highlightPostTag": "</span>",
    }

    response = requests.post(url, headers=headers, json=query)

    return response.json()


def search_results(query, start_date, end_date, page=1):
    raw_results = make_query(query, start_date, end_date, page)

    return Div(
        make_results_bar(raw_results),
        Div(*[make_card(r) for r in raw_results["hits"]]),
        make_pagination(
            query, start_date, end_date, page, raw_results["estimatedTotalHits"]
        ),
        id="search-results",
    )


def make_results_bar(results):
    processing_time = results["processingTimeMs"]
    estimated_hits = results["estimatedTotalHits"]
    return Div(
        Div(f"Processing time: {processing_time}ms"),
        Div(f"Estimated total hits: {estimated_hits}"),
        cls="results-bar",
    )


def make_card(result):
    result = result["_formatted"]
    url = f"https://hf.co/{result['repo_id']}/discussions/{result['discussion_num']}"
    date = unix_timestamp_to_nice_format(int(result["comment_updatedAt_timestamp"]))

    return Div(
        Div(
            Strong(NotStr(result["discussion_title"])),
            P(NotStr(result["comment_text"]), cls="comment-text"),
            Div(Span(date)),
            A(url, href=url, target="_blank"),
        ),
        cls="card-item",
    )


def make_pagination(query, start_date, end_date, current_page, total_hits, limit=10):
    total_pages = -(-total_hits // limit)  # Ceiling division

    children = []

    if current_page > 1:
        children.append(
                Button(
                "Previous",
                hx_post=f"/search?page={current_page-1}",
                hx_target="#search-results",
                hx_include="[name='query'], [name='start_date'], [name='end_date']",
            )
        )

    children.append(Span(f"Page {current_page} of {total_pages}"))

    if current_page < total_pages:
        children.append(
            Button(
                "Next",
                hx_post=f"/search?page={current_page+1}",
                hx_target="#search-results",
                hx_include="[name='query'], [name='start_date'], [name='end_date']",
            )
        )

    return Div(*children, cls="pagination")

scroll_button = Button("Scroll to Top", 
    id="scroll-top-btn", 
    style="""
        position: fixed; 
        bottom: 20px; 
        right: 20px; 
        display: none;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 5px;
        padding: 10px 15px;
        cursor: pointer;
    """
)

@rt("/")
def get():
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)
    return Titled(
        "HF Discussion Search",
        Div(
            search_form(start_date, end_date),
            Div(id="search-results"),
            scroll_button,
            scroll_script,
            cls="container",
        ),
    )


@rt("/search")
def post(query: str, start_date: str, end_date: str, page: int = 1):
    return search_results(query, start_date, end_date, page)


serve()