-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathleetcode.py
More file actions
1251 lines (1116 loc) · 47.9 KB
/
leetcode.py
File metadata and controls
1251 lines (1116 loc) · 47.9 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
#!/usr/bin/env python3
"""
LeetCode 工具集 - 主入口
支持交互式初始化、浏览器 Cookie 自动检测、多语言界面
使用方法:
python leetcode.py # 默认中文界面
python leetcode.py --en # 英文界面
python leetcode.py --init # 强制进入初始化向导
"""
import argparse
import asyncio
import datetime
import json
import logging
import math
import os
import random
import re
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from dotenv import load_dotenv, set_key
# Setup paths
file_path = Path(__file__)
root_path = file_path.parent.parent.parent
sys.path.insert(0, root_path.as_posix())
# Import CLI modules
from python.scripts.cli import (
t, set_language, get_language,
input_until_valid, input_pick_array,
get_browser_cookie, read_cookie_from_file, HAS_BROWSER_COOKIE,
check_and_update_cookie,
)
from python.scripts.cli.input_utils import allow_all, allow_all_not_empty, allow_number
# Import LeetCode libraries
from python.constants import constant
from python.lc_libs import get_daily_question, query_my_favorites, batch_add_questions_to_favorite, \
query_favorite_questions, contest as contest_lib
import python.lc_libs as lc_libs
from python.scripts.submit import main as submit_main_async
from python.utils import back_question_id, format_question_id, check_cookie_expired, create_link
from python.scripts.daily_auto import main as daily_auto_main
from python.scripts.get_problem import main as get_problem_main, get_question_slug_by_id
from python.scripts.tools import lucky_main, remain_main, clean_empty_java_main, clean_error_rust_main
from python.scripts.fetch_solution_articles import main as fetch_solution_main
from python.scripts.repository_health import scan_repository, format_report, build_fix_suggestions, apply_fix
# Constants
SEPARATE_LINE = "-" * 50
SUPPORTED_LANGUAGES = ["python3", "java", "golang", "cpp", "typescript", "rust"]
# ============================================================================
# Initialization and Configuration
# ============================================================================
def initialize_env():
"""Interactive environment initialization wizard"""
print("\n" + "=" * 50)
print(t("init_title"))
print("=" * 50)
env_file = root_path / ".env"
# Step 1: Auto-detect browser cookie
print(f"\n{t('init_step1')}")
cookie = None
max_retries = 3
retry_count = 0
if HAS_BROWSER_COOKIE:
while retry_count < max_retries:
result = get_browser_cookie()
if result:
cookie, browser_name, cookie_count = result
print(t("init_found_cookie", browser=browser_name, count=cookie_count))
# Verify cookie immediately
print(t("init_verifying"))
if check_cookie_expired(cookie):
print(t("init_cookie_invalid"))
print(t("cookie_auto_expired_hint"))
retry = input_until_valid(t("init_retry_login"), allow_all)
if retry != "n":
retry_count += 1
if retry_count >= max_retries:
print(t("init_max_retries"))
cookie = None
break
print(t("init_waiting_login"))
input() # Wait for user to press Enter after logging in
continue
else:
cookie = None
else:
print(t("init_cookie_valid"))
break
else:
print(t("init_no_cookie"))
print(t("cookie_no_browser_hint"))
break
else:
print(t("init_browser_not_installed"))
print(t("init_browser_install_hint"))
if not cookie:
cookie = read_cookie_from_file()
if not cookie:
cookie = input_until_valid(
t("init_enter_cookie"),
allow_all_not_empty,
t("init_cookie_empty")
)
print(SEPARATE_LINE)
# Load existing config or use defaults
if env_file.exists():
try:
load_dotenv(dotenv_path=env_file.as_posix())
except Exception as e:
print(t("init_load_failed", error=e))
existing_languages = os.getenv(constant.LANGUAGES, "python3").split(",")
existing_problem_folder = os.getenv(constant.PROBLEM_FOLDER, "problems")
existing_contest_folder = os.getenv(constant.CONTEST_FOLDER, "contest")
existing_config_str = f"{','.join(existing_languages)}, {existing_problem_folder}, {existing_contest_folder}"
skip_config = input_until_valid(
t("init_skip_config", config=existing_config_str),
allow_all
)
if skip_config.lower() != "n":
languages = existing_languages
problem_folder = existing_problem_folder
contest_folder = existing_contest_folder
print(t("init_skip_confirmed"))
print(SEPARATE_LINE)
# Save to .env
save_config = input_until_valid(
t("init_save_config"),
allow_all
)
if save_config != "n":
env_file.touch() # Ensure file exists
set_key(env_file.as_posix(), constant.COOKIE, cookie)
set_key(env_file.as_posix(), constant.PROBLEM_FOLDER, problem_folder)
set_key(env_file.as_posix(), constant.CONTEST_FOLDER, contest_folder)
set_key(env_file.as_posix(), constant.LANGUAGES, ",".join(languages))
set_key(env_file.as_posix(), "PYTHONPATH", ".")
print(t("init_saved", path=env_file))
print("\n" + "=" * 50)
print(t("init_done"))
print("=" * 50 + "\n")
else:
print(t("init_not_saved"))
print(SEPARATE_LINE)
return languages, problem_folder, cookie, contest_folder
# Step 2: Select languages
print(f"\n{t('init_step2')}")
lang_options = "\n".join(f"{idx}. {lang}" for idx, lang in enumerate(SUPPORTED_LANGUAGES))
pick_languages = input_until_valid(
t("init_select_lang", options=lang_options),
lambda x: re.match(r"^[0-5](,[0-5])*$", x),
t("init_lang_invalid")
)
languages = list(set(SUPPORTED_LANGUAGES[int(idx)] for idx in pick_languages.split(",")))
print(t("init_lang_selected", langs=", ".join(languages)))
print(SEPARATE_LINE)
# Step 3: Set problem folder
print(f"\n{t('init_step3')}")
input_problem_folder = input_until_valid(
t("init_problem_folder"),
allow_all
)
problem_folder = input_problem_folder if input_problem_folder else "problems"
print(t("init_folder_selected", folder=problem_folder))
input_contest_folder = input_until_valid(
t("init_contest_folder"),
allow_all
)
contest_folder = input_contest_folder if input_contest_folder else "contest"
print(t("init_folder_selected", folder=contest_folder))
print(SEPARATE_LINE)
# Step 4: Optional notification
print(f"\n{t('init_step4')}")
push_key = input_until_valid(
t("init_push_key"),
allow_all
)
if push_key:
print(t("init_notify_configured"))
else:
print(t("init_notify_skipped"))
print(SEPARATE_LINE)
# Save to .env
save_config = input_until_valid(
t("init_save_config"),
allow_all
)
if save_config != "n":
env_file.touch() # Ensure file exists
set_key(env_file.as_posix(), constant.COOKIE, cookie)
set_key(env_file.as_posix(), constant.PROBLEM_FOLDER, problem_folder)
set_key(env_file.as_posix(), constant.CONTEST_FOLDER, contest_folder)
set_key(env_file.as_posix(), constant.LANGUAGES, ",".join(languages))
if push_key:
set_key(env_file.as_posix(), constant.PUSH_KEY, push_key)
set_key(env_file.as_posix(), "PYTHONPATH", ".")
print(t("init_saved", path=env_file))
print("\n" + "=" * 50)
print(t("init_done"))
print("=" * 50 + "\n")
else:
print(t("init_not_saved"))
print(SEPARATE_LINE)
return languages, problem_folder, cookie, contest_folder
def configure():
"""Main configuration function"""
env_file = root_path / ".env"
# Check if .env exists
if not env_file.exists():
print(t("init_no_cookie_hint").replace("请确保你已在浏览器中登录 leetcode.cn", "未找到 .env 文件,启动初始化向导..."))
return initialize_env()
# Load existing .env
try:
load_dotenv(dotenv_path=env_file.as_posix())
except Exception:
pass
print(t("config_title"))
config_select = input_until_valid(t("config_select"), allow_all)
print(SEPARATE_LINE)
if config_select == "2":
# Re-initialize
return initialize_env()
if config_select == "1":
# Custom config
lang_options = "\n".join(f"{idx}. {lang}" for idx, lang in enumerate(SUPPORTED_LANGUAGES))
pick_languages = input_until_valid(
t("init_select_lang", options=lang_options),
lambda x: re.match(r"^[0-5](,[0-5])*$", x),
t("init_lang_invalid")
)
languages = list(set(SUPPORTED_LANGUAGES[int(idx)] for idx in pick_languages.split(",")))
print(t("init_lang_selected", langs=", ".join(languages)))
print(SEPARATE_LINE)
input_problem_folder = input_until_valid(
t("init_problem_folder"),
allow_all
)
problem_folder = input_problem_folder if input_problem_folder else os.getenv(constant.PROBLEM_FOLDER, "problems")
print(t("init_folder_selected", folder=problem_folder))
print(SEPARATE_LINE)
input_contest_folder = input_until_valid(
t("init_contest_folder"),
allow_all
)
contest_folder = input_contest_folder if input_contest_folder else os.getenv(constant.CONTEST_FOLDER, "contest")
print(t("init_folder_selected", folder=contest_folder))
print(SEPARATE_LINE)
# Try auto-detect cookie first
cookie = None
if HAS_BROWSER_COOKIE:
auto_detect = input_until_valid(
t("config_auto_detect"),
allow_all
)
if auto_detect != "n":
print(t("config_detecting"))
result = get_browser_cookie()
if result:
cookie, browser_name, cookie_count = result
print(t("init_found_cookie", browser=browser_name, count=cookie_count))
else:
print(t("config_no_browser_cookie"))
print(SEPARATE_LINE)
if not cookie:
cookie = read_cookie_from_file()
if not cookie:
input_cookie = input_until_valid(
t("config_enter_cookie"),
allow_all
)
cookie = input_cookie.strip() if input_cookie else os.getenv(constant.COOKIE)
cookie = check_and_update_cookie(cookie)
print(SEPARATE_LINE)
update_config = input_until_valid(
t("config_update_env"),
allow_all
)
if update_config == "y":
with env_file.open("w") as f:
f.write(f'{constant.COOKIE}="{cookie}"\n')
f.write(f'{constant.PROBLEM_FOLDER}="{problem_folder}"\n')
f.write(f'{constant.CONTEST_FOLDER}="{contest_folder}"\n')
f.write(f'{constant.LANGUAGES}="{",".join(languages)}"\n')
print(t("config_env_updated", path=env_file))
print(SEPARATE_LINE)
else:
# Load from .env
cookie = check_and_update_cookie(os.getenv(constant.COOKIE))
problem_folder = os.getenv(constant.PROBLEM_FOLDER, "problems")
contest_folder = os.getenv(constant.CONTEST_FOLDER, "contest")
languages = os.getenv(constant.LANGUAGES, "python3").split(",")
print(t("init_lang_selected", langs=", ".join(languages)))
print(t("init_folder_selected", folder=problem_folder))
print(t("init_folder_selected", folder=contest_folder))
print(SEPARATE_LINE)
logging.basicConfig(level=logging.ERROR)
return languages, problem_folder, cookie, contest_folder
# ============================================================================
# Problem Management
# ============================================================================
def get_problem(languages, problem_folder, cookie):
"""Get problem menu handler"""
while True:
get_problem_method = input_until_valid(
t("get_menu"),
allow_all
)
print(SEPARATE_LINE)
match get_problem_method:
case "1":
exit_code = daily_auto_main(problem_folder, cookie, languages)
if exit_code == 0:
print(t("get_daily_success"))
else:
print(t("get_daily_failed"))
case "2":
input_problem_id = input_until_valid(
t("get_problem_id"), allow_all_not_empty, t("get_problem_id_empty")
)
problem_id = back_question_id(input_problem_id)
exit_code = get_problem_main(
problem_id, force=True, cookie=cookie, replace_problem_id=True, skip_language=True,
languages=languages, problem_folder=problem_folder
)
if exit_code == 0:
print(t("get_success", id=problem_id))
else:
print(t("get_failed", id=problem_id))
case "3":
exit_code = lucky_main(languages, problem_folder)
if exit_code == 0:
print(t("get_random_success"))
else:
print(t("get_random_failed"))
case "4":
exit_code = remain_main(cookie, languages, problem_folder)
if exit_code == 0:
print(t("get_random_success"))
else:
print(t("get_remain_failed"))
case "5":
_handle_category_selection(languages, problem_folder, cookie)
case "6":
_handle_contest_problem(languages, problem_folder, cookie)
case _:
return
def _handle_category_selection(languages, problem_folder, cookie):
"""Handle category-based problem selection"""
tags = root_path / "data" / "tags.json"
if not tags.exists():
print(t("tags_not_found"))
return
with tags.open("r", encoding="utf-8") as f:
json_tags = json.load(f)
tags_list = list(json_tags.keys())
pick_tag = input_pick_array("tag", tags_list)
if pick_tag is None:
return
tag = tags_list[pick_tag]
tag_data = json_tags[tag]
print(t("tag_selected", tag=tag, translations=",".join(tag_data.get('translations', []))))
print(SEPARATE_LINE)
problems = tag_data.get("problems", [])
if not problems:
print(t("tag_no_problems"))
return
pick_problem = input_pick_array("problem", problems)
if pick_problem is None:
return
problem_id = problems[pick_problem]
exit_code = get_problem_main(
problem_id, force=True, cookie=cookie, replace_problem_id=True, skip_language=True,
languages=languages, problem_folder=problem_folder
)
if exit_code == 0:
print(t("get_success", id=problem_id))
else:
print(t("get_failed", id=problem_id))
def _handle_contest_problem(languages, problem_folder, cookie):
"""Handle contest-based problem fetching"""
contest_type = input_until_valid(
t("contest_type_menu"),
lambda x: x in ["0", "1", "2"],
t("contest_invalid_type")
)
print(SEPARATE_LINE)
if contest_type == "0":
return
contest_id = input_until_valid(
t("contest_id_num"),
allow_number,
t("contest_id_empty")
)
print(SEPARATE_LINE)
if contest_type == "1":
contest_id = f"weekly-contest-{contest_id}"
elif contest_type == "2":
contest_id = f"biweekly-contest-{contest_id}"
else:
print(t("contest_invalid_type"))
return
contest_questions = contest_lib.get_contest_info(contest_id)
results = []
with ThreadPoolExecutor(max_workers=max(1, len(contest_questions))) as executor:
for question_data in contest_questions:
results.append(
executor.submit(get_problem_main, problem_slug=question_data["title_slug"], force=True,
cookie=cookie, skip_language=True,
languages=languages, problem_folder=problem_folder))
for future in results:
exit_code = future.result()
if exit_code != 0:
print(t("get_failed", id="contest problem"))
def change_problem(languages, problem_folder):
"""Change test problem for all languages"""
input_problem_id = input_until_valid(
t("get_problem_id"), allow_all_not_empty, t("get_problem_id_empty")
)
problem_id = back_question_id(input_problem_id)
for lang in languages:
cls = getattr(lc_libs, f"{lang.capitalize()}Writer", None)
if not cls:
print(t("lang_not_support", lang=lang))
continue
obj: lc_libs.LanguageWriter = cls()
obj.change_test(root_path, problem_folder, format_question_id(problem_id))
print(t("change_test_success", lang=lang, id=problem_id))
print(SEPARATE_LINE)
# ============================================================================
# Submission
# ============================================================================
def submit(languages, problem_folder, cookie):
"""Submit code menu handler"""
while True:
submit_method = input_until_valid(
t("submit_menu"),
allow_all
)
print(SEPARATE_LINE)
if submit_method == "2" or submit_method == "4":
lang_options = "\n".join(f"{idx}. {lang}" for idx, lang in enumerate(SUPPORTED_LANGUAGES))
language_select = input_until_valid(
t("init_select_lang", options=lang_options),
lambda x: re.match(r"^[0-5](,[0-5])*$", x),
t("init_lang_invalid")
)
languages = list(set(SUPPORTED_LANGUAGES[int(idx)] for idx in language_select.split(",")))
print(SEPARATE_LINE)
match submit_method:
case "1" | "2":
daily_info = get_daily_question()
if not daily_info:
print(t("submit_daily_failed"))
continue
problem_id = daily_info['questionId']
case "3" | "4":
input_problem_id = input_until_valid(
t("get_problem_id"), allow_all_not_empty, t("get_problem_id_empty")
)
problem_id = back_question_id(input_problem_id)
case _:
return
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
print(t("submit_starting"))
logging.basicConfig(level=logging.INFO, force=True)
for i, lang in enumerate(languages):
print(t("submit_in_lang", lang=lang))
loop.run_until_complete(
submit_main_async(
root_path,
format_question_id(problem_id),
lang,
cookie,
problem_folder
)
)
if i < len(languages) - 1:
time.sleep(1)
if loop.is_running():
loop.stop()
loop.close()
logging.basicConfig(level=logging.ERROR, force=True)
time.sleep(1)
print(t("submit_done"))
print(SEPARATE_LINE)
# ============================================================================
# Contest Management
# ============================================================================
def contest_main(languages, contest_folder, cookie):
"""Contest menu handler"""
def contest_list():
cur_page = 1
while True:
contest_page = contest_lib.get_contest_list(cur_page)
total, data, has_more = contest_page["total"], contest_page["contests"], contest_page["has_more"]
max_page = math.ceil(total / 10)
if not data:
print(t("contest_no_contests"))
break
contest_content = "\n".join(
f"{_i}. [{datetime.datetime.fromtimestamp(c['start_time']).strftime('%Y-%m-%d %H:%M:%S')}]{c['title']}"
for _i, c in enumerate(data, start=1))
user_input_select = input_until_valid(
t("contest_page", total=total, content=contest_content),
allow_all
)
pick = None
match user_input_select:
case "b":
cur_page = max(1, cur_page - 1)
case "n":
cur_page = min(max_page, cur_page + 1)
case v if v.isdigit() and 1 <= int(v) <= 10:
pick = int(v)
case _:
break
print(SEPARATE_LINE)
if not pick:
continue
return data[pick - 1]
return None
user_input_contest = input_until_valid(
t("contest_menu"),
allow_all
)
print(SEPARATE_LINE)
match user_input_contest:
case "1":
contest = contest_list()
if not contest:
return None
contest_id = contest["title_slug"]
case "2":
contest_id = input_until_valid(
t("contest_id"),
allow_all_not_empty,
t("contest_id_empty")
)
case _:
return None
contest_questions = contest_lib.get_contest_info(contest_id)
p = root_path / contest_folder / contest_id
p.mkdir(parents=True, exist_ok=True)
def process_question_worker(question_idx_data_tuple):
question_idx, question_data = question_idx_data_tuple
question_slug = question_data["title_slug"]
subp = p / chr(ord('a') + question_idx - 1)
subp.mkdir(parents=True, exist_ok=True)
problem_info = contest_lib.get_contest_problem_info(contest_id, question_slug, ["python3"], cookie)
if not problem_info:
logging.error(f"Failed to get contest [{contest_id}] problem [{question_slug}]")
return False
try:
with (subp / "problem.md").open("w", encoding="utf-8") as f:
f.write(problem_info["en_markdown_content"])
with (subp / "problem_zh.md").open("w", encoding="utf-8") as f:
f.write(problem_info["cn_markdown_content"])
with (subp / "input.json").open("w", encoding="utf-8") as f:
json.dump(problem_info["question_example_testcases"], f)
with (subp / "output.json").open("w", encoding="utf-8") as f:
json.dump(problem_info["question_example_testcases_output"], f)
for lang, code_content in problem_info["language_default_code"].items():
cls = getattr(lc_libs, f"{lang.capitalize()}Writer", None)
if not cls:
logging.warning(f"Unsupported language {lang} for question {question_slug}")
continue
obj: lc_libs.LanguageWriter = cls()
solution_file = obj.solution_file
with (subp / solution_file).open("w", encoding="utf-8") as f:
generated_code = obj.write_contest(code_content, problem_info["question_id"], "")
if not generated_code:
logging.warning(f"Failed to write solution for {lang} for question {question_slug}")
continue
f.write(generated_code)
logging.info(f"Successfully processed question {question_slug}")
return True
except Exception as e:
logging.error(f"Error writing files for question {question_slug}: {e}")
return False
num_workers = max(1, len(contest_questions))
with ThreadPoolExecutor(max_workers=num_workers) as executor:
tasks_data = list(enumerate(contest_questions, start=1))
results = list(executor.map(process_question_worker, tasks_data))
for result in results:
if not result:
print(t("get_failed", id="contest question"))
p.rmdir()
return None
print(t("contest_generated", id=contest_id))
print(SEPARATE_LINE)
return None
# ============================================================================
# Favorite Management
# ============================================================================
def favorite_main(languages, problem_folder, cookie):
"""Favorite menu handler"""
def favorite_list():
while True:
my_favorites = query_my_favorites(cookie)
total, data, has_more = my_favorites["total"], my_favorites["favorites"], my_favorites["has_more"]
if not data:
print(t("fav_no_favorites"))
break
content = "\n".join(
[f"{_i}. {f['name']}" for _i, f in enumerate(data, start=1)],
)
user_input_select = input_until_valid(
t("contest_page", total=total, content=content),
allow_all
)
pick = None
match user_input_select:
case v if v.isdigit() and 1 <= int(v) <= 10:
pick = int(v)
case _:
break
print(SEPARATE_LINE)
if not pick:
continue
return data[pick - 1]
return None
def question_list(favorite_slug):
def question_to_str(q):
difficulty = constant.DIFFICULTY_TRANSLATE_MAP.get(q["difficulty"], "未知")
status = constant.STATUS_TRANSLATE_MAP.get(q["status"], "x")
paid_only = " {会员}" if q["paid_only"] else ""
return f"{status} [{q['question_frontend_id']}] {q['translated_title']} ({difficulty}){paid_only}"
cur_page = 1
page_size = 20
while True:
_questions = query_favorite_questions(favorite_slug, cookie, limit=page_size,
skip=(cur_page - 1) * page_size)
total, data, has_more = _questions["total"], _questions["questions"], _questions["has_more"]
max_page = math.ceil(total / page_size)
if not data:
print(t("fav_no_questions"))
break
content = "\n".join(
[f"{_i}. {question_to_str(q)}" for _i, q in enumerate(data, start=1)],
)
user_input_select = input_until_valid(
t("contest_page", total=total, content=content),
allow_all
)
pick = None
match user_input_select:
case "b":
cur_page = max(1, cur_page - 1)
case "n":
cur_page = min(max_page, cur_page + 1)
case v if v.isdigit() and 1 <= int(v) <= page_size:
pick = int(v)
case _:
break
print(SEPARATE_LINE)
if not pick:
continue
return data[pick - 1]
return None
if check_cookie_expired(cookie):
print(t("fav_expired"))
return
while True:
favorite = favorite_list()
if not favorite:
return
slug = favorite["slug"]
while True:
favorite_method = input_until_valid(
t("fav_menu"),
allow_all
)
print(SEPARATE_LINE)
match favorite_method:
case "1":
question = question_list(slug)
if not question:
break
code = get_problem_main(
problem_slug=question["title_slug"], force=True, cookie=cookie, replace_problem_id=True,
skip_language=True, languages=languages, problem_folder=problem_folder
)
if code == 0:
print(t("get_success", id=f"{question['question_frontend_id']} {question['translated_title']}"))
else:
print(t("get_failed", id=f"{question['question_frontend_id']} {question['translated_title']}"))
case "2":
input_questions = input_until_valid(
t("fav_add_ids"),
allow_all_not_empty,
t("fav_ids_empty")
)
question_ids = [q.strip() for q in input_questions.split(",")]
if not question_ids:
print(t("fav_ids_empty"))
continue
with ThreadPoolExecutor() as executor:
slugs = list(executor.map(get_question_slug_by_id, question_ids, [cookie] * len(question_ids)))
questions = []
for question_id, question_slug in zip(question_ids, slugs):
if not question_slug:
print(f"Invalid question ID: {question_id}. Skipping.")
continue
questions.append(question_slug)
if not questions:
print(t("fav_ids_empty"))
continue
result = batch_add_questions_to_favorite(slug, questions, cookie)
if result.get("status") == "success":
print(t("fav_add_success", count=len(questions), name=favorite['name']))
else:
print(t("fav_add_failed", name=favorite['name'], msg=result.get('message')))
case _:
break
def link_problems(problem_folder):
"""Link two problems with identical solutions"""
target_id = input_until_valid(
t("link_target_id"), allow_all_not_empty, t("get_problem_id_empty")
)
target_id = back_question_id(target_id)
source_id = input_until_valid(
t("link_source_id"), allow_all_not_empty, t("get_problem_id_empty")
)
source_id = back_question_id(source_id)
reason = input_until_valid(
t("link_reason"), allow_all
)
delete_solution = input_until_valid(
t("link_delete_solution"), allow_all
)
print(SEPARATE_LINE)
try:
link_file = create_link(
target_problem=target_id,
source_problem=source_id,
reason=reason if reason else None,
source_folder=problem_folder,
target_folder=problem_folder
)
print(t("link_success", target=target_id, source=source_id))
if delete_solution == "y":
target_path = root_path / problem_folder / f"{problem_folder}_{target_id}"
solution_files = ["solution.py", "solution.go", "Solution.java", "Solution.cpp", "solution.rs", "solution.ts", "Cargo.toml"]
for sol_file in solution_files:
file_path = target_path / sol_file
if file_path.exists():
file_path.unlink()
print(f"Deleted: {sol_file}")
except Exception as e:
print(t("link_failed", msg=str(e)))
print(SEPARATE_LINE)
def repository_health(problem_folder: str):
"""Run generated problem repository health checks."""
print(t("health_running", folder=problem_folder))
report = scan_repository(root_path, [problem_folder])
print(format_report(report, root_path))
fixes = build_fix_suggestions(report, root_path)
if fixes:
print()
print(t("health_fix_header"))
for idx, fix in enumerate(fixes, start=1):
print(f"{idx}. {fix.display(root_path)}")
selection = input_until_valid(t("health_fix_select"), allow_all)
selected_indices: list[int] = []
if selection.lower() == "a":
selected_indices = list(range(len(fixes)))
else:
for part in selection.split(","):
part = part.strip()
if part.isdigit() and 1 <= int(part) <= len(fixes):
selected_indices.append(int(part) - 1)
for idx in dict.fromkeys(selected_indices):
fix = fixes[idx]
confirm = input_until_valid(t("health_fix_confirm", fix=fix.display(root_path)), allow_all)
if confirm.lower() != "y":
print(t("health_fix_skipped"))
continue
print(apply_fix(fix))
if selected_indices:
print()
report = scan_repository(root_path, [problem_folder])
print(format_report(report, root_path))
print(SEPARATE_LINE)
def _get_problem_slug_from_id(problem_id: str, cookie: str) -> Optional[str]:
"""通过题目 ID 获取 problem_slug"""
origin_problem_id = back_question_id(problem_id)
questions = lc_libs.get_questions_by_key_word(origin_problem_id, cookie)
if not questions:
return None
for question in questions:
if question["questionFrontendId"] == origin_problem_id:
return question["titleSlug"]
return None
def _display_width(s: str) -> int:
"""计算字符串在终端的显示宽度(中文等宽字符占两列)"""
import unicodedata
return sum(2 if unicodedata.east_asian_width(c) in ('W', 'F') else 1 for c in s)
def _pad_to_width(s: str, width: int) -> str:
"""将字符串填充到指定显示宽度"""
current_width = _display_width(s)
if current_width >= width:
return s
return s + ' ' * (width - current_width)
def _display_solution_detail(title: str, author_name: str, upvote: int,
content: str, solution_link: str) -> bool:
"""
展示题解详情(边界框 + 分页器)
Returns:
True 如果用户选择保存,False 否则
"""
# 边界框展示元信息(固定宽度 50)
box_width = 50
content_width = box_width - 4 # 去掉 "│ " 和 " │"
print(f"\n┌{'─' * (box_width - 2)}┐")
# 标题行(截断并填充)
title_display = title[:content_width - 2] if _display_width(title) > content_width - 2 else title
print(f"│ 📄 {_pad_to_width(title_display, content_width - 2)}│")
# 作者行
author_display = author_name[:content_width - 2] if _display_width(author_name) > content_width - 2 else author_name
print(f"│ 👤 {_pad_to_width(author_display, content_width - 2)}│")
# 点赞行
upvote_str = str(upvote)
print(f"│ 👍 {_pad_to_width(upvote_str, content_width - 2)}│")
# 链接行(如果有)
if solution_link:
link_display = solution_link[:content_width - 2] if len(solution_link) > content_width - 2 else solution_link
print(f"│ 🔗 {_pad_to_width(link_display, content_width - 2)}│")
print(f"└{'─' * (box_width - 2)}┘")
# 使用分页器展示内容
if content:
import subprocess
import tempfile
tmp_path = None
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
f.write(f"# {title}\n\n")
f.write(f"> Author: {author_name} | Upvotes: {upvote}\n\n")
f.write(content)
tmp_path = f.name
# 使用列表形式避免 shell 注入
import shlex
pager_cmd = shlex.split(os.environ.get('PAGER', 'less -R'))
subprocess.run(pager_cmd + [tmp_path])
except Exception:
# 如果分页器失败,直接打印前 100 行
print("\n" + SEPARATE_LINE)
lines = content.split('\n')
for line in lines[:100]:
print(line)
if len(lines) > 100:
print(f"\n... (共 {len(lines)} 行,已截断)")
print(SEPARATE_LINE)
finally:
if tmp_path and os.path.exists(tmp_path):
os.unlink(tmp_path)
save_input = input_until_valid(t("solution_save"), allow_all)
return save_input.lower() == "y"
def _save_solution(article_content: dict, problem_folder: str, problem_id: str):
"""保存题解到本地文件"""
problem_dir = root_path / problem_folder / f"{problem_folder}_{back_question_id(problem_id)}"
if not problem_dir.exists():
print(f"{t('solution_save_failed')} - 目录不存在: {problem_dir}")
return
author_info = article_content.get("author", {})
profile = author_info.get("profile", {})
author_slug = profile.get("userSlug", "unknown") if profile else "unknown"
# Sanitize author_slug: only allow alphanumeric, underscore, dash
author_slug = re.sub(r"[^a-zA-Z0-9_-]", "", author_slug) or "unknown"
save_path = problem_dir / f"solution_{author_slug}.md"
author_name = profile.get("realName", "") or author_info.get("username", "")
title = article_content.get("title", "")
content = article_content.get("content", "")
upvote = article_content.get("upvoteCount", 0)
md = f"# {title}\n\n> Author: {author_name}\n> Upvotes: {upvote}\n\n---\n\n{content}"
with open(save_path, "w", encoding="utf-8") as f:
f.write(md)
print(t("solution_saved", path=save_path))
def _browse_community_solutions(cookie: str, problem_folder: str):
"""浏览社区题解(支持分页)"""
problem_id_input = input_until_valid(t("solution_enter_problem_id"), allow_all_not_empty,
t("solution_problem_id_empty"))
print(SEPARATE_LINE)
if not problem_id_input:
return
problem_slug = _get_problem_slug_from_id(problem_id_input, cookie)
if not problem_slug:
print(t("solution_no_articles"))
return