Spaces:
Running
Running
File size: 7,294 Bytes
37ba1ba 1606cd0 b12faee 37ba1ba 1606cd0 37ba1ba b12faee 37ba1ba 1606cd0 b12faee 1606cd0 37ba1ba 1606cd0 37ba1ba b12faee edac3aa b12faee 37ba1ba eafa97a 5b96dd0 b12faee 5b96dd0 b12faee 5b96dd0 eafa97a 37ba1ba edac3aa 5b96dd0 edac3aa 5b96dd0 37ba1ba 5b96dd0 37ba1ba 5b96dd0 37ba1ba 5b96dd0 37ba1ba b12faee 37ba1ba 5b96dd0 eafa97a 1606cd0 37ba1ba 5b96dd0 37ba1ba 1606cd0 5b96dd0 37ba1ba b12faee 37ba1ba 1606cd0 37ba1ba 1606cd0 37ba1ba b12faee 5b96dd0 b12faee 37ba1ba b12faee 37ba1ba 5b96dd0 37ba1ba 1606cd0 5b96dd0 37ba1ba 5b96dd0 37ba1ba 5b96dd0 37ba1ba 5b96dd0 37ba1ba 1606cd0 b12faee 37ba1ba 1606cd0 eafa97a 37ba1ba 5b96dd0 37ba1ba 5b96dd0 1606cd0 37ba1ba eafa97a 5b96dd0 37ba1ba eafa97a b12faee 5b96dd0 eafa97a 5b96dd0 37ba1ba eafa97a 5b96dd0 37ba1ba 5b96dd0 eafa97a 37ba1ba b12faee 5b96dd0 b12faee 5b96dd0 b12faee 37ba1ba 5b96dd0 37ba1ba 5b96dd0 37ba1ba 5b96dd0 1606cd0 |
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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
import json
import os
from datetime import datetime, timezone, timedelta
from dateutil import parser as dateparser
import meilisearch
from fasthtml.common import *
from markdown import markdown
from dotenv import load_dotenv
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from contextlib import asynccontextmanager
from constants import MeilisearchIndexFields
from update import process_webhook, update_webhooks
loaded = load_dotenv("./.env", override=True)
print("Loaded .env file:", loaded)
MS_URL = os.getenv("MS_URL")
MS_SEARCH_KEY = os.getenv("MS_SEARCH_KEY")
ms_client = meilisearch.Client(MS_URL, MS_SEARCH_KEY)
css_content = open("styles.css").read()
@asynccontextmanager
async def lifespan(app):
# Setup
scheduler = BackgroundScheduler()
scheduler.add_job(update_webhooks, CronTrigger.from_crontab("0 */3 * * *"))
scheduler.start()
yield
# Cleanup
scheduler.shutdown()
# If running locally, don't use the lifespan
if os.getenv("SPACE_ID") is None:
lifespan = None
app, rt = fast_app(hdrs=(Style(css_content),), lifespan=lifespan)
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(
Div(
Label("Start date", for_="start_date"),
Input(
type="date",
name="start_date",
value=start_date.strftime("%Y-%m-%d"),
title="Start date",
),
cls="date-input",
),
Div(
Label("End date", for_="end_date"),
Input(
type="date",
name="end_date",
value=end_date.strftime("%Y-%m-%d"),
title="End date",
),
cls="date-input",
),
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 = dateparser.isoparse(iso_string)
return int(dt.timestamp())
def unix_timestamp_to_nice_format(timestamp):
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
return dt.strftime("%b %d, %Y at %H:%M UTC")
def make_query(query, start_date, end_date, page=1, limit=10):
twenty_three_hours_59_minutes_59_seconds_in_seconds = (23 * 60 + 59) * 60 + 59
after_timestamp = iso_to_unix_timestamp(start_date)
before_timestamp = (
iso_to_unix_timestamp(end_date)
+ twenty_three_hours_59_minutes_59_seconds_in_seconds
)
options = {
"limit": limit,
"offset": (page - 1) * limit,
"filter": f"{MeilisearchIndexFields.UPDATED_AT.value} >= {after_timestamp} AND {MeilisearchIndexFields.UPDATED_AT.value} < {before_timestamp}",
"attributesToCrop": [MeilisearchIndexFields.CONTENT.value],
"cropLength": 30,
"attributesToHighlight": [
MeilisearchIndexFields.CONTENT.value,
MeilisearchIndexFields.TITLE.value,
],
"highlightPreTag": '<span class="highlight">',
"highlightPostTag": "</span>",
"distinct": MeilisearchIndexFields.URL.value,
}
return ms_client.index(MeilisearchIndexFields.INDEX_NAME.value).search(
query=query, opt_params=options
)
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(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 = result[MeilisearchIndexFields.URL.value]
date = unix_timestamp_to_nice_format(
int(result[MeilisearchIndexFields.UPDATED_AT.value])
)
return Div(
Div(
Strong(NotStr(result[MeilisearchIndexFields.TITLE.value])),
P(NotStr(result[MeilisearchIndexFields.CONTENT.value]), cls="comment-text"),
Div(Span(date)),
A(url, href=url, target="_blank"),
),
cls="card-item",
)
def make_pagination(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)
@app.post("/webhook")
async def hf_webhook(request):
return await process_webhook(request)
serve()
|