-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2062 lines (1715 loc) · 74.8 KB
/
Copy pathmain.py
File metadata and controls
2062 lines (1715 loc) · 74.8 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
from fastapi import FastAPI, HTTPException, UploadFile, File, Form, Query
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
import tempfile
import os
from typing import Dict
import json
import uuid
import yaml
import platformdirs
from typing import Optional
import datetime
from src.git_manager import GitManager
from src.template_loader import template_loader
from src.file_lock_manager import FileLockManager
from src.project_manager import ProjectManager
from src.utils import convert_pptx_to_pdf
from src.utils import force_delete_directory
from src.utils import logger
app = FastAPI(
title="PPTXSlideshow editor", description="Online editingPPTXpresentation"
)
app.mount("/static", StaticFiles(directory="static"), name="static")
# Global project manager
file_locks = FileLockManager()
# Global manager instance
project_manager = ProjectManager()
class SlideUpdate(BaseModel):
session_id: str
current_slide: int
shape_changes: Dict[str, Dict] # 🎯 Change to required
@app.post("/api/save")
async def save_changes(update: SlideUpdate):
"""Save slide changes(Supports both text and table data)"""
logger.debug(
f"💾 Save request received - Type: {type(update.shape_changes).__name__}"
)
try:
if not hasattr(update, "shape_changes") or not update.shape_changes:
logger.debug(f"❌ No structured data provided")
raise HTTPException(400, "Please use structured data format")
shape_changes = update.shape_changes
logger.debug(f" - Total shapes to save: {len(shape_changes)}")
project_data_obj = project_manager.get_project_by_session(update.session_id)
if not project_data_obj:
raise HTTPException(404, "Session does not exist")
project_dir = project_data_obj.get("project_dir")
if not project_dir:
raise HTTPException(400, "No project directory")
logger.debug(f"✅ Project directory: {project_dir}")
file_save_success = 0
file_save_failed = 0
total_runs_saved = 0
total_paragraphs_saved = 0
total_tables_saved = 0
for shape_id, change_data in shape_changes.items():
try:
logger.debug(f"🔄 Processing: {shape_id}")
# 🎯 Analyze shapesID
parts = shape_id.split("_")
if not (
len(parts) >= 4 and parts[0] == "slide" and parts[2] == "shape"
):
logger.debug(f"⚠️ Invalid shape ID format: {shape_id}")
file_save_failed += 1
continue
slide_idx = int(parts[1])
# 🎯 Determine the data type and process accordingly
success = False
# Condition1:text data(Include'txt'Field)
if isinstance(change_data, dict) and "txt" in change_data:
structured_data = change_data["txt"]
if isinstance(structured_data, list):
# statisticsruns
runs_count = 0
for para in structured_data:
runs_count += len(para.get("runs", []))
# Save text data
success = project_manager.save_structured_data_to_json(
project_dir, slide_idx, shape_id, structured_data
)
if success:
total_runs_saved += runs_count
total_paragraphs_saved += len(structured_data)
logger.debug(f" - ✅ Text data saved ({runs_count} runs)")
# 🎯 Condition2:tabular data(Include'type': 'table')
elif (
isinstance(change_data, dict)
and change_data.get("type") == "table"
and "changes" in change_data
):
# Call the table save function
success = project_manager.save_table_changes(
project_dir,
slide_idx,
shape_id,
change_data["changes"],
change_data.get("original_data", "[]"),
)
if success:
total_tables_saved += 1
logger.debug(f" - ✅ Table data saved")
# Condition3:other formats(jump over)
else:
logger.debug(
f"⚠️ Unsupported data format for {shape_id}: {type(change_data)}"
)
file_save_failed += 1
continue
# Update statistics
if success:
file_save_success += 1
else:
file_save_failed += 1
except Exception as e:
logger.debug(f"❌ Failed to process {shape_id}: {e}")
file_save_failed += 1
# Update projectYAML
try:
project_manager.update_project_yaml(update.session_id)
logger.debug(f"✅ Project YAML updated")
except Exception as e:
logger.debug(f"⚠️ Failed to update project YAML: {e}")
# Return statistics
logger.debug(f"📊 Save statistics:")
logger.debug(f" - Success: {file_save_success}")
logger.debug(f" - Failed: {file_save_failed}")
logger.debug(f" - Paragraphs: {total_paragraphs_saved}")
logger.debug(f" - Runs: {total_runs_saved}")
logger.debug(f" - Tables: {total_tables_saved}")
response = {
"status": "success",
"message": f"Saved {file_save_success} modifications",
"stats": {
"shapes_success": file_save_success,
"shapes_failed": file_save_failed,
"paragraphs_saved": total_paragraphs_saved,
"runs_saved": total_runs_saved,
"tables_saved": total_tables_saved,
"data_format": "structured",
},
}
return response
except HTTPException:
raise
except Exception as e:
logger.debug(f"❌ Save failed: {e}")
raise HTTPException(500, f"Save failed: {str(e)}")
@app.get("/api/get-changes/{session_id}")
async def get_saved_changes(session_id: str):
"""Get saved changes(Load from file, support both text and table data)"""
logger.debug(f"📤 Get modifications - sessionID: {session_id}")
changes = {}
try:
# Get project data from project manager
project_data_obj = project_manager.get_project_by_session(session_id)
if not project_data_obj:
raise HTTPException(404, "Session does not exist")
project_dir = project_data_obj.get("project_dir")
if not project_dir:
raise HTTPException(400, "No project directory")
logger.debug(f"✅ Project directory: {project_dir}")
# Load all changes
changes = project_manager.fetch_changes(session_id)
logger.debug(f"📁 Load from file to {len(changes)} Modify everywhere")
# 🎯 new features:Load table data
slides_dir = os.path.join(project_dir, "slides")
if os.path.exists(slides_dir):
for filename in sorted(os.listdir(slides_dir)):
if filename.endswith(".json"):
slide_path = os.path.join(slides_dir, filename)
try:
with open(slide_path, "r", encoding="utf-8") as f:
slide_data = json.load(f)
if "shapes" in slide_data:
for shape_id, shape_info in slide_data["shapes"].items():
# Check if there is table data
if (
"table_data" in shape_info
and shape_info["table_data"]
):
try:
# Parse tabular data
table_data = json.loads(
shape_info["table_data"]
)
# Build tabular data structure
table_structure = {
"type": "table",
"original_data": shape_info.get(
"table_data", "[]"
),
"changes": {}, # Initially empty,The front end can be populated
"rows": len(table_data),
"cols": (
len(table_data[0])
if table_data and len(table_data) > 0
else 0
),
}
# Add table data tochangesmiddle
if shape_id not in changes:
changes[shape_id] = {}
# Make sure the table data is formatted correctly
if isinstance(changes[shape_id], dict):
changes[shape_id]["table"] = table_structure
else:
# If it is already text data,merge
changes[shape_id] = {
"txt": changes[shape_id],
"table": table_structure,
}
logger.debug(
f"📊 Load table data: {shape_id} ({table_structure['rows']}x{table_structure['cols']})"
)
except json.JSONDecodeError as e:
logger.debug(
f"⚠️ Failed to parse table data for {shape_id}: {e}"
)
except Exception as e:
logger.debug(f"⚠️ load {filename} fail: {e}")
# 🎯 Replenish:Make sure all table shapes have the correct structure
for shape_id, shape_data in changes.items():
if isinstance(shape_data, dict) and "table" in shape_data:
# Ensure table data is in the correct format
table_info = shape_data["table"]
if "type" not in table_info:
table_info["type"] = "table"
if "changes" not in table_info:
table_info["changes"] = {}
if "original_data" not in table_info:
table_info["original_data"] = "[]"
# 🎯 new features:Merge text and tabular data
merged_changes = {}
for shape_id, shape_data in changes.items():
if isinstance(shape_data, dict):
# If there is tabular data,Build the complete structure
if "table" in shape_data:
merged_changes[shape_id] = {
"type": "table",
"changes": shape_data["table"].get("changes", {}),
"original_data": shape_data["table"].get("original_data", "[]"),
}
# If there is text data
elif "txt" in shape_data:
merged_changes[shape_id] = {"txt": shape_data["txt"]}
# Other formats remain unchanged
else:
merged_changes[shape_id] = shape_data
else:
# Old format text data
merged_changes[shape_id] = {"txt": shape_data}
changes = merged_changes
logger.debug(f"📊 After merging: {len(changes)} shapes")
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Loading modifications failed: {e}")
raise HTTPException(500, f"Loading modifications failed: {str(e)}")
logger.debug(f"📤 return {len(changes)} Modify to session {session_id}")
return changes
@app.get("/editor/{session_id}", response_class=HTMLResponse)
async def editor_page(session_id: str):
"""Editor page - Support snapshot viewing mode"""
try:
logger.debug(f"🎯 Load editor page - sessionID: {session_id}")
# Notice:Here you need to get the query parameters from the request
# because FastAPI Parameter acquisition method,we need to adjust
project_data_obj = project_manager.get_project_by_session(session_id)
if not project_data_obj:
raise HTTPException(404, f"Session does not exist: {session_id}")
# GetGitstate,Determine whether you are in snapshot viewing mode
git_manager = project_manager.get_git_manager(session_id)
if git_manager:
snapshot_status = git_manager.get_snapshot_view_status()
is_snapshot_view = snapshot_status.get("is_snapshot_view", False)
else:
is_snapshot_view = False
# Get project information
project_dir = project_data_obj.get("project_dir", "")
project_data = project_data_obj.get("project_data", {})
content_structure = project_data_obj.get("content", [])
# make sureslidesis an array
slides = content_structure
if isinstance(slides, dict) and "slides" in slides:
slides = slides["slides"]
if not isinstance(slides, list):
slides = []
total_slides = len(slides)
# loadeditor.htmlcontent
editor_html_path = "templates/editor.html"
with open(editor_html_path, "r", encoding="utf-8") as f:
editor_html = f.read()
# usebase.htmltemplate
base_html = template_loader.load_template("base.html")
html_content = base_html.replace("{{content}}", editor_html)
# 🔥 key:Inject data,Contains snapshot viewing mode information
snapshot_extra_data = {}
if is_snapshot_view and git_manager:
snapshot_status = git_manager.get_snapshot_view_status()
snapshot_extra_data = {
"is_snapshot_view": True,
"commit_hash": snapshot_status.get("commit_hash"),
"short_hash": snapshot_status.get("short_hash"),
"switched_at": snapshot_status.get("switched_at"),
"original_state": snapshot_status.get("original_state"),
"can_exit_snapshot": True,
}
# Get snapshot description
commit_hash = snapshot_status.get("commit_hash")
if commit_hash:
log_success, log_output = git_manager._run_git_command(
["log", "--format=%s", "-n", "1", commit_hash]
)
if log_success:
snapshot_extra_data["snapshot_description"] = log_output.strip()
data_injection = f"""
<script type="module">
import {{ logger }} from "/static/js/logger.js";
// Set data
window.editorData = {{
slidesData: {json.dumps(slides)},
sessionId: "{session_id}",
totalSlides: {total_slides},
projectInfo: {{
session_id: "{session_id}",
project_dir: {json.dumps(project_dir)},
project_id: "{project_data.get('project', {}).get('id', '')}",
project_name: "{project_data.get('project', {}).get('name', 'Unnamed')}",
...{json.dumps(snapshot_extra_data)}
}}
}};
logger.debug("✅ window.editorData Already set");
logger.debug("📊 slidesDatalength:", window.editorData.slidesData.length);
logger.debug("📸 Snapshot viewing mode:", window.editorData.projectInfo.is_snapshot_view);
// Initialize immediately(make sureeditor.jsLoaded)
if (typeof initEditor === 'function') {{
logger.debug("🚀 Initialize editor now");
initEditor(
window.editorData.slidesData,
window.editorData.sessionId,
window.editorData.totalSlides,
window.editorData.projectInfo
);
}} else {{
logger.debug("⏳ editor.jsnot loaded,Wait for loading to complete");
// monitoreditor.jsload
const checkInterval = setInterval(function() {{
if (typeof initEditor === 'function') {{
clearInterval(checkInterval);
logger.debug("🚀 detectedinitEditor,Start initialization");
initEditor(
window.editorData.slidesData,
window.editorData.sessionId,
window.editorData.totalSlides,
window.editorData.projectInfo
);
}}
}}, 100);
}}
</script>
"""
html_content = html_content.replace("</body>", f"{data_injection}\n</body>")
logger.debug(f"✅ Editor page generation completed")
return HTMLResponse(html_content)
except Exception as e:
logger.debug(f"❌ Failed to load editor page: {e}")
import traceback
traceback.print_exc()
error_html = f"""
<!DOCTYPE html>
<html>
<head><title>Editor error</title></head>
<body style="font-family: Arial; padding: 20px;">
<h1>Editor failed to load</h1>
<p>sessionID: {session_id}</p>
<p>mistake: {str(e)}</p>
<pre>{traceback.format_exc()}</pre>
<a href="/">Return to homepage</a>
</body>
</html>
"""
return HTMLResponse(error_html)
@app.get("/api/debug-filesystem/{session_id}")
async def debug_filesystem(session_id):
"""Debug file system status"""
return project_manager.check_project(session_id)
@app.post("/api/create-project")
async def create_project(
pptx_file: UploadFile = File(...),
project_name: str = Form(...),
# no longer needed project_dir parameter
):
"""Create new project - Use system-specific data directories"""
try:
logger.debug(f"🔄 Start creating a project: {project_name}")
# 1. Determine application data directory
user_data_dir = platformdirs.user_data_dir("PPTeXpress", "Paradoxsolver")
# Make sure the application directory exists
os.makedirs(user_data_dir, exist_ok=True)
logger.debug(f"📁 application data directory: {user_data_dir}")
# 2. Create project directory(use session_id as directory name)
# First generate session_id
session_id = str(uuid.uuid4())
project_dir = os.path.join(user_data_dir, session_id)
logger.debug(f"📁 Project directory: {project_dir}")
# 3. Save uploadedPPTXto temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp:
content = await pptx_file.read()
tmp.write(content)
tmp_path = tmp.name
# 4. Initialize project
logger.debug(f"🔄 Initialize project...")
try:
results = project_manager.create_project_with_data(
tmp_path, project_dir, project_name
)
logger.debug(f"✅ Project created successfully: {session_id}")
except Exception as e:
logger.debug(f"❌ Project creation failed: {e}")
raise
# 5. Clean temporary files
os.unlink(tmp_path)
return results
except Exception as e:
logger.debug(f"❌ Failed to create project: {e}")
import traceback
traceback.print_exc()
raise HTTPException(500, f"Failed to create project: {str(e)}")
@app.get("/api/recent-projects")
async def recent_projects():
"""List available items"""
try:
logger.debug("🔄 Get a list of recent projects")
# Call the project manager to get the project list
projects = project_manager.get_recent_projects()
logger.debug(f"✅ Get {len(projects)} items")
# Returns the format expected by the front end(IncludestatusField)
return {
"status": "success",
"projects": projects,
"count": len(projects),
"message": f"turn up {len(projects)} items",
}
except Exception as e:
logger.debug(f"❌ Failed to get recent items: {e}")
import traceback
traceback.print_exc()
return {
"status": "error",
"message": f"Failed to get project list: {str(e)}",
"projects": [],
}
@app.get("/", response_class=HTMLResponse)
async def home():
"""Home page"""
logger.debug("🔄 Visit homepage")
try:
home_content = template_loader.load_template("home.html")
return HTMLResponse(home_content)
except Exception as e:
logger.debug(f"❌ Failed to load home page: {e}")
import traceback
traceback.print_exc()
# Return to simple error page
error_html = f"""
<!DOCTYPE html>
<html>
<head><title>Home page error</title></head>
<body style="font-family: Arial; padding: 20px;">
<h1>Home page loading error</h1>
<p>mistake: {str(e)}</p>
</body>
</html>
"""
return HTMLResponse(error_html)
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
"""Unified error handling"""
if request.url.path.startswith("/api/"):
# APIerror returnJSON
return JSONResponse(
status_code=exc.status_code,
content={"status": "error", "message": exc.detail},
)
else:
# Page error returnHTML
error_html = f"""
<div style="max-width: 600px; margin: 100px auto; text-align: center;">
<h1>mistake {exc.status_code}</h1>
<p>{exc.detail}</p>
<a href="/">Return to homepage</a>
</div>
"""
return HTMLResponse(error_html, status_code=exc.status_code)
@app.get("/new-project", response_class=HTMLResponse)
async def new_project_page():
"""New project page"""
logger.debug("🔄 Visit the new project page")
# try to loadnew-project.htmltemplate,Create a simple version if it does not exist
try:
# First check if the template exists
template_path = "templates/new-project.html"
with open(template_path, "r", encoding="utf-8") as f:
new_project_html = f.read()
# usebase.htmlTemplate packaging
base_html = template_loader.load_template("base.html")
html_content = base_html.replace("{{content}}", new_project_html)
return HTMLResponse(html_content)
except Exception as e:
logger.debug(f"❌ Failed to load new project page: {e}")
import traceback
traceback.print_exc()
# Return error page
error_html = f"""
<div style="padding: 20px; color: #721c24; background: #f8d7da; border: 1px solid #f5c6cb;">
<h2>Failed to load new project page</h2>
<p>{str(e)}</p>
<a href="/">Return to home page</a>
</div>
"""
base_html = template_loader.load_template("base.html")
html_content = base_html.replace("{{content}}", error_html)
return HTMLResponse(html_content)
@app.get("/api/verify-session/{session_id}")
async def verify_session(session_id: str):
"""Verify session state"""
project_data_obj = project_manager.get_project_by_session(session_id)
if not project_data_obj:
return {"valid": False, "error": "Session does not exist"}
content = project_data_obj.get("content", {})
project_data = project_data_obj.get("project_data", {})
return {
"valid": True,
"session_id": session_id,
"project_id": project_data.get("project", {}).get("id"),
"project_name": project_data.get("project", {}).get("name"),
"content_type": type(content).__name__,
"is_list": isinstance(content, list),
"list_length": len(content) if isinstance(content, list) else 0,
"has_slides_key": isinstance(content, dict) and "slides" in content,
"session_in_manager": session_id in project_manager.sessions,
}
@app.get("/debug-sessions")
async def debug_all_sessions():
"""Debug all sessions"""
# useProjectManagerdebugging method
logger.debug("🔍 Debug all sessions...")
sessions_info = []
for session_id, project_id in project_manager.sessions.items():
project = project_manager.projects.get(project_id)
sessions_info.append(
{
"session_id": session_id,
"project_id": project_id,
"project_dir": project.get("project_dir", "N/A") if project else "N/A",
"content_length": len(project.get("content", [])) if project else 0,
"has_content": bool(project.get("content")) if project else False,
}
)
return {
"total_sessions": len(project_manager.sessions),
"total_projects": len(project_manager.projects),
"sessions": sessions_info,
}
@app.get("/api/open-recent/{session_id}")
async def api_open_recent_project(session_id: str):
"""passsession_id(directory name)Open recent projects"""
try:
logger.debug(f"🔄 Open recent projects: session_id={session_id}")
# 1. Build project directory path(session_idIt’s the directory name)
app_data_dir = project_manager.get_app_data_dir()
project_dir = os.path.join(app_data_dir, session_id)
# 2. Verify directory exists
if not os.path.exists(project_dir):
raise HTTPException(404, f"Project directory does not exist: {session_id}")
# 3. useopen_projectmethod
result = project_manager.open_project(project_dir)
if result["status"] != "success":
raise HTTPException(400, result["message"])
logger.debug(f"✅ The recent project was successfully opened:")
logger.debug(f" session_id: {result['session_id']}")
logger.debug(f" Project name: {result['project_info']['name']}")
return {
"status": "success",
"session_id": result["session_id"],
"project_info": result["project_info"],
"message": f"project '{result['project_info']['name']}' Opened",
}
except HTTPException:
raise
except Exception as e:
logger.debug(f"❌ Failed to open recent project: {e}")
import traceback
traceback.print_exc()
raise HTTPException(500, f"Failed to open recent project: {str(e)}")
@app.delete("/api/delete-project/{session_id}")
async def api_delete_project(session_id: str):
"""Delete project"""
try:
logger.debug(f"🗑️ Delete project: {session_id}")
# 🔧 New:Clean the project first,in particularGitstorehouse
logger.debug("🧹 Start cleaning project(releaseGitfile lock)...")
cleanup_result = project_manager.cleanup_project_for_deletion(session_id)
if not cleanup_result.get("success", False):
logger.debug(
f"⚠️ Project cleanup failed,but still trying to delete: {cleanup_result.get('message')}"
)
# 1. Get project data(Use original logic)
project = project_manager.get_project_by_session(session_id)
# 🔧 Revise:If there is project data in memory,clean up firstGitManager
if project and session_id in project_manager.git_managers:
try:
del project_manager.git_managers[session_id]
logger.debug(f"🗑️ Clean up the memoryGitManager: {session_id}")
except:
pass
if not project:
# 🔧 Alternatives:If there is no memory,Try deleting the directory directly
app_data_dir = project_manager.get_app_data_dir()
project_dir = os.path.join(app_data_dir, session_id)
if not os.path.exists(project_dir):
raise HTTPException(
404, f"Project directory does not exist: {session_id}"
)
# 🔧 Revise:Try cleaning again before deleting.gitTable of contents
git_dir = os.path.join(project_dir, ".git")
if os.path.exists(git_dir):
logger.debug(f"🧹 detected.gitTable of contents,try to clean...")
try:
# Try usingGitManagerclean up(if possible)
temp_git_manager = GitManager(project_dir)
temp_git_manager.cleanup_repository()
# A short delay to allow the system to release the file lock
import time
time.sleep(0.5)
except Exception as e:
logger.debug(f"⚠️ temporaryGitManagerCleanup failed: {e}")
# Read project name
yaml_path = os.path.join(project_dir, "project.yaml")
if os.path.exists(yaml_path):
with open(yaml_path, "r", encoding="utf-8") as f:
project_data = yaml.safe_load(f)
project_name = project_data.get("project", {}).get(
"name", "Unnamed project"
)
else:
project_name = session_id[:8] # before directory name8bit as name
# delete directory
try:
# 🔧 Revise:Use a more robust removal method
force_delete_directory(project_dir)
logger.debug(f"✅ Delete project directory: {project_dir}")
except Exception as e:
logger.debug(f"❌ Failed to delete directory: {e}")
raise HTTPException(500, f"Failed to delete directory: {str(e)}")
return {"status": "success", "message": f"project '{project_name}' Deleted"}
# 🔧 repair:Correctly obtain the project directory and name
project_dir = project["project_dir"]
project_data = project.get("project_data", {})
project_name = project_data.get("project", {}).get("name", "Unnamed project")
logger.debug(f"📋 Delete project information:")
logger.debug(f" Project directory: {project_dir}")
logger.debug(f" Project name: {project_name}")
logger.debug(
f" projectID: {project_data.get('project', {}).get('id', 'N/A')}"
)
# 2. Verify project directory exists
if not os.path.exists(project_dir):
raise HTTPException(404, "Project directory does not exist")
# 3. Delete project directory
try:
# 🔧 Revise:Use new force delete method
force_delete_directory(project_dir)
logger.debug(f"✅ Delete project directory: {project_dir}")
except Exception as e:
logger.debug(f"❌ Failed to delete directory: {e}")
raise HTTPException(500, f"Failed to delete directory: {str(e)}")
# 4. fromProjectManagerRemove sessions and data from
try:
# Remove session mapping
if session_id in project_manager.sessions:
del project_manager.sessions[session_id]
# logger.debug(f"✅ Remove session mapping: {session_id}")
# Remove project data(Need to find the correspondingproject_id)
project_id = project_data.get("project", {}).get("id")
if project_id and project_id in project_manager.projects:
del project_manager.projects[project_id]
# logger.debug(f"✅ Remove project data: {project_id}")
except Exception as e:
logger.debug(f"⚠️ An error occurred while clearing memory data: {e}")
# Continue execution,Does not affect directory deletion
return {
"status": "success",
"message": f"project '{project_name}' Deleted",
"project_name": project_name,
"session_id": session_id,
}
except HTTPException:
raise
except Exception as e:
logger.debug(f"❌ Failed to delete item: {e}")
import traceback
traceback.print_exc()
raise HTTPException(500, f"Failed to delete item: {str(e)}")
@app.get("/api/project/{session_id}/images")
async def get_project_images(session_id: str):
"""Get all images in the project"""
try:
images_info = project_manager.list_project_images(session_id)
return {"status": "success", "session_id": session_id, "data": images_info}
except Exception as e:
logger.debug(f"❌ Failed to get image list: {e}")
return JSONResponse(
status_code=500, content={"status": "error", "message": str(e)}
)
@app.get("/api/project/{session_id}/image/{image_filename}")
async def get_project_image(session_id: str, image_filename: str):
"""Get a single image file in the project(Simple extension matching)"""
try:
project = project_manager.get_project_by_session(session_id)
if not project:
raise HTTPException(404, "Project does not exist")
project_dir = project["project_dir"]
images_dir = os.path.join(project_dir, "assets", "images")
if not os.path.exists(images_dir):
raise HTTPException(404, "Picture directory does not exist")
# 🔧 simple match:Remove requested extension,matches any extension
main_name = os.path.splitext(image_filename)[0]
# Find matching files
for file in os.listdir(images_dir):
if os.path.splitext(file)[0] == main_name:
image_path = os.path.join(images_dir, file)
# Determine media type
ext = os.path.splitext(file)[1].lower()
media_types = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".bmp": "image/bmp",
}
media_type = media_types.get(ext, "application/octet-stream")
return FileResponse(image_path, media_type=media_type, filename=file)
raise HTTPException(404, f"Picture does not exist: {image_filename}")
except HTTPException:
raise
except Exception as e:
logger.debug(f"❌ Failed to get image: {e}")
raise HTTPException(500, f"Failed to get image: {str(e)}")
@app.post("/api/project/{session_id}/upload-image")
async def upload_project_image(session_id: str, file: UploadFile = File(...)):
"""Upload images to project"""
try:
logger.debug(f"📤 Upload images to project: {session_id}")
# Verify file type
allowed_types = ["image/png", "image/jpeg", "image/gif", "image/bmp"]
if file.content_type not in allowed_types:
raise HTTPException(400, "Only supportsPNG,JPEG,GIF,BMPformat pictures")
# Read file contents
image_data = await file.read()
# Verify file size(For example5MBlimit)
if len(image_data) > 5 * 1024 * 1024:
raise HTTPException(400, "Image size cannot exceed5MB")
# Upload pictures
result = project_manager.upload_image(session_id, file.filename, image_data)
if not result.get("success", False):
raise HTTPException(500, result.get("error", "Upload failed"))
return {
"status": "success",
"message": "Image uploaded successfully",
"data": result,
}
except HTTPException:
raise
except Exception as e:
logger.debug(f"❌ Failed to upload image: {e}")
raise HTTPException(500, f"Failed to upload image: {str(e)}")
@app.post("/api/project/{session_id}/save-image-changes")
async def save_image_changes(session_id: str, changes: dict):
"""Save image modification information"""
try:
logger.debug(f"💾 Save image changes: {session_id}")
logger.debug(f" Modify quantity: {len(changes)}")
project_data_obj = project_manager.get_project_by_session(session_id)
if not project_data_obj:
raise HTTPException(404, "Session does not exist")
project_dir = project_data_obj.get("project_dir")
if not project_dir:
raise HTTPException(400, "This session has no associated project directory")
# Save image modification information to file
images_json_path = os.path.join(project_dir, "images.json")
# Read existing image information
existing_data = {}
if os.path.exists(images_json_path):
try:
with open(images_json_path, "r", encoding="utf-8") as f:
existing_data = json.load(f)
except:
existing_data = {}
# Update data
existing_data.update(changes)
# save to file
with open(images_json_path, "w", encoding="utf-8") as f:
json.dump(existing_data, f, indent=2, ensure_ascii=False)
logger.debug(f"✅ Image modification and saving completed: {images_json_path}")
return {
"status": "success",
"message": f"saved {len(changes)} Picture modification",
"file_path": images_json_path,
}