-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathweb_server.py
More file actions
1664 lines (1373 loc) · 58 KB
/
Copy pathweb_server.py
File metadata and controls
1664 lines (1373 loc) · 58 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Daily Recommender Web Backend
FastAPI + WebSocket 实时日志
"""
from __future__ import annotations
import asyncio
import json
import locale
import mimetypes
import os
import re
import sys
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
from typing import Literal
from urllib.parse import urlparse
import httpx
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
from fetchers.profile_fetcher import build_profile_text_from_urls
# 项目根目录
PROJECT_ROOT = Path(__file__).parent.absolute()
HISTORY_DIR = PROJECT_ROOT / "history"
CONFIG_FILE = PROJECT_ROOT / ".web_config.json"
CLIENT_CONFIG_FILE = PROJECT_ROOT / ".client_config.json"
ENV_FILE = PROJECT_ROOT / ".env"
PUBLIC_UI_FILE = PROJECT_ROOT / "templates" / "public-web-ui.html"
ADMIN_UI_FILE = PROJECT_ROOT / "templates" / "web-ui.html"
DESKTOP_UI_FILE = PROJECT_ROOT / "templates" / "desktop-ui.html"
CLIENT_DIST_DIR = PROJECT_ROOT / "client" / "dist"
CLIENT_DIST_INDEX_FILE = CLIENT_DIST_DIR / "index.html"
DESCRIPTION_FILE = PROJECT_ROOT / "profiles" / "description.txt"
RESEARCHER_PROFILE_FILE = PROJECT_ROOT / "profiles" / "researcher_profile.md"
TWITTER_ACCOUNTS_FILE = PROJECT_ROOT / "profiles" / "x_accounts.txt"
SWIPE_FEEDBACK_FILE = PROJECT_ROOT / "profiles" / "swipe_feedback.json"
USERS_DIR = PROJECT_ROOT / "users"
GITHUB_REPO_URL = "https://github.com/LiYu0524/daily-recommender"
DEFAULT_CONFIG = {
"desktop_python_path": "",
"provider": "openai",
"model": "gpt-4o-mini",
"base_url": "",
"api_key": "",
"temperature": 0.5,
"smtp_server": "",
"smtp_port": 465,
"sender": "",
"receiver": "",
"smtp_password": "",
"gh_languages": "all",
"gh_since": "daily",
"gh_max_repos": 30,
"hf_content_types": ["papers", "models"],
"hf_max_papers": 30,
"hf_max_models": 15,
"description": "",
"researcher_profile": "",
"x_rapidapi_key": "",
"x_rapidapi_host": "twitter-api45.p.rapidapi.com",
"x_accounts": "",
"arxiv_categories": "cs.AI",
"arxiv_max_entries": 100,
"arxiv_max_papers": 60,
"ss_max_results": 60,
"ss_max_papers": 30,
"ss_year": "",
"ss_api_key": "",
"rss_urls": "https://imjuya.github.io/juya-ai-daily/rss.xml",
"rss_max_items": 30,
"schedule_enabled": False,
"schedule_frequency": "daily",
"schedule_time": "08:00",
"schedule_sources": [],
"schedule_generate_report": False,
"schedule_generate_ideas": False,
}
app = FastAPI(title="Daily Recommender API", version="1.0.0")
# Bot integration (Telegram / Feishu)
from bot import setup_bot_routes
setup_bot_routes(app)
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============== User isolation ==============
def _email_to_user_id(email: str) -> str:
"""Stable short hash from email for directory naming."""
import hashlib
return hashlib.sha256(email.strip().lower().encode()).hexdigest()[:16]
def _get_user_dir(user_id: str) -> Path | None:
"""Return the user's data directory, or None for anonymous/desktop."""
if not user_id:
return None
d = USERS_DIR / user_id
d.mkdir(parents=True, exist_ok=True)
return d
def _user_description_path(user_id: str) -> Path:
d = _get_user_dir(user_id)
return (d / "description.txt") if d else DESCRIPTION_FILE
def _user_swipe_path(user_id: str) -> Path:
d = _get_user_dir(user_id)
return (d / "swipe_feedback.json") if d else SWIPE_FEEDBACK_FILE
def _user_config_path(user_id: str) -> Path:
d = _get_user_dir(user_id)
return (d / "config.json") if d else CONFIG_FILE
def _resolve_user_id(request) -> str:
"""Extract user_id from X-User-Id header. Empty = anonymous/desktop."""
return (request.headers.get("x-user-id") or "").strip()
@app.post("/api/auth/login")
def auth_login(payload: dict):
"""Email-based login (no password). Creates user dir if first time."""
email = (payload.get("email") or "").strip().lower()
if not email or "@" not in email:
return JSONResponse({"error": "Invalid email"}, status_code=400)
user_id = _email_to_user_id(email)
user_dir = _get_user_dir(user_id)
# Save email mapping
meta_path = user_dir / "meta.json"
if not meta_path.exists():
meta_path.write_text(json.dumps({"email": email, "created": datetime.now().isoformat()}, ensure_ascii=False), encoding="utf-8")
# New user starts with empty description — setup flow will prompt
needs_setup = not (user_dir / "description.txt").exists()
return {"user_id": user_id, "email": email, "needs_setup": needs_setup}
@app.get("/api/user/description")
def get_user_description(request: Request):
uid = _resolve_user_id(request)
path = _user_description_path(uid)
content = path.read_text(encoding="utf-8") if path.exists() else ""
return {"description": content}
@app.post("/api/user/description")
def save_user_description(request: Request, payload: dict):
uid = _resolve_user_id(request)
desc = (payload.get("description") or "").strip()
if not desc:
return JSONResponse({"error": "Description cannot be empty"}, status_code=400)
path = _user_description_path(uid)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(desc + "\n", encoding="utf-8")
return {"status": "ok"}
@app.get("/api/auth/me")
def auth_me(request: Request):
"""Return current user info based on X-User-Id header."""
user_id = _resolve_user_id(request)
if not user_id:
return {"user_id": "", "email": "", "anonymous": True}
user_dir = _get_user_dir(user_id)
meta_path = user_dir / "meta.json"
if meta_path.exists():
meta = json.loads(meta_path.read_text(encoding="utf-8"))
return {"user_id": user_id, "email": meta.get("email", ""), "anonymous": False}
return {"user_id": user_id, "email": "", "anonymous": True}
# ============== Utilities ==============
def _read_text_if_exists(path: Path) -> str:
if path.exists():
return path.read_text(encoding="utf-8").strip()
return ""
def _decode_process_line(raw: bytes) -> str:
preferred = locale.getpreferredencoding(False) or "utf-8"
tried: list[str] = []
for encoding in (preferred, "utf-8", "gbk", "cp936"):
normalized = encoding.lower()
if normalized in tried:
continue
tried.append(normalized)
try:
return raw.decode(encoding).rstrip()
except UnicodeDecodeError:
continue
return raw.decode(preferred, errors="replace").rstrip()
def _normalize_multiline_text(value: str) -> str:
lines = [line.rstrip() for line in str(value or "").replace("\r\n", "\n").split("\n")]
return "\n".join(lines).strip()
def _load_env_fallbacks() -> dict:
if not ENV_FILE.exists():
return {}
raw_values: dict[str, str] = {}
for raw_line in ENV_FILE.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
if key.startswith("export "):
key = key[len("export "):].strip()
if value and value[0] == value[-1] and value[0] in ("'", '"'):
value = value[1:-1]
raw_values[key] = value
fallback: dict[str, object] = {}
mapping = {
"desktop_python_path": "DESKTOP_PYTHON_PATH",
"provider": "PROVIDER",
"model": "MODEL_NAME",
"base_url": "BASE_URL",
"api_key": "API_KEY",
"smtp_server": "SMTP_SERVER",
"sender": "SMTP_SENDER",
"receiver": "SMTP_RECEIVER",
"smtp_password": "SMTP_PASSWORD",
"gh_languages": "GH_LANGUAGES",
"gh_since": "GH_SINCE",
"gh_max_repos": "GH_MAX_REPOS",
"hf_max_papers": "HF_MAX_PAPERS",
"hf_max_models": "HF_MAX_MODELS",
"x_rapidapi_key": "X_RAPIDAPI_KEY",
"x_rapidapi_host": "X_RAPIDAPI_HOST",
}
for config_key, env_key in mapping.items():
value = raw_values.get(env_key, "")
if value:
fallback[config_key] = value
if raw_values.get("TEMPERATURE"):
fallback["temperature"] = float(raw_values["TEMPERATURE"])
if raw_values.get("SMTP_PORT"):
fallback["smtp_port"] = int(raw_values["SMTP_PORT"])
if raw_values.get("GH_MAX_REPOS"):
fallback["gh_max_repos"] = int(raw_values["GH_MAX_REPOS"])
if raw_values.get("HF_MAX_PAPERS"):
fallback["hf_max_papers"] = int(raw_values["HF_MAX_PAPERS"])
if raw_values.get("HF_MAX_MODELS"):
fallback["hf_max_models"] = int(raw_values["HF_MAX_MODELS"])
if raw_values.get("HF_CONTENT_TYPES"):
fallback["hf_content_types"] = [item for item in raw_values["HF_CONTENT_TYPES"].split() if item]
return fallback
def load_config_data() -> dict:
config = dict(DEFAULT_CONFIG)
env_fallbacks = _load_env_fallbacks()
config.update(env_fallbacks)
for config_file in (CONFIG_FILE, CLIENT_CONFIG_FILE):
if config_file.exists():
content = config_file.read_text(encoding="utf-8").strip()
if content:
config.update(json.loads(content))
# File-backed values are used as fallback only when the JSON config
# does not already contain a non-empty value for the key. Previously
# they unconditionally overwrote the JSON config, which caused the
# saved description to be ignored if the file still held old content.
file_backed_values = {
"description": _read_text_if_exists(DESCRIPTION_FILE),
"researcher_profile": _read_text_if_exists(RESEARCHER_PROFILE_FILE),
"x_accounts": _read_text_if_exists(TWITTER_ACCOUNTS_FILE),
}
for key, value in file_backed_values.items():
if value and not config.get(key):
config[key] = value
if not config.get("hf_content_types"):
config["hf_content_types"] = ["papers", "models"]
if not config.get("x_rapidapi_host"):
config["x_rapidapi_host"] = DEFAULT_CONFIG["x_rapidapi_host"]
return config
def _write_text_file(path: Path, content: str, delete_if_empty: bool = False) -> None:
normalized = _normalize_multiline_text(content)
path.parent.mkdir(parents=True, exist_ok=True)
if normalized:
path.write_text(normalized + "\n", encoding="utf-8")
return
if delete_if_empty:
if path.exists():
path.unlink()
return
path.write_text("", encoding="utf-8")
def _append_arg(cmd: list[str], flag: str, value: str | int | float | None) -> None:
if value in (None, ""):
return
cmd.extend([flag, str(value)])
def _resolve_client_dist_path(relative_path: str) -> Path | None:
if not CLIENT_DIST_DIR.exists():
return None
candidate = (CLIENT_DIST_DIR / relative_path).resolve()
dist_root = CLIENT_DIST_DIR.resolve()
if candidate != dist_root and dist_root not in candidate.parents:
return None
return candidate
def _merge_unique_strings(*groups: list[str]) -> list[str]:
merged: list[str] = []
seen: set[str] = set()
for group in groups:
for item in group:
value = item.strip()
if not value:
continue
key = value.lower()
if key in seen:
continue
seen.add(key)
merged.append(value)
return merged
def _normalize_x_username(raw_value: str) -> str | None:
candidate = raw_value.strip().lstrip("@")
if not candidate:
return None
if re.fullmatch(r"[A-Za-z0-9_]{1,15}", candidate):
return candidate
return None
def _extract_x_username(raw_value: str) -> str | None:
candidate = raw_value.strip()
if not candidate:
return None
if re.match(r"^(?:www\.)?(?:mobile\.)?(?:x|twitter)\.com/", candidate, flags=re.IGNORECASE):
candidate = "https://" + candidate.lstrip("/")
if not re.match(r"^https?://", candidate, flags=re.IGNORECASE):
return _normalize_x_username(candidate)
parsed = urlparse(candidate)
host = parsed.netloc.lower()
if host.startswith("www."):
host = host[4:]
if host not in {"x.com", "twitter.com", "mobile.twitter.com"}:
return None
segments = [segment for segment in parsed.path.split("/") if segment]
if not segments:
return None
reserved_segments = {
"explore",
"hashtag",
"home",
"i",
"intent",
"messages",
"notifications",
"search",
"settings",
"share",
"tos",
"privacy",
}
if segments[0].lower() in reserved_segments:
return None
return _normalize_x_username(segments[0])
def _parse_x_accounts_input(raw_text: str) -> tuple[list[str], list[str]]:
usernames: list[str] = []
invalid_entries: list[str] = []
for raw_line in str(raw_text or "").replace("\r\n", "\n").split("\n"):
line = raw_line.strip()
if not line or line.startswith("#"):
continue
username = _extract_x_username(line)
if username:
usernames.append(username)
else:
invalid_entries.append(line)
return _merge_unique_strings(usernames), invalid_entries
def _collect_generated_files(result_dirs: list[Path]) -> list[dict]:
generated_files = []
for dir_path in result_dirs:
if not dir_path.exists():
continue
for md_file in dir_path.glob("*.md"):
content = md_file.read_text(encoding="utf-8")
generated_files.append({
"type": "markdown",
"name": md_file.name,
"content": content,
"source": dir_path.parent.name,
})
for html_file in dir_path.glob("*.html"):
generated_files.append({
"type": "html",
"name": html_file.name,
"url": f"/api/file/{dir_path.parent.name}/{dir_path.name}/{html_file.name}",
"source": dir_path.parent.name,
})
json_dir = dir_path / "json"
if json_dir.exists():
items = []
for json_file in json_dir.glob("*.json"):
data = json.loads(json_file.read_text(encoding="utf-8"))
items.append(data)
if items:
generated_files.append({
"type": "json_list",
"name": f"{dir_path.parent.name}_items",
"items": items,
"source": dir_path.parent.name,
})
return generated_files
# ============== Models ==============
class Config(BaseModel):
desktop_python_path: str = ""
provider: str = "openai"
model: str = "gpt-4o-mini"
base_url: str = ""
api_key: str = ""
temperature: float = 0.5
smtp_server: str = ""
smtp_port: int = 465
sender: str = ""
receiver: str = ""
smtp_password: str = ""
gh_languages: str = "all"
gh_since: str = "daily"
gh_max_repos: int = 30
hf_content_types: list[str] = ["papers", "models"]
hf_max_papers: int = 30
hf_max_models: int = 15
description: str = ""
researcher_profile: str = ""
x_rapidapi_key: str = ""
x_rapidapi_host: str = "twitter-api45.p.rapidapi.com"
x_accounts: str = ""
arxiv_categories: str = "cs.AI"
arxiv_max_entries: int = 100
arxiv_max_papers: int = 60
ss_max_results: int = 60
ss_max_papers: int = 30
ss_year: str = ""
ss_api_key: str = ""
rss_urls: str = "https://imjuya.github.io/juya-ai-daily/rss.xml"
rss_max_items: int = 30
schedule_enabled: bool = False
schedule_frequency: str = "daily"
schedule_time: str = "08:00"
schedule_sources: list[str] = []
schedule_generate_report: bool = False
schedule_generate_ideas: bool = False
class RunRequest(BaseModel):
sources: list[str]
generate_report: bool = False
generate_ideas: bool = False
save: bool = True
receiver: str = ""
description: str = ""
researcher_profile: str = ""
scholar_urls: str = ""
x_accounts_input: str = ""
delivery_mode: Literal["source_emails", "combined_report", "both", "save_only"] = "source_emails"
# ============== Config API ==============
@app.get("/api/config")
def get_config():
"""获取当前配置"""
return load_config_data()
@app.get("/api/public/meta")
def get_public_meta():
config = load_config_data()
return {
"github_url": GITHUB_REPO_URL,
"twitter_enabled": bool(config.get("x_rapidapi_key")),
"mail_enabled": bool(config.get("smtp_server") and config.get("sender")),
"arxiv_enabled": True,
}
@app.post("/api/config")
def save_config(config: Config):
"""保存配置"""
try:
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump() if hasattr(config, "model_dump") else config.dict()
config_dict["description"] = _normalize_multiline_text(config_dict.get("description", ""))
config_dict["researcher_profile"] = _normalize_multiline_text(config_dict.get("researcher_profile", ""))
config_dict["x_accounts"] = _normalize_multiline_text(config_dict.get("x_accounts", ""))
serialized_config = json.dumps(config_dict, indent=2, ensure_ascii=False)
CONFIG_FILE.write_text(serialized_config, encoding="utf-8")
CLIENT_CONFIG_FILE.write_text(serialized_config, encoding="utf-8")
env_content = f"""# Auto-generated by web UI
DESKTOP_PYTHON_PATH={config.desktop_python_path}
PROVIDER={config.provider}
MODEL_NAME={config.model}
BASE_URL={config.base_url}
API_KEY={config.api_key}
TEMPERATURE={config.temperature}
SMTP_SERVER={config.smtp_server}
SMTP_PORT={config.smtp_port}
SMTP_SENDER={config.sender}
SMTP_RECEIVER={config.receiver}
SMTP_PASSWORD={config.smtp_password}
GH_LANGUAGES={config.gh_languages}
GH_SINCE={config.gh_since}
GH_MAX_REPOS={config.gh_max_repos}
HF_CONTENT_TYPES={" ".join(config.hf_content_types)}
HF_MAX_PAPERS={config.hf_max_papers}
HF_MAX_MODELS={config.hf_max_models}
DESCRIPTION_FILE=profiles/description.txt
X_RAPIDAPI_KEY={config.x_rapidapi_key}
X_RAPIDAPI_HOST={config.x_rapidapi_host}
X_ACCOUNTS_FILE=profiles/x_accounts.txt
ARXIV_CATEGORIES={config.arxiv_categories}
ARXIV_MAX_ENTRIES={config.arxiv_max_entries}
ARXIV_MAX_PAPERS={config.arxiv_max_papers}
SS_MAX_RESULTS={config.ss_max_results}
SS_MAX_PAPERS={config.ss_max_papers}
SS_YEAR={config.ss_year}
SS_API_KEY={config.ss_api_key}
RSS_URLS={config.rss_urls}
RSS_MAX_ITEMS={config.rss_max_items}
"""
(PROJECT_ROOT / ".env").write_text(env_content, encoding="utf-8")
_write_text_file(DESCRIPTION_FILE, config.description)
_write_text_file(RESEARCHER_PROFILE_FILE, config.researcher_profile, delete_if_empty=True)
_write_text_file(TWITTER_ACCOUNTS_FILE, config.x_accounts)
return {"status": "ok"}
except Exception as e:
import traceback
print(f"保存配置失败: {e}")
print(traceback.format_exc())
return JSONResponse({"status": "error", "message": str(e)}, status_code=500)
# ============== Run API ==============
async def run_daily_recommender(req: RunRequest, extra_args: list[str] | None = None):
"""异步运行 daily-recommender"""
if not req.sources:
raise ValueError("请至少选择一个信息源。")
local_today = datetime.now().strftime("%Y-%m-%d")
utc_today = datetime.utcnow().strftime("%Y-%m-%d")
date_candidates = list(dict.fromkeys([local_today, utc_today]))
result_dirs: list[Path] = []
config = load_config_data()
temp_dir = tempfile.TemporaryDirectory(prefix="daily-recommender-web-")
temp_root = Path(temp_dir.name)
try:
override_description = _normalize_multiline_text(req.description)
receiver = req.receiver.strip() or str(config.get("receiver", "")).strip()
custom_x_accounts, invalid_x_accounts = _parse_x_accounts_input(req.x_accounts_input)
effective_description = override_description or _normalize_multiline_text(config.get("description", ""))
report_profile_path: Path | None = None
description_path: Path | None = None
researcher_profile_path: Path | None = None
profile_urls: list[str] = [
url.strip()
for url in re.split(r"[\n,]+", req.scholar_urls)
if url.strip()
]
if invalid_x_accounts:
preview = "、".join(invalid_x_accounts[:3])
raise ValueError(
f"以下 X 信息源无法识别:{preview}。仅支持 用户名、@用户名 或 https://x.com/username 链接。"
)
if profile_urls:
yield {"type": "log", "message": f"正在读取 {len(profile_urls)} 个 Google Scholar / 主页信息..."}
profile_text, _ = await asyncio.to_thread(build_profile_text_from_urls, profile_urls)
profile_text = _normalize_multiline_text(profile_text)
if profile_text:
effective_description = "\n\n".join(
part
for part in [
effective_description,
"[Optional profile URL context]\n" + profile_text,
]
if part
).strip()
yield {"type": "log", "message": f"已附加 {len(profile_urls)} 个 Scholar 画像信息到本次请求。"}
else:
yield {"type": "log", "message": "Scholar 页面未返回可用文本,将继续使用输入兴趣。"}
if effective_description:
description_path = temp_root / "description.txt"
description_path.write_text(effective_description + "\n", encoding="utf-8")
report_profile_path = description_path
if req.researcher_profile.strip():
researcher_profile_path = temp_root / "researcher_profile.md"
researcher_profile_path.write_text(
_normalize_multiline_text(req.researcher_profile) + "\n",
encoding="utf-8",
)
report_profile_path = researcher_profile_path
elif req.generate_ideas:
base_profile = _normalize_multiline_text(config.get("researcher_profile", "")) or effective_description
if not base_profile:
raise ValueError("生成研究想法前,请先配置研究者画像或在本次请求中填写兴趣描述。")
researcher_profile_path = temp_root / "researcher_profile.md"
researcher_profile_path.write_text(base_profile + "\n", encoding="utf-8")
should_generate_report = req.generate_report or req.delivery_mode in ("combined_report", "both")
should_send_combined_report = req.delivery_mode in ("combined_report", "both")
should_skip_source_emails = req.delivery_mode in ("combined_report", "save_only")
if should_send_combined_report and not receiver:
raise ValueError("请输入接收邮件的邮箱地址。")
if receiver and (not config.get("smtp_server") or not config.get("sender")):
raise ValueError("服务器还没有配置发件邮箱,请先在 /admin 完成 SMTP 配置。")
cmd = [
sys.executable,
"main.py",
"--sources",
*req.sources,
"--num_workers",
"4",
"--provider",
config.get("provider", "openai"),
"--model",
config.get("model", "gpt-4o-mini"),
"--base_url",
config.get("base_url", ""),
"--api_key",
config.get("api_key", ""),
"--temperature",
str(config.get("temperature", 0.5)),
]
if req.save:
cmd.append("--save")
if description_path:
_append_arg(cmd, "--description", description_path)
# Pass profile hash for eval cache isolation
if effective_description:
from core.cache_utils import stable_profile_hash
_append_arg(cmd, "--profile_hash", stable_profile_hash(effective_description))
if should_generate_report:
cmd.append("--generate_report")
for d in date_candidates:
result_dirs.append(HISTORY_DIR / "reports" / d)
if report_profile_path:
_append_arg(cmd, "--report_profile", report_profile_path)
if should_send_combined_report:
cmd.append("--send_report_email")
if should_skip_source_emails:
cmd.append("--skip_source_emails")
if req.generate_ideas:
if not researcher_profile_path:
raise ValueError("生成研究想法需要研究者画像。")
cmd.extend(["--generate_ideas", "--researcher_profile", str(researcher_profile_path)])
for d in date_candidates:
result_dirs.append(HISTORY_DIR / "ideas" / d)
_append_arg(cmd, "--smtp_server", config.get("smtp_server"))
_append_arg(cmd, "--smtp_port", config.get("smtp_port"))
_append_arg(cmd, "--sender", config.get("sender"))
_append_arg(cmd, "--receiver", receiver)
_append_arg(cmd, "--sender_password", config.get("smtp_password"))
cmd.extend([
"--gh_languages",
config.get("gh_languages", "all"),
"--gh_since",
config.get("gh_since", "daily"),
"--gh_max_repos",
str(config.get("gh_max_repos", 30)),
])
hf_types = config.get("hf_content_types", ["papers", "models"]) or ["papers", "models"]
cmd.extend([
"--hf_content_type",
*hf_types,
"--hf_max_papers",
str(config.get("hf_max_papers", 30)),
"--hf_max_models",
str(config.get("hf_max_models", 15)),
])
if "twitter" in req.sources:
_append_arg(cmd, "--x_rapidapi_key", config.get("x_rapidapi_key"))
_append_arg(cmd, "--x_rapidapi_host", config.get("x_rapidapi_host"))
accounts_file_path: Path = TWITTER_ACCOUNTS_FILE
if custom_x_accounts:
static_x_accounts, _ = _parse_x_accounts_input(_read_text_if_exists(TWITTER_ACCOUNTS_FILE))
merged_x_accounts = _merge_unique_strings(custom_x_accounts, static_x_accounts)
accounts_file_path = temp_root / "x_accounts.request.txt"
accounts_file_path.write_text("\n".join(merged_x_accounts) + "\n", encoding="utf-8")
yield {
"type": "log",
"message": f"已附加 {len(custom_x_accounts)} 个本次请求专用的 X 信息源。",
}
_append_arg(cmd, "--x_accounts_file", accounts_file_path)
should_run_oneoff_discovery = bool(override_description or profile_urls)
if should_run_oneoff_discovery:
discovery_persist_file = temp_root / "x_accounts.discovered.txt"
cmd.extend([
"--x_discover_accounts",
"--x_merge_static_accounts",
"--x_force_refresh_discovery",
"--x_discovery_persist_file",
str(discovery_persist_file),
])
if profile_urls:
cmd.extend(["--x_profile_urls", *profile_urls])
if "arxiv" in req.sources:
arxiv_cats = config.get("arxiv_categories", "cs.AI")
cat_list = [c.strip() for c in arxiv_cats.split() if c.strip()]
cmd.extend(["--arxiv_categories", *cat_list])
cmd.extend([
"--arxiv_max_entries",
str(config.get("arxiv_max_entries", 100)),
"--arxiv_max_papers",
str(config.get("arxiv_max_papers", 60)),
])
if "semanticscholar" in req.sources:
cmd.extend([
"--ss_max_results",
str(config.get("ss_max_results", 60)),
"--ss_max_papers",
str(config.get("ss_max_papers", 30)),
])
ss_year = config.get("ss_year", "")
if ss_year:
cmd.extend(["--ss_year", ss_year])
ss_api_key = config.get("ss_api_key", "")
if ss_api_key:
cmd.extend(["--ss_api_key", ss_api_key])
if "rss" in req.sources:
rss_urls = [url.strip() for url in re.split(r"[\s,]+", str(config.get("rss_urls", ""))) if url.strip()]
if rss_urls:
cmd.extend(["--rss_urls", *rss_urls])
cmd.extend(["--rss_max_items", str(config.get("rss_max_items", 30))])
if extra_args:
cmd.extend(extra_args)
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
cwd=str(PROJECT_ROOT),
)
while True:
line = await process.stdout.readline()
if not line:
break
text = _decode_process_line(line)
yield {"type": "log", "message": text}
await process.wait()
for src in req.sources:
for d in date_candidates:
result_dirs.append(HISTORY_DIR / src / d)
# De-duplicate candidate directories while preserving order.
dedup_result_dirs: list[Path] = []
seen_dirs: set[str] = set()
for p in result_dirs:
key = str(p)
if key in seen_dirs:
continue
seen_dirs.add(key)
dedup_result_dirs.append(p)
generated_files = _collect_generated_files(dedup_result_dirs)
def _date_has_artifacts(date_str: str) -> bool:
candidate_dirs: list[Path] = []
for src in req.sources:
candidate_dirs.append(HISTORY_DIR / src / date_str)
if should_generate_report:
candidate_dirs.append(HISTORY_DIR / "reports" / date_str)
if req.generate_ideas:
candidate_dirs.append(HISTORY_DIR / "ideas" / date_str)
for d in candidate_dirs:
if not d.exists() or not d.is_dir():
continue
has_md = any(d.glob("*.md"))
has_html = any(d.glob("*.html"))
has_json = (d / "json").exists() and any((d / "json").glob("*.json"))
if has_md or has_html or has_json:
return True
return False
resolved_date = local_today
for d in date_candidates:
if _date_has_artifacts(d):
resolved_date = d
break
yield {
"type": "complete",
"exit_code": process.returncode,
"success": process.returncode == 0,
"files": generated_files,
"date": resolved_date,
}
finally:
temp_dir.cleanup()
@app.websocket("/ws/run")
async def websocket_run(websocket: WebSocket):
"""WebSocket 实时运行日志"""
await websocket.accept()
try:
data = await websocket.receive_json()
req = RunRequest(**data)
await websocket.send_json({"type": "start", "message": "开始运行..."})
async for msg in run_daily_recommender(req):
await websocket.send_json(msg)
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
await websocket.send_json({
"type": "error",
"message": str(e),
})
# ============== History API ==============
@app.get("/api/history")
def get_history():
"""获取历史运行记录"""
history = []
if not HISTORY_DIR.exists():
return []
for source_dir in HISTORY_DIR.iterdir():
if not source_dir.is_dir():
continue
source_name = source_dir.name
for date_dir in source_dir.iterdir():
if not date_dir.is_dir():
continue
date_str = date_dir.name
has_results = list(date_dir.glob("*.md")) or list(date_dir.glob("*.html"))
json_files = list(date_dir.glob("json/*.json"))
if has_results or json_files:
history.append({
"id": f"{source_name}_{date_str}",
"type": source_name,
"date": date_str,
"sources": [source_name.replace("_", ", ")],
"items": len(json_files),
"path": str(date_dir.relative_to(PROJECT_ROOT)),
})
history.sort(key=lambda x: x["date"], reverse=True)
return history
@app.get("/api/results/{source}/{date}")
def get_results(source: str, date: str):
"""获取某天的详细结果"""
result_dir = HISTORY_DIR / source / date
if not result_dir.exists():
return JSONResponse({"error": "Not found"}, status_code=404)
results = {
"source": source,
"date": date,
"markdown_files": [],
"html_files": [],
"json_files": [],
}
for f in result_dir.glob("*.md"):
results["markdown_files"].append({
"name": f.name,
"content": f.read_text(encoding="utf-8"),
})
for f in result_dir.glob("*.html"):
results["html_files"].append({
"name": f.name,
"url": f"/api/file/{source}/{date}/{f.name}",
})
json_dir = result_dir / "json"
if json_dir.exists():
for f in json_dir.glob("*.json"):
results["json_files"].append({
"name": f.name,
"data": json.loads(f.read_text(encoding="utf-8")),
})
return results
@app.get("/api/file/{source}/{date}/{filename}")
def get_file(source: str, date: str, filename: str):
"""获取文件内容"""
file_path = HISTORY_DIR / source / date / filename
if not file_path.exists():
return JSONResponse({"error": "Not found"}, status_code=404)
return FileResponse(file_path)
# ============== Static Files ==============