-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
308 lines (250 loc) · 10.4 KB
/
Copy pathapp.py
File metadata and controls
308 lines (250 loc) · 10.4 KB
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import json
import logging
import sys
import threading
from datetime import date
from flask import Flask, render_template, request, jsonify, abort, Response, stream_with_context
from config import ENABLE_RUN_NOW, TOP_N_RECOMMENDATIONS, FEISHU_APP_ID, FEISHU_APP_SECRET
from db.database import (
init_db, get_recommendations_for_date, get_available_dates,
get_paper, save_summary, get_digest, get_vote,
get_local_profile, save_local_profile, record_vote, get_vote_history,
)
from services.claude_service import summarize_paper
import log_stream
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
log_stream.install_handler()
app = Flask(__name__)
_pipeline_running = False
# Start Feishu long-connection (WebSocket) for card button callbacks
from feishu.longconn import start_longconn
start_longconn(FEISHU_APP_ID, FEISHU_APP_SECRET)
@app.before_request
def setup():
init_db()
def _parse_recs(recs):
for r in recs:
r["authors"] = json.loads(r.get("authors_json") or "[]")
r["categories"] = json.loads(r.get("categories_json") or "[]")
r["vote"] = get_vote(r["arxiv_id"])
return recs
@app.route("/")
def index():
available_dates = get_available_dates()
default_date = available_dates[0] if available_dates else str(date.today())
selected_date = request.args.get("date", default_date)
# If the requested date has no data but other dates do, redirect to latest
if selected_date not in available_dates and available_dates:
from flask import redirect
return redirect(f"/?date={available_dates[0]}")
all_recs = _parse_recs(get_recommendations_for_date(selected_date))
top_recs = all_recs[:TOP_N_RECOMMENDATIONS]
other_recs = all_recs[TOP_N_RECOMMENDATIONS:]
digest = get_digest(selected_date)
return render_template(
"index.html",
top_recs=top_recs,
other_recs=other_recs,
selected_date=selected_date,
available_dates=available_dates,
today=str(date.today()),
digest=digest,
)
@app.route("/api/last-date")
def api_last_date():
dates = get_available_dates()
return jsonify({"date": dates[0] if dates else None})
@app.route("/paper/<arxiv_id>")
def paper_detail(arxiv_id):
paper = get_paper(arxiv_id)
if not paper:
abort(404)
if not paper.get("summary"):
try:
summary = summarize_paper(paper["title"], paper["abstract"])
save_summary(arxiv_id, summary)
paper["summary"] = summary
except Exception as e:
paper["summary"] = f"(Summary unavailable: {e})"
paper["authors"] = json.loads(paper.get("authors_json") or "[]")
paper["categories"] = json.loads(paper.get("categories_json") or "[]")
paper["vote"] = get_vote(arxiv_id)
return render_template("paper_detail.html", paper=paper)
@app.route("/summarize/<arxiv_id>", methods=["POST"])
def get_summary(arxiv_id):
paper = get_paper(arxiv_id)
if not paper:
return jsonify({"error": "Paper not found"}), 404
if paper.get("summary"):
return jsonify({"summary": paper["summary"]})
try:
summary = summarize_paper(paper["title"], paper["abstract"])
save_summary(arxiv_id, summary)
return jsonify({"summary": summary})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/history")
def history():
ratings = get_vote_history(limit=100)
return render_template("history.html", ratings=ratings)
@app.route("/run-now", methods=["POST"])
def run_now():
global _pipeline_running
if not ENABLE_RUN_NOW:
abort(403)
if _pipeline_running:
return jsonify({"status": "already_running"})
from datetime import datetime as _dt
data = request.get_json(silent=True) or {}
target_date_str = data.get("target_date")
target_date = None
if target_date_str:
try:
target_date = _dt.strptime(target_date_str, "%Y-%m-%d").date()
except ValueError:
return jsonify({"error": "Invalid date format, use YYYY-MM-DD"}), 400
def _run(for_date):
global _pipeline_running
_pipeline_running = True
try:
from jobs.daily_job import run_daily_job
run_daily_job(for_date=for_date)
finally:
_pipeline_running = False
threading.Thread(target=_run, args=(target_date,), daemon=True).start()
return jsonify({"status": "started", "target_date": target_date_str or str(date.today())})
@app.route("/pipeline-status")
def pipeline_status():
return jsonify({"running": _pipeline_running})
@app.route("/log-stream")
def log_stream_sse():
"""SSE endpoint: streams log entries as server-sent events."""
import queue as q_mod
def generate():
lq = log_stream.get_queue()
# Send a heartbeat immediately so the browser knows the connection is alive
yield "data: {\"type\":\"connected\"}\n\n"
while True:
try:
entry = lq.get(timeout=20)
payload = json.dumps({"type": "log", **entry})
yield f"data: {payload}\n\n"
except q_mod.Empty:
# Heartbeat to keep connection alive
yield "data: {\"type\":\"heartbeat\"}\n\n"
return Response(
stream_with_context(generate()),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
@app.route("/profile")
def profile():
return render_template("profile.html", profile=get_local_profile())
@app.route("/api/profile", methods=["POST"])
def api_profile_save():
data = request.get_json()
scholar_id = (data.get("scholar_id") or "").strip()
display_name = (data.get("display_name") or "").strip()
bio = (data.get("bio") or "").strip()
interests = [s.strip() for s in (data.get("interests") or []) if s.strip()]
own_papers = [
{"title": p.get("title", "").strip(), "abstract": p.get("abstract", "").strip()}
for p in (data.get("own_papers") or [])
if p.get("title", "").strip()
]
save_local_profile(scholar_id, display_name, bio, interests, own_papers)
return jsonify({"status": "ok"})
@app.route("/api/profile/sync-scholar", methods=["POST"])
def api_profile_sync_scholar():
data = request.get_json(silent=True) or {}
scholar_id = (data.get("scholar_id") or "").strip()
if not scholar_id:
# Fall back to whatever is stored in local profile
scholar_id = get_local_profile().get("scholar_id", "")
if not scholar_id:
return jsonify({"error": "No Scholar ID provided"}), 400
from services.scholar import sync_from_scholar
result = sync_from_scholar(scholar_id)
return jsonify(result)
@app.route("/vote", methods=["POST"])
def vote():
data = request.get_json()
arxiv_id = data.get("arxiv_id")
vote_val = data.get("vote")
if not arxiv_id or not get_paper(arxiv_id):
return jsonify({"error": "Paper not found"}), 404
if vote_val not in (1, -1):
return jsonify({"error": "vote must be 1 or -1"}), 400
record_vote(arxiv_id, vote_val)
return jsonify({"status": "ok", "arxiv_id": arxiv_id, "vote": vote_val})
@app.route("/api/greeting")
def api_greeting():
from services.claude_service import generate_pipeline_greeting
emoji, msg = generate_pipeline_greeting()
return jsonify({"emoji": emoji, "msg": msg})
@app.route("/api/clear-data", methods=["POST"])
def api_clear_data():
"""Delete fetched papers, recommendations, digests, votes, and ratings.
The user's local profile and institution settings are preserved.
Deletion order respects FK constraints:
votes/ratings/recommendations/digests → papers (child before parent)
"""
from db.database import get_db
targets = request.get_json(silent=True) or {}
clear_papers = targets.get("papers", True)
clear_votes = targets.get("votes", True)
with get_db() as conn:
# Always clear child rows before touching papers
if clear_votes or clear_papers:
conn.execute("DELETE FROM votes")
conn.execute("DELETE FROM ratings")
conn.execute("DELETE FROM topic_signals")
conn.execute("DELETE FROM author_signals")
conn.execute("DELETE FROM institution_signals")
if clear_papers:
conn.execute("DELETE FROM recommendations")
conn.execute("DELETE FROM daily_digests")
conn.execute("DELETE FROM papers")
return jsonify({"status": "ok"})
@app.route("/settings")
def settings():
return render_template("settings.html")
# ── Feishu webhook ────────────────────────────────────────────────────────────
@app.route("/feishu/callback", methods=["POST"])
def feishu_callback():
"""Receive Feishu card button clicks (旧版 card.action.trigger_v1)."""
body = request.get_json(silent=True) or {}
logger.info("Feishu callback received: %s", body)
# URL verification challenge (event subscription setup)
if "challenge" in body:
return jsonify({"challenge": body["challenge"]})
# Card button click — old format: body has action.value directly (no type field)
# New format also handled: body.type == "card.action.trigger"
if body.get("type") == "card.action.trigger":
action_val = body.get("action", {}).get("value", {})
else:
action_val = body.get("action", {}).get("value", {})
action = action_val.get("action")
arxiv_id = action_val.get("arxiv_id", "")
if arxiv_id and action in ("vote_up", "vote_down"):
vote = 1 if action == "vote_up" else -1
record_vote(arxiv_id, vote)
logger.info("Feishu vote: %s → %+d", arxiv_id, vote)
if FEISHU_APP_ID and FEISHU_APP_SECRET:
from feishu.bot import build_vote_ack_card
paper = get_paper(arxiv_id)
title = paper["title"] if paper else arxiv_id
url = f"https://arxiv.org/abs/{arxiv_id}"
ack = build_vote_ack_card(arxiv_id, vote, title, url)
return jsonify({"toast": {"type": "success", "content": "投票已记录 ✓"}, "card": ack})
return jsonify({})
if __name__ == "__main__":
init_db()
app.run(debug=False, port=5001, threaded=True)