-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1158 lines (930 loc) · 45.2 KB
/
app.py
File metadata and controls
1158 lines (930 loc) · 45.2 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 os
import shutil
from fastapi import FastAPI, UploadFile, File, Form, BackgroundTasks
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.requests import Request
from dotenv import load_dotenv
import asyncio
import urllib.request
import urllib.error
import requests
import mimetypes
from src.analyzer import Analyzer
from src.image_processor import ImageProcessor
from src.code_generator import CodeGenerator
from src.pptx_generator import PPTXGenerator
from src.utils import generate_timestamp, ensure_directory, get_logger
from datetime import datetime
import json
import uuid
from typing import List
from src.security_utils import validate_safe_path
load_dotenv(override=True)
logger = get_logger(__name__)
# PPTX MIME 타입 명시적 등록 (브라우저 인식 개선)
mimetypes.add_type('application/vnd.openxmlformats-officedocument.presentationml.presentation', '.pptx')
app = FastAPI(title="Slide Reconstructor")
# Directory Setup
# Directory Setup
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
INPUT_DIR = os.path.join(BASE_DIR, "input")
OUTPUT_DIR = os.path.join(BASE_DIR, "output")
STATIC_DIR = os.path.join(BASE_DIR, "static")
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates")
UPLOAD_DIR = os.path.join(STATIC_DIR, "uploads")
for d in [INPUT_DIR, OUTPUT_DIR, STATIC_DIR, TEMPLATES_DIR, UPLOAD_DIR]:
ensure_directory(d)
# Mount Static & Templates
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/output", StaticFiles(directory=OUTPUT_DIR), name="output")
templates = Jinja2Templates(directory=TEMPLATES_DIR)
# Default Settings
# Default Settings (New Structure)
DEFAULT_SETTINGS = {
"common": {
"exclude_text": ""
},
"reconstruct": {
"vision_model": "gemini-3-flash-preview",
"inpainting_model": "opencv-telea",
"codegen_model": "algorithmic",
"output_format": "both",
"max_concurrent": 15,
"font_family": "Malgun Gothic",
"refine_layout": False
},
"pdf_pptx": {
"pdf_quality": "3.0",
"vision_model": "gemini-3-flash-preview",
"inpainting_model": "opencv-telea",
"codegen_model": "algorithmic",
"output_format": "both",
"max_concurrent": 15,
"font_family": "Malgun Gothic",
"refine_layout": False
},
"pdf_png": {
"vision_model": "gemini-3-flash-preview",
"inpainting_model": "opencv-telea",
"codegen_model": "algorithmic",
"output_format": "both",
"max_concurrent": 15,
"font_family": "Malgun Gothic",
"refine_layout": False
},
"photoroom": {
"mode": "ai.all"
}
}
SETTINGS_FILE = os.path.join(BASE_DIR, "settings.json")
def load_settings():
try:
if os.path.exists(SETTINGS_FILE):
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logger.error(f"Failed to load settings: {e}")
return DEFAULT_SETTINGS.copy()
def save_settings_to_file(settings):
try:
with open(SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=4)
return True
except Exception as e:
logger.error(f"Failed to save settings: {e}")
return False
# Initialize Core Modules
current_settings = load_settings()
# Use reconstruct settings as default for analyzer if specific context not provided
default_vision_model = current_settings.get("reconstruct", {}).get("vision_model", "gemini-3-flash-preview")
analyzer = Analyzer(model_name=default_vision_model)
image_processor = ImageProcessor()
code_generator = CodeGenerator()
pptx_generator = PPTXGenerator()
@app.get("/settings")
async def get_settings():
return JSONResponse(load_settings())
@app.get("/system/models")
async def get_system_models():
settings = load_settings()
system_conf = settings.get("system", {})
return JSONResponse({
"models": system_conf.get("allowed_vision_models", []),
"default": system_conf.get("default_vision_model", "gemini-3-flash-preview")
})
@app.post("/settings")
async def update_settings(request: Request):
# Partial update logic
incoming_data = await request.json()
current_data = load_settings()
# Merge existing structure with incoming changes (deep merge preferred, or key-level repl)
# Incoming might be { "reconstruct": { ... } } or { "common": { ... } }
for section, values in incoming_data.items():
if section in current_data and isinstance(values, dict):
current_data[section].update(values)
else:
current_data[section] = values
save_settings_to_file(current_data)
# Update active analyzer if reconstruct vision model changed
if "reconstruct" in incoming_data and "vision_model" in incoming_data["reconstruct"]:
analyzer.model_name = incoming_data["reconstruct"]["vision_model"]
return JSONResponse({"status": "success", "settings": current_data})
@app.get("/api-key")
async def get_api_key(request: Request):
"""
Returns the current API Key (full).
Frontend will handle masking.
"""
key = os.environ.get("GOOGLE_API_KEY", "")
return JSONResponse({"api_key": key})
@app.post("/api-key")
async def update_api_key(request: Request):
"""
Updates GOOGLE_API_KEY in .env file and reloads environment.
"""
try:
data = await request.json()
new_key = data.get("api_key", "").strip()
if not new_key:
return JSONResponse(status_code=400, content={"message": "API Key cannot be empty"})
# 1. Update .env file
env_path = os.path.join(BASE_DIR, ".env")
# Read existing content
lines = []
if os.path.exists(env_path):
with open(env_path, "r", encoding="utf-8") as f:
lines = f.readlines()
found = False
new_lines = []
for line in lines:
if line.strip().startswith("GOOGLE_API_KEY="):
new_lines.append(f"GOOGLE_API_KEY={new_key}\n")
found = True
else:
new_lines.append(line)
if not found:
# If not found (or empty file), append it
if new_lines and not new_lines[-1].endswith('\n'):
new_lines.append('\n')
new_lines.append(f"GOOGLE_API_KEY={new_key}\n")
with open(env_path, "w", encoding="utf-8") as f:
f.writelines(new_lines)
# 2. Update Runtime Environment
os.environ["GOOGLE_API_KEY"] = new_key
# 3. Reload Analyzer Client
global analyzer
# Analyzer re-init will pick up new os.environ key
current_vision_model = analyzer.model_name
try:
analyzer = Analyzer(model_name=current_vision_model)
logger.info("Analyzer re-initialized with new API Key.")
except Exception as e:
logger.error(f"Failed to re-init analyzer: {e}")
return JSONResponse(status_code=500, content={"message": "Saved key but failed to reload analyzer. Please restart server."})
return JSONResponse({"status": "success", "message": "API Key updated successfully."})
except Exception as e:
logger.error(f"Failed to update API Key: {e}")
return JSONResponse(status_code=500, content={"message": str(e)})
@app.post("/test-api-key")
async def test_api_key(request: Request):
"""
Tests the API Key using Gemini 2.5 Flash.
Accepts 'api_key' in body. If missing, uses environment variable.
"""
try:
data = await request.json()
api_key_to_test = data.get("api_key", "").strip()
# If no key provided, use current env var
if not api_key_to_test:
api_key_to_test = os.environ.get("GOOGLE_API_KEY", "")
if not api_key_to_test:
return JSONResponse(status_code=400, content={"message": "No API Key provided to test."})
# Import explicitly to ensure availability
from google import genai
# Initialize client with the specific key
client = genai.Client(api_key=api_key_to_test)
# Run Test (Using configured vision_model from settings)
target_model = current_settings.get("vision_model", "gemini-3-flash-preview")
try:
response = client.models.generate_content(
model=target_model,
contents="Explain how AI works in a few words"
)
return JSONResponse({
"status": "success",
"message": f"API Key is valid! (Tested with {target_model})",
"response": response.text
})
except Exception as e_test:
logger.error(f"Model {target_model} Access Failed: {e_test}")
error_msg = str(e_test)
if "API_KEY_INVALID" in error_msg or "INVALID_ARGUMENT" in error_msg:
return JSONResponse(status_code=400, content={
"status": "error",
"message": f"유효하지 않은 API Key입니다. ({target_model} 테스트 실패)",
"details": str(e_test)
})
else:
return JSONResponse(status_code=500, content={
"status": "error",
"message": f"테스트 실패 ({target_model}): {str(e_test)}"
})
except Exception as e:
logger.error(f"API Key Test Failed: {e}")
return JSONResponse(status_code=500, content={"message": f"Test Failed: {str(e)}"})
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
# Progress tracking storage (Simple in-memory for demo)
progress_store = {}
@app.get("/progress/{task_id}")
async def progress_stream(task_id: str):
async def event_generator():
while True:
if task_id in progress_store:
data = progress_store[task_id]
yield f"data: {json.dumps(data)}\n\n"
if data['status'] in ['complete', 'error']:
break
await asyncio.sleep(0.5)
# Timeout/Cleanup logic could be added here
return StreamingResponse(event_generator(), media_type="text/event-stream")
@app.post("/upload")
async def upload_file(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
vision_model: str = Form("gemini-3-flash-preview"),
inpainting_model: str = Form("opencv-telea"),
codegen_model: str = Form("algorithmic"),
batch_folder: str = Form("single"),
max_concurrent: int = Form(3), # Receive concurrency setting
exclude_text: str = Form(None),
font_family: str = Form("Malgun Gothic"), # Default font
refine_layout: bool = Form(False)
):
# Concurrency controlled by global semaphore (fixed at startup)
timestamp = generate_timestamp()
task_id = str(uuid.uuid4()) # Use UUID for unique task tracking
original_name = os.path.splitext(file.filename)[0]
ext = os.path.splitext(file.filename)[1]
input_filename = f"{original_name}_{timestamp}{ext}"
# SAVE DIRECTLY TO OUTPUT DIR (User Request)
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
ensure_directory(target_dir)
input_path = os.path.join(target_dir, input_filename)
# Function to run in thread
def save_file_sync(infile, outpath):
with open(outpath, "wb") as buffer:
shutil.copyfileobj(infile, buffer)
await asyncio.to_thread(save_file_sync, file.file, input_path)
logger.info(f"File uploaded to Output Dir: {input_path}")
# Initialize progress
progress_store[task_id] = {"status": "starting", "message": "Starting process...", "percent": 0}
# Run processing in background
logger.info(f"Adding background task for {task_id}")
background_tasks.add_task(
process_slide_task,
task_id,
input_path,
original_name,
vision_model,
inpainting_model,
codegen_model,
batch_folder,
exclude_text,
font_family,
refine_layout
)
return JSONResponse({"status": "processing", "task_id": task_id})
# Concurrency Limit
MAX_CONCURRENT_TASKS = int(current_settings.get("max_concurrent", 3))
semaphore = asyncio.Semaphore(MAX_CONCURRENT_TASKS)
# Cancellation Store
cancelled_tasks = set()
# Pause Control
pause_event = asyncio.Event()
pause_event.set() # Initially True (Running)
@app.post("/pause")
async def pause_processing():
pause_event.clear()
logger.info(" Global Processing PAUSED")
return JSONResponse({"status": "paused"})
@app.post("/resume")
async def resume_processing():
pause_event.set()
logger.info(" Global Processing RESUMED")
return JSONResponse({"status": "resumed"})
async def wait_if_paused(task_id):
"""
Checks if global pause is active. If so, waits until resumed.
Also handles cancellation during pause.
"""
if not pause_event.is_set():
logger.info(f"Task {task_id} entering PAUSE state...")
# Save previous state to restore later if needed, or just update to paused
if task_id in progress_store:
progress_store[task_id]['status'] = 'paused'
progress_store[task_id]['message'] = "⏸️ 일시정지됨 (재개 대기 중...)"
while not pause_event.is_set():
if task_id in cancelled_tasks:
return # Exit loop to handle cancellation in main flow
await asyncio.sleep(0.5)
logger.info(f"Task {task_id} RESUMING...")
if task_id in progress_store and task_id not in cancelled_tasks:
progress_store[task_id]['status'] = 'processing'
@app.post("/cancel/{task_id}")
async def cancel_task(task_id: str):
cancelled_tasks.add(task_id)
# Also update progress immediately to stop frontend polling if possible
if task_id in progress_store:
progress_store[task_id]["status"] = "cancelled"
progress_store[task_id]["message"] = "작업이 취소되었습니다."
return JSONResponse({"status": "cancelled"})
return JSONResponse({"status": "cancelled"})
async def process_combine_task(task_id, source_path, bg_path, original_name, vision_model, codegen_model, batch_folder, font_family="Malgun Gothic", refine_layout=False, exclude_text=None):
async with semaphore:
if task_id in cancelled_tasks:
cancelled_tasks.discard(task_id)
return
logger.info(f"Starting process_combine_task for {task_id} (Refine: {refine_layout})")
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
ensure_directory(target_dir)
try:
await wait_if_paused(task_id)
if task_id in cancelled_tasks: return
# 1. Analyze Source
# Update model
analyzer.model_name = vision_model
file_id = generate_timestamp()
progress_store[task_id] = {"status": "processing", "message": "[1단계] 원본 텍스트 분석 중...", "percent": 20}
# 1.1 Initial Detection
layout_data, width, height = await asyncio.to_thread(analyzer.detect_initial_layout, source_path)
# 1.2 Refinement (Optional)
if refine_layout:
progress_store[task_id] = {"status": "processing", "message": "[1.5단계] 정밀 분석 (Refinement) 수행 중...", "percent": 40}
layout_data = await asyncio.to_thread(analyzer.refine_layout, source_path, layout_data)
# 1.3 Pixel Convert
layout_data = analyzer.convert_to_pixels(layout_data, width, height)
# 1.4 Normalize
layout_data = code_generator.normalize_font_sizes(layout_data, width)
# 1.5 Text Exclusion (Fix for Watermark)
# Use provided exclude_text or default
if not exclude_text:
exclude_text = "NotebookLM, 워터마크" # Default as per user request
full_layout_data = layout_data
filtered_layout_data = analyzer.apply_text_exclusion(layout_data, exclude_text)
# Save JSON
json_filename = f"{original_name}_layout_{file_id}.json"
# Also save as filtered for PPTX batch compatibility logic
json_filename_filtered = f"{original_name}_layout_{file_id}_filtered.json"
json_path = os.path.join(target_dir, json_filename)
with open(json_path, "w", encoding="utf-8") as f:
json.dump(full_layout_data, f, indent=4, ensure_ascii=False)
json_path_filtered = os.path.join(target_dir, json_filename_filtered)
with open(json_path_filtered, "w", encoding="utf-8") as f:
json.dump(filtered_layout_data, f, indent=4, ensure_ascii=False)
await wait_if_paused(task_id)
if task_id in cancelled_tasks: return
# Step 2: Skip Inpainting, Use Provided BG
# Fix for PPTX Size: Resize Provided BG to Match Source Dimensions
# User reported text size issues in batch. Batch uses BG image size.
# If BG size != Source Size, Layout (based on Source) is mismatched.
# We must resize BG to Source (width, height).
final_bg_filename = f"{original_name}_bg_{file_id}.png"
final_bg_path = os.path.join(target_dir, final_bg_filename)
# Resize logic using PIL in thread
def resize_bg(src_bg, target_w, target_h, dest_path):
from PIL import Image
with Image.open(src_bg) as img:
msg_log = f"Resizing BG from {img.size} to ({target_w}, {target_h})"
img_resized = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
img_resized.save(dest_path)
return msg_log
msg = await asyncio.to_thread(resize_bg, bg_path, width, height, final_bg_path)
logger.info(msg)
# Step 3: Generate HTML
progress_store[task_id] = {"status": "processing", "message": "[2단계] HTML 생성 중...", "percent": 60}
html_filename = f"{original_name}_slide_{file_id}.html"
html_path = os.path.join(target_dir, html_filename)
await asyncio.to_thread(code_generator.generate_html, filtered_layout_data, width, height, final_bg_path, html_path, normalize=False, font_family=font_family)
# Step 4: Generate PPTX
progress_store[task_id] = {"status": "processing", "message": "[3단계] PPTX 생성 중...", "percent": 80}
# Check settings
current_settings_local = load_settings()
output_fmt = current_settings_local.get("output_format", "both")
pptx_url = None
if output_fmt in ["pptx", "both"]:
pptx_filename = f"{original_name}_slide_{file_id}.pptx"
pptx_path = os.path.join(target_dir, pptx_filename)
pptx_gen_single = PPTXGenerator()
pptx_gen_single.add_slide(filtered_layout_data, final_bg_path, width, height, font_family=font_family)
pptx_gen_single.save(pptx_path)
pptx_url = f"/output/{batch_folder}/{pptx_filename}"
# Complete
progress_store[task_id] = {
"status": "complete",
"message": "[완료] 조합 작업이 끝났습니다.",
"percent": 100,
"data": {
"html_url": f"/output/{batch_folder}/{html_filename}",
"bg_url": f"/output/{batch_folder}/{final_bg_filename}",
"pptx_url": pptx_url
}
}
except Exception as e:
logger.error(f"Combine Task Error: {e}")
progress_store[task_id] = {"status": "error", "message": str(e), "percent": 0}
# --- Refactored Helpers ---
async def _perform_analysis(input_path, task_id, vision_model, refine_layout, exclude_text):
# Update model
analyzer.model_name = vision_model
logger.info(f"Analyzer model set to: {analyzer.model_name}")
# 1.1 Initial Detection
layout_data, width, height = await asyncio.to_thread(analyzer.detect_initial_layout, input_path)
logger.info(f"Initial Analysis complete for {task_id}. Width: {width}, Height: {height}")
# 1.2 Refinement
if refine_layout:
layout_data = await asyncio.to_thread(analyzer.refine_layout, input_path, layout_data)
# 1.3 Pixel Convert
layout_data = analyzer.convert_to_pixels(layout_data, width, height)
# 1.4 Normalize
layout_data = code_generator.normalize_font_sizes(layout_data, width)
# 1.5 Text Exclusion
full_layout_data = layout_data
filtered_layout_data = analyzer.apply_text_exclusion(layout_data, exclude_text)
return full_layout_data, filtered_layout_data, width, height
async def _perform_inpainting(input_path, layout_data, bg_path):
# CRITICAL: Use full_layout_data here to ensure Watermarks are ERASED from background
await asyncio.to_thread(image_processor.create_clean_background, input_path, layout_data, bg_path)
async def _generate_html_slide(layout_data, w, h, bg_path, html_path, font_family, codegen_model):
await asyncio.to_thread(code_generator.generate_html, layout_data, w, h, bg_path, html_path, normalize=False, font_family=font_family, model_name=codegen_model)
async def _generate_pptx_slide(layout_data, bg_path, w, h, pptx_path, font_family):
def _gen():
try:
pptx_gen_single = PPTXGenerator()
pptx_gen_single.add_slide(layout_data, bg_path, w, h, font_family=font_family)
pptx_gen_single.save(pptx_path)
return True
except Exception as e:
logger.error(f"PPTX Gen Error: {e}")
return False
return await asyncio.to_thread(_gen)
async def process_slide_task(task_id, input_path, original_name, vision_model, inpainting_model, codegen_model, batch_folder, exclude_text=None, font_family="Malgun Gothic", refine_layout=False):
async with semaphore:
if task_id in cancelled_tasks:
logger.info(f"Task {task_id} cancelled before starting.")
cancelled_tasks.discard(task_id)
return
logger.info(f"Starting process_slide_task for {task_id} with model {vision_model}")
# Determine Output Directory
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
ensure_directory(target_dir)
try:
await wait_if_paused(task_id)
if task_id in cancelled_tasks: return
# Generate timestamp ID
file_id = generate_timestamp()
# Step 1: Layout Analysis
progress_store[task_id] = {"status": "processing", "message": "[1단계] 이미지 레이아웃 분석 중...", "percent": 10}
full_layout_data, filtered_layout_data, width, height = await _perform_analysis(
input_path, task_id, vision_model, refine_layout, exclude_text
)
# Save JSONs
json_filename_raw = f"{original_name}_layout_{file_id}.json"
json_path_raw = os.path.join(target_dir, json_filename_raw)
with open(json_path_raw, "w", encoding="utf-8") as f:
json.dump(full_layout_data, f, indent=4, ensure_ascii=False)
json_filename_filtered = f"{original_name}_layout_{file_id}_filtered.json"
json_path_filtered = os.path.join(target_dir, json_filename_filtered)
with open(json_path_filtered, "w", encoding="utf-8") as f:
json.dump(filtered_layout_data, f, indent=4, ensure_ascii=False)
# Check Pause/Cancel
if task_id in cancelled_tasks:
progress_store[task_id] = {"status": "cancelled", "message": "취소됨", "percent": 0}; return
await wait_if_paused(task_id)
if task_id in cancelled_tasks: return
# Step 2: Inpainting
progress_store[task_id] = {"status": "processing", "message": "[2단계] 배경 복원 중...", "percent": 60}
bg_filename = f"{original_name}_bg_{file_id}.png"
bg_path = os.path.join(target_dir, bg_filename)
await _perform_inpainting(input_path, full_layout_data, bg_path)
# Check Pause/Cancel
if task_id in cancelled_tasks:
progress_store[task_id] = {"status": "cancelled", "message": "취소됨", "percent": 0}; return
await wait_if_paused(task_id)
if task_id in cancelled_tasks: return
# Step 3: Generate HTML
progress_store[task_id] = {"status": "processing", "message": "[3단계] HTML 생성 중...", "percent": 80}
html_filename = f"{original_name}_slide_{file_id}.html"
html_path = os.path.join(target_dir, html_filename)
await _generate_html_slide(filtered_layout_data, width, height, bg_path, html_path, font_family, codegen_model)
log_execution(original_name, vision_model, inpainting_model, codegen_model)
# Step 4: PPTX Generation
current_settings_local = load_settings()
output_fmt = current_settings_local.get("output_format", "both")
pptx_url = None
if output_fmt in ["pptx", "both"]:
progress_store[task_id]["message"] = "[완료 단계] PPTX 생성 중..."
pptx_filename = f"{original_name}_slide_{file_id}.pptx"
pptx_path = os.path.join(target_dir, pptx_filename)
if await _generate_pptx_slide(filtered_layout_data, bg_path, width, height, pptx_path, font_family):
pptx_url = f"/output/{batch_folder}/{pptx_filename}"
logger.info(f"PPTX generated: {pptx_path}")
# Complete
progress_store[task_id] = {
"status": "complete",
"message": "[완료] 모든 작업 처리가 끝났습니다.",
"percent": 100,
"data": {
"html_url": f"/output/{batch_folder}/{html_filename}",
"bg_url": f"/output/{batch_folder}/{bg_filename}",
"preview_url": f"/output/{batch_folder}/{html_filename}",
"pptx_url": pptx_url
}
}
except Exception as e:
logger.error(f"Processing error: {str(e)}")
progress_store[task_id] = {"status": "error", "message": str(e), "percent": 0}
def log_execution(filename, vision, inpaint, codegen):
try:
log_dir = os.path.join(BASE_DIR, "logs")
ensure_directory(log_dir)
log_file = os.path.join(log_dir, "execution_log.txt")
timestamp = datetime.now().isoformat()
log_entry = f"[{timestamp}] File: {filename} | Vision: {vision} | Inpaint: {inpaint} | CodeGen: {codegen}\n"
with open(log_file, "a", encoding="utf-8") as f:
f.write(log_entry)
logger.info(f"Execution logged to {log_file}")
except Exception as e:
logger.error(f"Failed to write execution log: {e}")
def log_photoroom_execution(filename, mode):
try:
log_dir = os.path.join(BASE_DIR, "logs")
ensure_directory(log_dir)
log_file = os.path.join(log_dir, "execution_log.txt")
timestamp = datetime.now().isoformat()
log_entry = f"[{timestamp}] [Photoroom] File: {filename} | Mode: {mode}\n"
with open(log_file, "a", encoding="utf-8") as f:
f.write(log_entry)
logger.info(f"Photoroom execution logged to {log_file}")
except Exception as e:
logger.error(f"Failed to write Photoroom execution log: {e}")
@app.post("/remove-text")
async def remove_text(
file: UploadFile = File(...),
vision_model: str = Form("gemini-3-flash-preview"),
inpainting_model: str = Form("opencv-telea"),
batch_folder: str = Form("single")
):
try:
timestamp = generate_timestamp()
original_name = os.path.splitext(file.filename)[0]
ext = os.path.splitext(file.filename)[1]
input_filename = f"{original_name}_{timestamp}{ext}"
# Save to Output Dir directly
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
ensure_directory(target_dir)
input_path = os.path.join(target_dir, input_filename)
with open(input_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# 1. Analyze
# Pass exclude_text to analyzer
# FORCE NEW METHOD CALL
import sys
if 'src.analyzer' in sys.modules:
logger.info(f"DEBUG: Analyzer loaded from {sys.modules['src.analyzer'].__file__}")
analyzer.model_name = vision_model # Keep this line as it sets the model for the analyzer instance
layout_data, width, height = analyzer.analyze_image_v2(input_path, exclude_text) # Changed to analyze_image_v2 and passed exclude_text
# target_dir already defined above
bg_filename = f"{original_name}_bg_only_{timestamp}.png"
bg_path = os.path.join(target_dir, bg_filename)
image_processor.create_clean_background(input_path, layout_data, bg_path)
return JSONResponse({
"status": "success",
"data": {
"bg_url": f"/output/{batch_folder}/{bg_filename}"
}
})
except Exception as e:
logger.error(f"Remove Text Error: {e}")
return JSONResponse(status_code=500, content={"message": str(e)})
@app.post("/remove-text-ai")
async def remove_text_ai(
file: UploadFile = File(...),
vision_model: str = Form("gemini-3-flash-preview"), # Use 3.0 flash preview
batch_folder: str = Form("single")
):
try:
timestamp = generate_timestamp()
original_name = os.path.splitext(file.filename)[0]
ext = os.path.splitext(file.filename)[1]
input_filename = f"{original_name}_{timestamp}{ext}"
# Save to Output Dir
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
ensure_directory(target_dir)
input_path = os.path.join(target_dir, input_filename)
with open(input_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Use simple client to ask for clean text (No layout needed theoretically but we use analyzer for now? No, direct prompt)
# But wait, original code likely used analyzer or direct call. I should keep original logic but update path.
# Original code used `process_remove_text_ai` or similar. Let's check context.
# Assuming removing text uses analyzer.
analyzer.model_name = vision_model
# ... (rest of logic) ...
# logic below depends on input_path.
# Just update path setup above.
pass
# The surrounding code is not fully visible so I will substitute blindly but carefully.
# Wait, the tool requires EXACT match. I can't guess.
# I only viewed up to line 400. `remove_text_ai` starts at 391.
# I need to see more lines to safely replace `remove_text_ai`.
# I will skip `remove_text_ai` for now and do it in next step after viewing.
# Call Gemini for Text Removal
from google.genai import types
from PIL import Image
import io
# Configure client with API key from environment
client = analyzer.client
# Load image for Gemini
image = Image.open(input_path)
# Prompt for text removal
prompt = "Remove all text from this image completely. Fill the text areas with matching background seamlessly. Keep everything else identical."
# Use the model selected by user
model_to_use = vision_model
# User insists on 2.5 flash working.
# Ensure we request IMAGE modality explicitly as it helped in the test script.
response = client.models.generate_content(
model=model_to_use,
contents=[prompt, image],
config=types.GenerateContentConfig(
response_modalities=["TEXT", "IMAGE"]
)
)
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
ensure_directory(target_dir)
output_bg_filename = f"{original_name}_bg_ai_{timestamp}.png"
output_bg_path = os.path.join(target_dir, output_bg_filename)
image_saved = False
# Official sample style response handling
# Note: response.parts is a property that iterates over candidates[0].content.parts
if response.parts:
for part in response.parts:
if part.inline_data:
# Use SDK helper if available, otherwise manual
if hasattr(part, 'as_image'):
output_img = part.as_image()
else:
img_data = part.inline_data.data
output_img = Image.open(io.BytesIO(img_data))
output_img.save(output_bg_path)
image_saved = True
break
if not image_saved:
# Check for text in response similar to sample
text_content = ""
if response.parts:
for part in response.parts:
if part.text:
text_content += part.text
raise Exception(f"Gemini returned text instead of image: {text_content}")
return JSONResponse({
"status": "success",
"data": {
"bg_url": f"/output/{batch_folder}/{output_bg_filename}"
}
})
except Exception as e:
logger.error(f"Remove Text AI Error: {e}")
return JSONResponse(status_code=500, content={"message": str(e)})
@app.post("/generate-pptx-batch/{batch_folder}")
async def generate_pptx_batch(batch_folder: str):
try:
target_dir = validate_safe_path(OUTPUT_DIR, batch_folder)
if not os.path.exists(target_dir):
return JSONResponse(status_code=404, content={"message": "Batch folder not found"})
# Find all JSON layout files
all_json_files = [f for f in os.listdir(target_dir) if f.endswith(".json") and "_layout_" in f]
if not all_json_files:
return JSONResponse(status_code=400, content={"message": "No processed slides found in this batch"})
# Intelligent Filtering: Prefer _filtered.json over raw .json
filtered_files = {f for f in all_json_files if "_filtered.json" in f}
json_files = []
# Add all filtered files
json_files.extend(list(filtered_files))
# Add raw files ONLY if their filtered counterpart is missing
# Raw file: "name_layout_id.json" -> Expected filtered: "name_layout_id_filtered.json"
for f in all_json_files:
if "_filtered.json" in f:
continue # Already added
# Construct expected filtered name
expected_filtered = f.replace(".json", "_filtered.json")
if expected_filtered not in filtered_files:
json_files.append(f)
# Sort files to ensure order (optional, by timestamp usually)
json_files.sort()
# Create PPTX
pptx_gen = PPTXGenerator()
slides_added = 0
for json_file in json_files:
# Parse IDs to find matching BG
# Format: {original}_{timestamp}_layout_{id}.json
# We need to load JSON to be sure about the image size or deduce it.
# actually app.py saved metadata: layout_data = ...
# and logic: bg_filename = f"{original_name}_bg_{file_id}.png"
# Helper to find matching bg file
json_path = os.path.join(target_dir, json_file)
try:
with open(json_path, "r", encoding="utf-8") as f:
layout_data = json.load(f)
except Exception as e:
logger.warning(f"Skipping bad JSON {json_file}: {e}")
continue
# Need width/height.
# In process_slide_task, we saved the JSON. Currently JSON doesn't strictly have width/height in root.
# But convert_to_pixels put 'bbox_px' which is absolute.
# Refine_layout returns list of items.
# Missing: Original Image Dimensions.
# Workaround: Open the BG image to get dimensions.
# Infer BG Filename
# Naming convention: {original_name}_layout_{file_id}.json (or ..._filtered.json)
# BG convention: {original_name}_bg_{file_id}.png
# Fix: If json_file has _filtered.json, strip it first to find the raw BG image name
raw_json_name = json_file.replace("_filtered.json", ".json")
base_part = raw_json_name.replace("_layout_", "_bg_").replace(".json", ".png")
bg_path = os.path.join(target_dir, base_part)
if not os.path.exists(bg_path):
# Try fallback or loose search?
# Let's try to match by file_id if strict replacement fails
parts = json_file.split('_layout_')
if len(parts) == 2:
prefix = parts[0]
suffix = parts[1].replace('.json', '.png')
bg_path_candidate = os.path.join(target_dir, f"{prefix}_bg_{suffix}")
if os.path.exists(bg_path_candidate):
bg_path = bg_path_candidate
else:
logger.warning(f"BG image not found for {json_file}")
continue
else:
continue
# Get dimensions from BG image
from PIL import Image
with Image.open(bg_path) as img:
w, h = img.size
pptx_gen.add_slide(layout_data, bg_path, w, h)
slides_added += 1
if slides_added == 0:
return JSONResponse(status_code=400, content={"message": "Could not create any slides (missing backgrounds?)"})
# 깔끔한 파일명 생성 (사용자 요청 반영)
timestamp_clean = datetime.now().strftime("%Y%m%d_%H%M%S")
pptx_filename = f"PDF_AI_변환_결과_{timestamp_clean}.pptx"
output_pptx_path = os.path.join(target_dir, pptx_filename)
pptx_gen.save(output_pptx_path)
return JSONResponse({
"status": "success",
"download_url": f"/output/{batch_folder}/{pptx_filename}",
"filename": pptx_filename
})
except Exception as e:
logger.error(f"Generate PPTX Batch Error: {e}")
return JSONResponse(status_code=500, content={"message": str(e)})
@app.post("/save-pdf-images")
async def save_pdf_images(images: list[UploadFile] = File(...)):
"""
Client sends multiple image files.
Server saves them to output/pdftoimage_{yyyymmdd}_{hhmmss}/
"""
try:
if not images:
return JSONResponse(status_code=400, content={'status': 'error', 'message': 'No files received'})
# Create timestamped folder
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
folder_name = f"pdftoimage_{timestamp}"
save_path = os.path.join("output", folder_name)