forked from lza6/perplexity-2api-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1545 lines (1319 loc) · 56.3 KB
/
main.py
File metadata and controls
executable file
·1545 lines (1319 loc) · 56.3 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
import logging
import sys
import json
import uuid
import time
import os
import platform
import shutil
from pathlib import Path
from contextlib import asynccontextmanager
from typing import Dict, List, Any, Optional
from fastapi import FastAPI, Request, Depends, Header, HTTPException, Form
from fastapi.responses import JSONResponse, HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from datetime import datetime, timedelta
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
logger.warning("psutil not installed, system monitoring features will be limited. Run: pip install psutil")
from app.core.config import settings
from app.providers.perplexity_provider import PerplexityProvider
# [Modified] Set log level to DEBUG, format includes filename and line number
logger.remove()
logger.add(
sys.stdout,
level="DEBUG",
format="<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
)
provider = PerplexityProvider()
# Simulated account data storage (should use database in production)
accounts_db: Dict[str, Dict[str, Any]] = {}
logs_db: List[Dict[str, Any]] = []
custom_models: List[Dict[str, Any]] = [
{"id": "gpt-4", "name": "GPT-4", "provider": "openai", "is_custom": False},
{"id": "gpt-3.5-turbo", "name": "GPT-3.5 Turbo", "provider": "openai", "is_custom": False},
{"id": "claude-3-opus", "name": "Claude 3 Opus", "provider": "anthropic", "is_custom": False},
]
def load_accounts_from_sessions():
"""Load saved accounts from data/sessions/ directinto accounts_db"""
sessions_dir = Path("data/sessions")
if not sessions_dir.exists():
logger.info("📁 Sessions directory not found, skipping account loading")
return
for session_file in sessions_dir.glob("*.json"):
try:
logger.debug(f"Processing session file: {session_file}")
with open(session_file, 'r', encoding='utf-8') as f:
session_data = json.load(f)
account_name = session_data.get("account_name")
if not account_name:
logger.warning(f"⚠️ Session file missing account name: {session_file}")
continue
logger.info(f"📂 Found account: {account_name}")
# Check if account with same name already exists (avoid duplicates)
existing_account = None
for acc_id, acc in accounts_db.items():
if acc.get("name") == account_name:
existing_account = acc_id
break
if existing_account:
# Update existing record
account_id = existing_account
logger.debug(f"📝 Updating existing account: {account_name}")
else:
# Create new record
account_id = str(uuid.uuid4())[:8]
logger.info(f"📂 Loading account: {account_name} (session file: {session_file.name})")
# Get Cookie file info - enhanced path handling
cookie_file = session_data.get("cookie_file", "")
cookie_count = 0
cookie_file_path = None
if cookie_file:
# Try direct path
cookie_file_path = Path(cookie_file)
if not cookie_file_path.exists():
# Try relative to current working directory
cookie_file_path = Path.cwd() / cookie_file
if not cookie_file_path.exists():
# Try to get from directory_info
dir_info = session_data.get("directory_info", {})
cookie_json = dir_info.get("cookie_json", "")
if cookie_json:
cookie_file_path = Path(cookie_json)
if not cookie_file_path.exists():
cookie_file_path = Path.cwd() / cookie_json
else:
# Try to find in data/cookies/account_name/
candidate = Path("data/cookies") / account_name / "cookies.json"
if candidate.exists():
cookie_file_path = candidate
if cookie_file_path and cookie_file_path.exists():
try:
with open(cookie_file_path, 'r', encoding='utf-8') as cf:
cookie_data = json.load(cf)
cookie_count = cookie_data.get("cookie_count", 0)
logger.debug(f"✅ Successfully read Cookie file: {cookie_file_path}, cookie_count: {cookie_count}")
except Exception as e:
logger.warning(f"⚠️ Failed to read Cookie file {cookie_file_path}: {e}")
else:
logger.warning(f"⚠️ Cookie file does not exist: {cookie_file}, tried path: {cookie_file_path}")
else:
logger.warning(f"⚠️ cookie_file field not specified in session file")
# Get directory info
dir_info = session_data.get("directory_info", {})
account_dir = dir_info.get("account_dir", f"data/cookies/{account_name}")
cookie_json = dir_info.get("cookie_json", "")
cookie_txt = dir_info.get("cookie_txt", "")
# Create account record (structure consistent with Web UI additions)
account_record = {
"id": account_id,
"name": account_name,
"is_active": True,
"token_source": session_data.get("source", "unknown"),
"data_dir": account_dir,
"token": "Locally saved Cookie",
"expires_at": (datetime.now() + timedelta(days=30)).isoformat(),
"total_calls": session_data.get("stats", {}).get("total_calls", 0),
"discord_username": None,
"created_at": datetime.fromtimestamp(session_data.get("created_at", time.time())).isoformat(),
"cookie_count": cookie_count,
"user_agent_preview": "", # Can be obtained from Cookie file, but simplified
"local_saved": True,
"cookie_files": [cookie_json, cookie_txt]
}
accounts_db[account_id] = account_record
logger.info(f"✅ Successfully loaded account: {account_name} (ID: {account_id}, Cookie count: {cookie_count})")
except Exception as e:
logger.error(f"❌ Failed to load session file {session_file}: {e}")
import traceback
traceback.print_exc()
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info(f"Starting {settings.APP_NAME} v{settings.APP_VERSION} (Botasaurus Deep Debug Mode)...")
logger.info("Initializing Botasaurus browser service...")
try:
# Load locally saved accounts first
load_accounts_from_sessions()
logger.info(f"📊 Loaded {len(accounts_db)} local accounts")
# Then initialize Botasaurus
await provider.solver.initialize_session()
except Exception as e:
logger.error(f"Initialization failed: {e}")
yield
logger.info("Service shutdown.")
app = FastAPI(title=settings.APP_NAME, lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.mount("/static", StaticFiles(directory="static"), name="static")
async def verify_key(authorization: str = Header(None)):
if settings.API_MASTER_KEY != "1":
if not authorization or authorization.split(" ")[1] != settings.API_MASTER_KEY:
raise HTTPException(403, "Invalid API Key")
# ==================== Original API ====================
@app.post("/v1/chat/completions", dependencies=[Depends(verify_key)])
async def chat(request: Request):
try:
data = await request.json()
# [Added] Print client raw request
logger.debug(f"Received client request: {data}")
# Check if provider is ready
if not hasattr(provider, 'solver'):
raise HTTPException(503, "Service is initializing, please try again later or add account via Web UI")
# Check if valid Cookie is available
if not provider.solver.get_cookies():
raise HTTPException(400, "No valid Cookie found, please add account or import Cookie via Web UI")
return await provider.chat_completion(data)
except HTTPException:
raise
except Exception as e:
logger.error(f"Request Error: {e}")
raise HTTPException(500, f"Internal server error: {str(e)}")
@app.get("/v1/models")
async def models():
return await provider.get_models()
# ==================== Conversation Management API ====================
@app.get("/api/conversations")
async def get_conversations():
"""Get conversation statistics"""
stats = provider.conversation_manager.get_stats()
return JSONResponse(content={
"success": True,
"stats": stats
})
@app.post("/api/conversations/reset")
async def reset_conversation(request: Request):
"""Reset a specific conversation or all conversations"""
try:
data = await request.json()
conversation_id = data.get("conversation_id", "default")
await provider.conversation_manager.reset_conversation(conversation_id)
return JSONResponse(content={
"success": True,
"message": f"✅ Conversation '{conversation_id}' has been reset"
})
except Exception as e:
return JSONResponse(content={
"success": False,
"message": f"❌ Failed to reset conversation: {str(e)}"
})
@app.post("/api/conversations/reset-all")
async def reset_all_conversations():
"""Reset all conversations"""
try:
# Get all conversation IDs
stats = provider.conversation_manager.get_stats()
conversation_ids = list(stats.get("conversations", {}).keys())
for cid in conversation_ids:
await provider.conversation_manager.reset_conversation(cid)
return JSONResponse(content={
"success": True,
"message": f"✅ Reset {len(conversation_ids)} conversations"
})
except Exception as e:
return JSONResponse(content={
"success": False,
"message": f"❌ Failed to reset conversations: {str(e)}"
})
# ==================== Account Management API ====================
@app.get("/api/accounts")
async def get_accounts():
"""Get all accounts list"""
accounts = list(accounts_db.values())
active_count = sum(1 for acc in accounts if acc.get("is_active", False))
inactive_count = len(accounts) - active_count
return JSONResponse(content={
"accounts": accounts,
"active_count": active_count,
"inactive_count": inactive_count,
"total": len(accounts)
})
@app.post("/api/account/login/start")
async def start_login(name: str = Form(...)):
"""Start real browser login (using Botasaurus)"""
import asyncio
account_id = str(uuid.uuid4())[:8]
try:
logger.info(f"🔄 Starting interactive login process, account: {name}")
# Set timeout (5 minutes)
try:
result = await asyncio.wait_for(
provider.solver.interactive_login(name),
timeout=300 # 5 minutes
)
except asyncio.TimeoutError:
logger.warning(f"⏱️ Login timeout, account: {name}")
return JSONResponse(content={
"success": False,
"message": "❌ Login timeout (5 minutes). Please check if browser window opened properly.",
"account_id": account_id
})
if result.get("success"):
# Use actual account directory
account_dir = result.get("account_dir", f"data/cookies/{name}")
# Create account record
new_account = {
"id": account_id,
"name": name,
"is_active": True,
"token_source": "browser",
"data_dir": account_dir,
"token": "Real Token (saved locally)",
"expires_at": (datetime.now() + timedelta(days=30)).isoformat(),
"total_calls": 0,
"discord_username": None,
"created_at": datetime.now().isoformat(),
"cookie_count": len(result.get("cookies", {})),
"user_agent_preview": result.get("user_agent", "")[:30] + "...",
"local_saved": result.get("local_saved", False),
"cookie_files": [
f"{account_dir}/cookies.json",
f"{account_dir}/cookies.txt"
]
}
accounts_db[account_id] = new_account
# Add log
logs_db.append({
"timestamp": datetime.now().isoformat(),
"account_name": name,
"model": "N/A",
"duration": 0,
"status": "SUCCESS",
"note": f"Interactive login successful, data saved to: {account_dir}",
"level": "info"
})
logger.info(f"✅ Interactive login successful, account: {name}, data directory: {account_dir}")
return JSONResponse(content={
"success": True,
"message": f"✅ Login successful! Retrieved {result.get('cookie_count', 0)} Cookies and saved to local directory.",
"account_id": account_id,
"cookie_count": len(result.get("cookies", {})),
"user_agent_preview": result.get("user_agent", "")[:50],
"account_dir": account_dir,
"local_saved": result.get("local_saved", False)
})
else:
error_msg = result.get("error", "Unknown error")
logger.error(f"❌ Login failed, account: {name}, error: {error_msg}")
return JSONResponse(content={
"success": False,
"message": f"❌ Login failed: {error_msg}",
"account_id": account_id
})
except Exception as e:
logger.error(f"❌ Login process exception, account: {name}, error: {e}")
return JSONResponse(content={
"success": False,
"message": f"❌ Login process exception: {str(e)}",
"account_id": account_id
})
@app.post("/api/token/refresh/{account_id}")
async def refresh_token(account_id: str):
"""Refresh account Token (simulated)"""
if account_id not in accounts_db:
raise HTTPException(404, "Account not found")
account = accounts_db[account_id]
account["token"] = "RefreshToken_" + str(uuid.uuid4())[:8]
account["expires_at"] = (datetime.now() + timedelta(days=30)).isoformat()
return JSONResponse(content={
"success": True,
"message": "✅ Token refresh successful (simulated)"
})
@app.get("/api/account/toggle/{account_id}")
async def toggle_account(account_id: str):
"""Enable/Disable account"""
if account_id not in accounts_db:
raise HTTPException(404, "Account not found")
account = accounts_db[account_id]
account["is_active"] = not account.get("is_active", True)
return JSONResponse(content={
"success": True,
"message": "✅ Account status updated",
"is_active": account["is_active"]
})
@app.get("/api/account/delete/{account_id}")
async def delete_account(account_id: str):
"""Delete account"""
if account_id not in accounts_db:
raise HTTPException(404, "Account not found")
del accounts_db[account_id]
return JSONResponse(content={
"success": True,
"message": "✅ Account deleted"
})
# ==================== Log Management API ====================
@app.get("/api/logs")
async def get_logs():
"""Get recent logs"""
return JSONResponse(content={
"logs": logs_db[-50:] # Return last 50 entries
})
@app.get("/api/logs/clear")
async def clear_logs_get():
"""Clear logs (GET method for backward compatibility)"""
logs_db.clear()
return JSONResponse(content={
"success": True,
"message": "✅ Logs cleared"
})
@app.post("/api/logs/clear")
async def clear_logs_post():
"""Clear logs (POST method)"""
logs_db.clear()
return JSONResponse(content={
"success": True,
"message": "✅ Logs cleared"
})
# ==================== Service Control API ====================
@app.post("/api/service/stop")
async def stop_service():
"""Stop service (simulated)"""
return JSONResponse(content={
"success": True,
"message": "🛑 Service stop command sent (requires process management)"
})
@app.post("/api/settings/preview-mode")
async def set_preview_mode(request: Request):
"""Set preview mode"""
data = await request.json()
enabled = data.get("enabled", False)
return JSONResponse(content={
"success": True,
"message": f"✅ Preview mode {'enabled' if enabled else 'disabled'}"
})
# ==================== Web UI ====================
@app.get("/", response_class=HTMLResponse)
async def ui():
"""Serve Web UI"""
with open("static/index.html", "r", encoding="utf-8") as f:
return f.read()
@app.get("/api/ui-data")
async def ui_data():
"""Provide data for UI (for frontend JavaScript calls)"""
accounts = list(accounts_db.values())
active_count = sum(1 for acc in accounts if acc.get("is_active", False))
inactive_count = len(accounts) - active_count
return JSONResponse(content={
"accounts": accounts,
"active_count": active_count,
"inactive_count": inactive_count,
"logs": logs_db[-10:],
"api_url": f"http://127.0.0.1:{settings.NGINX_PORT}",
"version": "3.0"
})
# ==================== System Monitoring API ====================
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
status = {
"status": "healthy",
"service": "perplexity-2api",
"version": "3.0",
"timestamp": datetime.now().isoformat()
}
# Check basic service status
try:
# Check Botasaurus status
botasaurus_ready = False
if hasattr(provider, 'solver'):
solver = provider.solver
if hasattr(solver, 'cached_cookies'):
botasaurus_ready = True
status["botasaurus_ready"] = botasaurus_ready
status["accounts_count"] = len(accounts_db)
status["logs_count"] = len(logs_db)
if not botasaurus_ready:
status["warning"] = "Botasaurus not ready, please add account via Web UI or check initialization"
except Exception as e:
status["status"] = "degraded"
status["error"] = str(e)
return JSONResponse(content=status)
def get_directory_size(path: str) -> int:
"""Calculate directory size (bytes)"""
total = 0
try:
for entry in os.scandir(path):
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_directory_size(entry.path)
except (PermissionError, FileNotFoundError):
pass
return total
def format_file_size(size_bytes: int) -> str:
"""Format file size"""
if size_bytes == 0:
return "0 B"
units = ["B", "KB", "MB", "GB", "TB"]
i = 0
while size_bytes >= 1024 and i < len(units) - 1:
size_bytes /= 1024
i += 1
return f"{size_bytes:.1f} {units[i]}"
@app.get("/api/system/status")
async def get_system_status():
"""Get system status"""
status = {
"service_status": "running",
"botasaurus_status": "initializing",
"total_accounts": len(accounts_db),
"active_accounts": sum(1 for acc in accounts_db.values() if acc.get("is_active", False)),
"api_requests": len(logs_db) if logs_db else 0,
"memory_usage": 30, # Default value
"timestamp": datetime.now().isoformat()
}
# Check Botasaurus status
try:
if hasattr(provider, 'solver') and hasattr(provider.solver, 'cached_cookies'):
status["botasaurus_status"] = "initialized"
else:
status["botasaurus_status"] = "initializing"
except:
status["botasaurus_status"] = "failed"
# Get memory usage (if psutil available)
if HAS_PSUTIL:
try:
process = psutil.Process()
memory_percent = process.memory_percent()
status["memory_usage"] = round(memory_percent, 1)
except:
pass
return JSONResponse(content=status)
@app.get("/api/system/info")
async def get_system_info():
"""Get system information"""
import sys as sys_module
info = {
"python_version": f"{sys_module.version_info.major}.{sys_module.version_info.minor}.{sys_module.version_info.micro}",
"host_name": platform.node(),
"working_dir": os.getcwd(),
"platform": platform.platform(),
"uptime": "Just started", # Simplified version
"start_time": datetime.now().isoformat()
}
return JSONResponse(content=info)
# ==================== File Management API ====================
@app.get("/api/files/list")
async def list_files(path: str = ""):
"""List files in specified directory"""
base_path = Path.cwd()
if path:
target_path = (base_path / path).resolve()
# Security check: ensure path is within project directory
if not str(target_path).startswith(str(base_path)):
raise HTTPException(403, "Access to this path is forbidden")
else:
target_path = base_path
files = []
try:
for entry in os.scandir(target_path):
try:
file_info = {
"name": entry.name,
"path": str(Path(entry.path).relative_to(base_path)),
"type": "directory" if entry.is_dir() else "file",
"size": entry.stat().st_size if entry.is_file() else 0,
"modified": entry.stat().st_mtime,
"permissions": oct(entry.stat().st_mode)[-3:]
}
# If directory, estimate size
if entry.is_dir():
try:
dir_size = get_directory_size(entry.path)
file_info["size"] = dir_size
except:
pass
files.append(file_info)
except (PermissionError, FileNotFoundError):
continue
# Sort by type and name
files.sort(key=lambda x: (0 if x["type"] == "directory" else 1, x["name"].lower()))
except (PermissionError, FileNotFoundError) as e:
raise HTTPException(404, f"Cannot access directory: {str(e)}")
return JSONResponse(content={"files": files, "current_path": str(target_path.relative_to(base_path))})
@app.get("/api/files/storage")
async def get_storage_info():
"""Get storage space information"""
base_path = Path.cwd()
# Calculate various directory sizes
project_dir_size = get_directory_size(str(base_path))
# Account data directory (if exists)
account_data_path = base_path / "data"
account_data_size = get_directory_size(str(account_data_path)) if account_data_path.exists() else 0
# Log directory
log_files_path = base_path / "error_logs"
log_files_size = get_directory_size(str(log_files_path)) if log_files_path.exists() else 0
# Cache directory (output directory)
cache_files_path = base_path / "output"
cache_files_size = get_directory_size(str(cache_files_path)) if cache_files_path.exists() else 0
# Calculate total disk usage (if psutil available)
storage_usage = 25 # Default value
if HAS_PSUTIL:
try:
disk_usage = psutil.disk_usage(str(base_path))
storage_usage = (disk_usage.used / disk_usage.total) * 100
except:
pass
return JSONResponse(content={
"project_dir_size": project_dir_size,
"account_data_size": account_data_size,
"log_files_size": log_files_size,
"cache_files_size": cache_files_size,
"storage_usage": round(storage_usage, 1),
"formatted": {
"project_dir_size": format_file_size(project_dir_size),
"account_data_size": format_file_size(account_data_size),
"log_files_size": format_file_size(log_files_size),
"cache_files_size": format_file_size(cache_files_size),
}
})
@app.post("/api/files/clean-cache")
async def clean_cache():
"""Clean cache files"""
base_path = Path.cwd()
cache_dirs = ["output", "__pycache__", ".pytest_cache"]
deleted_count = 0
total_freed = 0
for cache_dir in cache_dirs:
cache_path = base_path / cache_dir
if cache_path.exists():
try:
if cache_path.is_dir():
dir_size = get_directory_size(str(cache_path))
shutil.rmtree(cache_path)
deleted_count += 1
total_freed += dir_size
logger.info(f"Deleted cache directory: {cache_dir}")
except Exception as e:
logger.error(f"Failed to delete cache directory {cache_dir}: {e}")
# Delete individual cache files
cache_patterns = ["*.pyc", "*.log", "*.tmp"]
for pattern in cache_patterns:
for file_path in base_path.rglob(pattern):
try:
if file_path.is_file():
file_size = file_path.stat().st_size
file_path.unlink()
deleted_count += 1
total_freed += file_size
except Exception as e:
pass
return JSONResponse(content={
"success": True,
"message": f"✅ Cleaned {deleted_count} cache items, freed {format_file_size(total_freed)}",
"deleted_count": deleted_count,
"freed_bytes": total_freed
})
@app.post("/api/files/delete")
async def delete_files(request: Request):
"""Delete specified files/directories"""
data = await request.json()
paths = data.get("paths", [])
if not paths:
raise HTTPException(400, "No paths specified for deletion")
base_path = Path.cwd()
deleted = []
errors = []
for rel_path in paths:
try:
target_path = (base_path / rel_path).resolve()
# Security check
if not str(target_path).startswith(str(base_path)):
errors.append(f"Access forbidden: {rel_path}")
continue
if target_path.exists():
if target_path.is_dir():
shutil.rmtree(target_path)
else:
target_path.unlink()
deleted.append(rel_path)
logger.info(f"Deleted: {rel_path}")
else:
errors.append(f"File not found: {rel_path}")
except Exception as e:
errors.append(f"Delete failed {rel_path}: {str(e)}")
return JSONResponse(content={
"success": len(errors) == 0,
"message": f"Deleted {len(deleted)} items, {len(errors)} errors",
"deleted": deleted,
"errors": errors
})
# ==================== Enhanced Log API ====================
@app.get("/api/logs/recent")
async def get_recent_logs(limit: int = 100):
"""Get recent logs (with filtering support)"""
recent_logs = []
# This can be extended to read logs from files or database
# Currently using in-memory logs
for log in logs_db[-limit:]:
recent_logs.append({
"timestamp": log.get("timestamp", ""),
"level": log.get("level", "info"),
"message": log.get("note", "") or log.get("status", ""),
"account": log.get("account_name", ""),
"model": log.get("model", "")
})
return JSONResponse(content={"logs": recent_logs})
@app.post("/api/accounts/refresh-all")
async def refresh_all_accounts():
"""Refresh all accounts (simulated)"""
# In production, this would call provider to refresh all account Cookies
logger.info("Starting to refresh all accounts...")
# Simulate refresh process
import asyncio
await asyncio.sleep(2)
return JSONResponse(content={
"success": True,
"message": "✅ Requested refresh for all accounts, will execute in background",
"account_count": len(accounts_db)
})
@app.post("/api/account/refresh/{account_id}")
async def refresh_account(account_id: str):
"""Refresh specified account"""
if account_id not in accounts_db:
raise HTTPException(404, "Account not found")
# Simulate refresh
account = accounts_db[account_id]
account["token"] = "RefreshToken_" + str(uuid.uuid4())[:8]
account["expires_at"] = (datetime.now() + timedelta(days=30)).isoformat()
account["total_calls"] = account.get("total_calls", 0) + 1
logs_db.append({
"timestamp": datetime.now().isoformat(),
"account_name": account["name"],
"level": "info",
"note": "Account Token refreshed",
"status": "SUCCESS"
})
return JSONResponse(content={
"success": True,
"message": "✅ Account refresh successful",
"account_id": account_id
})
@app.post("/api/cookie/parse")
async def parse_cookie_string(request: Request):
"""Parse Cookie string and create account"""
try:
data = await request.json()
text = data.get("text", "")
account_name = data.get("account_name", "Imported Account")
if not text:
raise HTTPException(400, "Please enter text content to parse")
# Call BrowserService to parse Cookie
result = provider.solver.parse_cookie_string(text, account_name)
if result.get("success"):
# Create account record
account_id = str(uuid.uuid4())[:8]
account_dir = result.get("account_dir", f"data/cookies/{account_name}")
new_account = {
"id": account_id,
"name": account_name,
"is_active": True,
"token_source": "cookie_import",
"data_dir": account_dir,
"token": "Cookie Import (saved locally)",
"expires_at": (datetime.now() + timedelta(days=30)).isoformat(),
"total_calls": 0,
"discord_username": None,
"created_at": datetime.now().isoformat(),
"cookie_count": result.get("cookie_count", 0),
"user_agent_preview": result.get("user_agent", "")[:30] + "...",
"local_saved": result.get("local_saved", False),
"cookie_files": [
f"{account_dir}/cookies.json",
f"{account_dir}/cookies.txt"
]
}
accounts_db[account_id] = new_account
# Add log
logs_db.append({
"timestamp": datetime.now().isoformat(),
"account_name": account_name,
"model": "N/A",
"duration": 0,
"status": "SUCCESS",
"note": f"Cookie import successful, data saved to: {account_dir}",
"level": "info"
})
return JSONResponse(content={
"success": True,
"message": f"✅ Cookie import successful! Extracted {result.get('cookie_count', 0)} Cookies and saved to local directory.",
"account_id": account_id,
"cookie_count": result.get("cookie_count", 0),
"user_agent_preview": result.get("user_agent", "")[:50],
"account_dir": account_dir
})
else:
return JSONResponse(content={
"success": False,
"message": f"❌ Parse failed: {result.get('error', 'Unknown error')}"
})
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Cookie parse exception: {e}")
return JSONResponse(content={
"success": False,
"message": f"❌ Parse exception: {str(e)}"
})
# ==================== API Key Management ====================
@app.get("/api/settings/api-key")
async def get_api_key():
"""Get current API Key"""
return JSONResponse(content={
"api_key": settings.API_MASTER_KEY,
"masked": "***" + settings.API_MASTER_KEY[-4:] if len(settings.API_MASTER_KEY) > 4 else "***"
})
@app.post("/api/settings/api-key")
async def update_api_key(request: Request):
"""Update API Key (write to .env file)"""
try:
data = await request.json()
new_key = data.get("api_key", "").strip()
if not new_key:
raise HTTPException(400, "API Key cannot be empty")
# Update .env file
env_path = ".env"
if not os.path.exists(env_path):
raise HTTPException(500, "Cannot find .env file")
with open(env_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
updated = False
new_lines = []
for line in lines:
if line.startswith("API_MASTER_KEY="):
new_lines.append(f'API_MASTER_KEY="{new_key}"\n')
updated = True
else:
new_lines.append(line)
if not updated:
new_lines.append(f'API_MASTER_KEY="{new_key}"\n')
with open(env_path, 'w', encoding='utf-8') as f:
f.writelines(new_lines)
# Update in-memory settings (optional, full effect may require restart)
# settings.API_MASTER_KEY = new_key
logger.info("API Key updated")
return JSONResponse(content={
"success": True,
"message": "✅ API Key updated. Note: some features may require a service restart to take effect.",
"masked": "***" + new_key[-4:] if len(new_key) > 4 else "***"
})
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to update API Key: {e}")
raise HTTPException(500, f"Update failed: {str(e)}")
@app.get("/api/settings/export-config")
async def export_config():
"""Export current system configuration (JSON format)"""
try:
# Collect configuration information
config = {
"export_time": datetime.now().isoformat(),
"version": "3.0",
"api_key_masked": "***" + settings.API_MASTER_KEY[-4:] if len(settings.API_MASTER_KEY) > 4 else "***",
"system_settings": {
"app_name": settings.APP_NAME,
"app_version": settings.APP_VERSION,
"api_master_key_length": len(settings.API_MASTER_KEY),
"default_model": settings.DEFAULT_MODEL,
"target_url": settings.TARGET_URL,
"api_url": settings.API_URL,
"nginx_port": settings.NGINX_PORT
},
"accounts": list(accounts_db.values()),
"custom_models": custom_models,
"statistics": {
"total_accounts": len(accounts_db),
"active_accounts": sum(1 for acc in accounts_db.values() if acc.get("is_active", False)),
"total_logs": len(logs_db),
"custom_models_count": len(custom_models)
},
"data_directories": {
"cookies": "data/cookies/",
"sessions": "data/sessions/",
"logs": "error_logs/",
"output": "output/"
}
}
return JSONResponse(content={
"success": True,
"message": "✅ Configuration exported successfully",
"config": config,
"download_filename": f"perplexity-config-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
})
except Exception as e:
logger.error(f"Failed to export configuration: {e}")
raise HTTPException(500, f"Failed to export configuration: {str(e)}")
# ==================== Account Detail API ====================
@app.get("/api/account/details/{account_name}")
async def get_account_details(account_name: str):
"""Get detailed account information (paths, creation time, update time, call stats, etc.)"""