-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathshellter_gradio.py
More file actions
3267 lines (2844 loc) ยท 146 KB
/
shellter_gradio.py
File metadata and controls
3267 lines (2844 loc) ยท 146 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 gradio as gr
import os
import json
import csv
import mimetypes
import requests
import re
import base64
import subprocess
import tempfile
from pathlib import Path
from dotenv import load_dotenv
import io
from PIL import Image, ImageDraw, ImageFont
import textwrap
from datetime import datetime
from tqdm import tqdm
from langchain_upstage import (
UpstageDocumentParseLoader,
UpstageEmbeddings,
ChatUpstage,
UpstageGroundednessCheck,
)
from operator import itemgetter
from langchain_community.vectorstores import Chroma
from langchain_core.documents import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.runnables import RunnableLambda
from langchain_core.output_parsers import StrOutputParser
# Groundedness ์ฒดํฌ์ฉ ์ปจํ
์คํธ ์ง๋ ฌํ ์ ํธ
def docs_to_text(docs):
try:
return "\n\n---\n\n".join(getattr(d, "page_content", str(d)) for d in docs)
except Exception:
return str(docs)
# Groundedness ์ปจํ
์คํธ ๋น๋: ๊ฒ์ ์ปจํ
์คํธ + ๊ณ์ฝ/์ง๋ฌธ ์๋ฌธ ๊ฒฐํฉ
def build_grounded_context_for_contract(contract_text: str) -> str:
try:
retrieved = RETRIEVER.invoke(contract_text) if RETRIEVER else []
except Exception:
retrieved = []
retrieved_text = docs_to_text(retrieved)
return f"[์ฐธ๊ณ ์๋ฃ]\n{retrieved_text}\n\n[๊ณ์ฝ์]\n{contract_text}"
def build_grounded_context_for_question(question_text: str) -> str:
try:
retrieved = RETRIEVER.invoke(question_text) if RETRIEVER else []
except Exception:
retrieved = []
retrieved_text = docs_to_text(retrieved)
return f"[์ฐธ๊ณ ์๋ฃ]\n{retrieved_text}\n\n[์ง๋ฌธ]\n{question_text}"
# ์ ํ ์์กด์ฑ (HTML -> PNG ๋ณํ์ฉ)
HTML2IMAGE_AVAILABLE = False
try:
from html2image import Html2Image
HTML2IMAGE_AVAILABLE = True
except Exception:
HTML2IMAGE_AVAILABLE = False
# ์ ํ ์์กด์ฑ (Markdown -> HTML ๋ณํ) - FIXED
MARKDOWN_AVAILABLE = False
try:
import markdown2
MARKDOWN_AVAILABLE = True
except Exception:
try:
import markdown
MARKDOWN_AVAILABLE = True
except Exception:
MARKDOWN_AVAILABLE = False
# ํ๊ฒฝ ๋ณ์
try:
if load_dotenv():
print("๐ API ํค๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ๋ถ๋ฌ์์ต๋๋ค.")
DEEPL_API_KEY = os.getenv("DEEPL_API_KEY")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
UPSTAGE_API_KEY = os.getenv("UPSTAGE_API_KEY")
except:
DEEPL_API_KEY = None
GOOGLE_API_KEY = None
UPSTAGE_API_KEY = None
# API ์๋ํฌ์ธํธ
TTS_API_URL = f"https://texttospeech.googleapis.com/v1/text:synthesize?key={GOOGLE_API_KEY}" if GOOGLE_API_KEY else None
STT_API_URL = f"https://speech.googleapis.com/v1/speech:recognize?key={GOOGLE_API_KEY}" if GOOGLE_API_KEY else None
DEEPL_API_URL = "https://api-free.deepl.com/v2/translate"
# ๋ฐ์ดํฐ ๊ฒฝ๋ก ์ค์
EASYLAW_QA_PATH = "./data/easylaw_qa_data.json"
SPECIAL_CLAUSES_PATH = "./data/ํน์ฝ๋ฌธ๊ตฌ ํฉ๋ณธ_utf8bom.csv"
LAW_PARSED_PATH = "./data/์ฃผํ์๋์ฐจ๋ณดํธ๋ฒ(๋ฒ๋ฅ )(์ 19356ํธ)_parsed.json"
DEFAULTER_LIST_PATH = "./data/์์ต์ฑ๋ฌด๋ถ์ดํ์.CSV"
CHROMA_DB_PATH = "./chroma_db_real_estate_gradio"
# ๋ค๊ตญ์ด ํฐํธ ์๋ ๋ค์ด๋ก๋ ๋ก์ง, TTF๋ง์ผ๋ก ์ ํํ ๋งํฌ๋ก ์์ ์งํ.
FONTS_DIR = Path("./fonts")
FONT_URLS = {
# Noto Sans (๋ผํด/ํค๋ฆด/๊ธฐ๋ณธ์๋ฌธ)
"NotoSans-Regular.ttf": "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf",
"NotoSans-Bold.ttf": "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Bold.ttf",
# Noto Sans KR (ํ๊ตญ์ด)
"NotoSansKR-Regular.ttf": "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/Korean/NotoSansCJKkr-Regular.otf",
"NotoSansKR-Bold.ttf": "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/Korean/NotoSansCJKkr-Bold.otf",
# Noto Sans JP (์ผ๋ณธ์ด) - TTF ํ์ผ๋ก ์์
"NotoSansJP-Regular.ttf": "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/Japanese/NotoSansCJKjp-Regular.otf",
"NotoSansJP-Bold.ttf": "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/Japanese/NotoSansCJKjp-Bold.otf",
# Noto Sans SC (์ค๊ตญ์ด ๊ฐ์ฒด) - TTF ํ์ผ๋ก ์์
"NotoSansSC-Regular.ttf": "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf",
"NotoSansSC-Bold.ttf": "https://github.com/googlefonts/noto-cjk/raw/main/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Bold.otf",
# Noto Color Emoji (์ด๋ชจ์ง ์ง์) - ์ฃผ ์ด๋ชจ์ง ํฐํธ
"NotoColorEmoji-Regular.ttf": "https://github.com/googlefonts/noto-emoji/raw/main/fonts/NotoColorEmoji.ttf",
# ์ถ๊ฐ ์ด๋ชจ์ง ํฐํธ (๋ฐฑ์
์ฉ)
"NotoColorEmoji.ttf": "https://github.com/googlefonts/noto-emoji/raw/main/fonts/NotoColorEmoji.ttf",
# Twemoji (Twitter ์ด๋ชจ์ง - SVG ๊ธฐ๋ฐ, ๊ฐ๋ฒผ์)
"TwitterColorEmoji.ttf": "https://github.com/twitter/twemoji/releases/download/v14.0.2/TwitterColorEmoji-SVGinOT.ttf",
# Noto Sans (์ฐํฌ๋ผ์ด๋์ด ํค๋ฆด ๋ฌธ์ ์ง์) - ์ถ๊ฐ
"NotoSans-{style}.ttf": "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf"
}
def setup_fonts():
"""
ํ์ํ ๋ค๊ตญ์ด ํฐํธ๋ฅผ ./fonts ํด๋์ ์๋์ผ๋ก ๋ค์ด๋ก๋ํ๊ณ , OTF ํ์ผ์ TTF๋ก ๋ณํํฉ๋๋ค.
"""
print("๐๏ธ ๋ค๊ตญ์ด ํฐํธ ์ค์ ์ ์์ํฉ๋๋ค...")
FONTS_DIR.mkdir(exist_ok=True)
for font_name, url in FONT_URLS.items():
font_path = FONTS_DIR / font_name
if font_path.exists():
print(f" - '{font_name}' ํฐํธ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค. (๊ฑด๋๋ฐ๊ธฐ)")
continue
try:
print(f" - '{font_name}' ํฐํธ ๋ค์ด๋ก๋ ์ค... ({url})")
response = requests.get(url, stream=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
block_size = 1024
with open(font_path, 'wb') as f, tqdm(
total=total_size, unit='iB', unit_scale=True, desc=f" {font_name}"
) as pbar:
for data in response.iter_content(block_size):
pbar.update(len(data))
f.write(data)
if total_size != 0 and pbar.n != total_size:
raise Exception("๋ค์ด๋ก๋ ์ค ์ค๋ฅ ๋ฐ์")
print(f" ๐ '{font_name}' ํฐํธ ๋ค์ด๋ก๋ ์๋ฃ!")
except Exception as e:
print(f" โ '{font_name}' ํฐํธ ๋ค์ด๋ก๋ ์คํจ: {e}")
if font_path.exists():
# ํ์ผ ํฌ๊ธฐ ํ์ธ ํ ์ญ์ ์ฌ๋ถ ๊ฒฐ์
try:
file_size = font_path.stat().st_size
if file_size < 10240: # 10KB ๋ฏธ๋ง์ด๋ฉด ๋ถ์์ ํ ํ์ผ๋ก ๊ฐ์ฃผ
font_path.unlink()
print(f" - ๋ถ์์ ํ ํ์ผ ์ญ์ ๋จ ({file_size} bytes)")
else:
print(f" - ๋ถ๋ถ ๋ค์ด๋ก๋ ํ์ผ ์ ์ง๋จ ({file_size} bytes)")
except Exception as cleanup_error:
print(f" - ํ์ผ ์ ๋ฆฌ ์ค ์ค๋ฅ: {cleanup_error}")
try:
font_path.unlink()
except:
pass
# OTF ํ์ผ์ TTF๋ก ๋ณํ ์๋
print(" - OTF ํ์ผ์ TTF๋ก ๋ณํ ์๋ ์ค...")
try:
from fontTools.ttLib import TTFont
from fontTools.ttx import makeOutputFileName
for font_name in FONT_URLS.keys():
if font_name.endswith('.otf'):
otf_path = FONTS_DIR / font_name
ttf_name = font_name.replace('.otf', '.ttf')
ttf_path = FONTS_DIR / ttf_name
if otf_path.exists() and not ttf_path.exists():
try:
print(f" - '{font_name}' โ '{ttf_name}' ๋ณํ ์ค...")
font = TTFont(str(otf_path))
font.save(str(ttf_path))
print(f" - '{ttf_name}' ๋ณํ ์๋ฃ!")
except Exception as e:
print(f" - '{font_name}' ๋ณํ ์คํจ: {e}")
except ImportError:
print(" - fontTools๊ฐ ์ค์น๋์ง ์์ OTFโTTF ๋ณํ์ ๊ฑด๋๋๋๋ค.")
print(" - pip install fonttools๋ก ์ค์น ๊ฐ๋ฅํฉ๋๋ค.")
print("โ
๋ชจ๋ ํฐํธ ์ค์ ์ด ์๋ฃ๋์์ต๋๋ค.")
def build_ai_brain_if_needed():
"""AI์ ์ง์ ๋ฒ ์ด์ค(Vector DB)๋ฅผ ๊ตฌ์ถํฉ๋๋ค. ์ด๋ฏธ ์กด์ฌํ๋ฉด ๊ฑด๋๋๋๋ค."""
if os.path.exists(CHROMA_DB_PATH):
print(f"โ
Vector DB๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค. ({CHROMA_DB_PATH})")
return
print(f"โจ AI์ ์ง์ ๋ฒ ์ด์ค(Vector DB)๋ฅผ ์๋ก ๊ตฌ์ถํฉ๋๋ค...")
all_documents = []
# EasyLaw Q&A ๋ฐ์ดํฐ ๋ก๋
try:
with open(EASYLAW_QA_PATH, 'r', encoding='utf-8') as f:
for item in json.load(f):
all_documents.append(Document(
page_content=f"์ฌ๋ก ์ง๋ฌธ: {item['question']}\n์ฌ๋ก ๋ต๋ณ: {item['answer']}",
metadata={"source": "easylaw_qa"}
))
print(f" - EasyLaw QA ๋ฐ์ดํฐ ๋ก๋ ์๋ฃ ({len(all_documents)}๊ฐ ๋ฌธ์)")
except FileNotFoundError:
print(f" [๊ฒฝ๊ณ ] '{EASYLAW_QA_PATH}' ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค.")
# ๋ฒ๋ฅ ์กฐ๋ฌธ ๋ฐ์ดํฐ ๋ก๋
try:
with open(LAW_PARSED_PATH, 'r', encoding='utf-8') as f:
law_text = json.load(f).get("text", "")
all_documents.append(Document(
page_content=law_text,
metadata={"source": "housing_lease_law"}
))
print(f" - ์ฃผํ์๋์ฐจ๋ณดํธ๋ฒ ๋ฐ์ดํฐ ๋ก๋ ์๋ฃ")
except FileNotFoundError:
print(f" [๊ฒฝ๊ณ ] '{LAW_PARSED_PATH}' ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค.")
# ํน์ฝ ์กฐํญ ๋ฐ์ดํฐ ๋ก๋
try:
clauses_count = 0
with open(SPECIAL_CLAUSES_PATH, 'r', encoding='utf-8-sig') as f:
for row in csv.DictReader(f):
if clause_content := row.get('ํน์ฝ๋ด์ฉ', '').strip():
all_documents.append(Document(
page_content=f"๊ถ์ฅ ํน์ฝ ์กฐํญ ์์: {clause_content}",
metadata={"source": "special_clauses"}
))
clauses_count += 1
print(f" - ํน์ฝ ์กฐํญ ๋ฐ์ดํฐ ๋ก๋ ์๋ฃ ({clauses_count}๊ฐ)")
except FileNotFoundError:
print(f" [๊ฒฝ๊ณ ] '{SPECIAL_CLAUSES_PATH}' ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค.")
if not all_documents:
print("๐ด DB๋ฅผ ๊ตฌ์ถํ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค. RAG ๊ธฐ๋ฅ์ด ์ ์ ๋์ํ์ง ์์ ์ ์์ต๋๋ค.")
return
print(" - ํ
์คํธ ๋ถํ ๋ฐ ์๋ฒ ๋ฉ ์งํ ์ค... (์๊ฐ์ด ๊ฑธ๋ฆด ์ ์์ต๋๋ค)")
split_docs = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100).split_documents(all_documents)
Chroma.from_documents(
documents=split_docs,
embedding=UpstageEmbeddings(model="solar-embedding-1-large"),
persist_directory=CHROMA_DB_PATH
)
print(f"๐ Vector DB ๊ตฌ์ถ ์๋ฃ! ({CHROMA_DB_PATH})")
# ### MODIFIED FUNCTION ###: ๋ก์ปฌ์ ๋ค์ด๋ก๋๋ ํฐํธ๋ฅผ ์ง์ ์ฌ์ฉํ๋ ๋ฐฉ์์ผ๋ก ๋ณ๊ฒฝ
def get_multilingual_font(size=16, bold=False, lang_code='KO'):
"""
๋ก์ปฌ ./fonts ํด๋์ ๋ค์ด๋ก๋๋ Noto ํฐํธ๋ฅผ ์ฌ์ฉํ์ฌ ๋ค๊ตญ์ด ํ
์คํธ ๋ ๋๋ง์ ์ง์ํฉ๋๋ค.
์ธ์ด ์ฝ๋์ ๋ฐ๋ผ ์ ์ ํ ํฐํธ ํ์ผ์ ์ ํํ์ฌ tofu ํ์์ ๋ฐฉ์งํฉ๋๋ค.
ํฝ์
ํฌ๊ธฐ ์์ ์ฑ์ ๊ฐํํ์ต๋๋ค.
"""
# ์์ ํ ํฝ์
ํฌ๊ธฐ ๋ฒ์ ์ ์ฉ (8-72)
safe_size = max(8, min(72, size))
style = "Bold" if bold else "Regular"
# ์ธ์ด ์ฝ๋์ ๋ฐ๋ฅธ ํฐํธ ํ์ผ ๋งคํ (TTF ์ฐ์ , OTF ํด๋ฐฑ)
font_map = {
'KO': [f'NotoSansKR-{style}.ttf', f'NotoSansKR-{style}.otf'],
'JA': [f'NotoSansJP-{style}.ttf', f'NotoSansJP-{style}.otf'],
'ZH': [f'NotoSansSC-{style}.ttf', f'NotoSansSC-{style}.otf'],
# ์ฐํฌ๋ผ์ด๋์ด(ํค๋ฆด) - ํค๋ฆด ๋ฌธ์ ์ง์ ํฐํธ ์ถ๊ฐ
'UK': [f'NotoSans-{style}.ttf', f'NotoSansKR-{style}.ttf', f'NotoSansKR-{style}.otf'],
'VI': [f'NotoSans-{style}.ttf'],
'EN': [f'NotoSans-{style}.ttf'],
}
# ์์ฒญ๋ ์ธ์ด์ ํฐํธ ํ์ผ๋ช
๊ฐ์ ธ์ค๊ธฐ, ์์ผ๋ฉด ๊ธฐ๋ณธ NotoSans ์ฌ์ฉ
font_candidates = font_map.get(lang_code.upper(), [f'NotoSans-{style}.ttf'])
# TTF ํ์ผ์ ์ฐ์ ์ ์ผ๋ก ์ฐพ๊ธฐ
for font_filename in font_candidates:
font_path = FONTS_DIR / font_filename
if font_path.exists():
try:
return ImageFont.truetype(str(font_path), safe_size)
except (OSError, IOError) as e:
if "invalid pixel size" in str(e).lower():
print(f"โ ๏ธ ํฐํธ '{font_filename}' ํฝ์
ํฌ๊ธฐ ์ค๋ฅ, ๊ธฐ๋ณธ ํฌ๊ธฐ๋ก ์ฌ์๋: {e}")
try:
return ImageFont.truetype(str(font_path), 16)
except Exception as e2:
print(f"โ ๏ธ ํฐํธ '{font_filename}' ๊ธฐ๋ณธ ํฌ๊ธฐ ๋ก๋๋ ์คํจ: {e2}")
continue
else:
print(f"โ ๏ธ ํฐํธ ๋ก๋ ์คํจ '{font_filename}': {e}")
continue
except Exception as e:
print(f"โ ๏ธ ํฐํธ ๋ก๋ ์ค ์ ์ ์๋ ์ค๋ฅ '{font_filename}': {e}")
continue
# ๋ชจ๋ ํ๋ณด ํฐํธ๊ฐ ์คํจํ ๊ฒฝ์ฐ ํด๋ฐฑ ์๋
fallback_candidates = [
FONTS_DIR / "NotoSans-Regular.ttf",
FONTS_DIR / "NotoSans-Regular.otf"
]
for fallback_path in fallback_candidates:
if fallback_path.exists():
try:
print(f"โ ๏ธ ๊ฒฝ๊ณ : ์์ฒญ๋ ํฐํธ๋ฅผ ์ฐพ์ ์ ์์ด '{fallback_path.name}'๋ก ๋์ฒดํฉ๋๋ค.")
return ImageFont.truetype(str(fallback_path), safe_size)
except (OSError, IOError) as e:
if "invalid pixel size" in str(e).lower():
print(f"โ ๏ธ ํด๋ฐฑ ํฐํธ '{fallback_path.name}' ํฝ์
ํฌ๊ธฐ ์ค๋ฅ, ๊ธฐ๋ณธ ํฌ๊ธฐ๋ก ์ฌ์๋: {e}")
try:
return ImageFont.truetype(str(fallback_path), 16)
except Exception as e2:
print(f"โ ๏ธ ํด๋ฐฑ ํฐํธ '{fallback_path.name}' ๊ธฐ๋ณธ ํฌ๊ธฐ ๋ก๋๋ ์คํจ: {e2}")
continue
else:
print(f"โ ๏ธ ํด๋ฐฑ ํฐํธ ๋ก๋ ์คํจ '{fallback_path.name}': {e}")
continue
except Exception as e:
print(f"โ ๏ธ ํด๋ฐฑ ํฐํธ ๋ก๋ ์ค ์ ์ ์๋ ์ค๋ฅ '{fallback_path.name}': {e}")
continue
# ์ตํ์ ์๋จ - ์์คํ
๊ธฐ๋ณธ ํฐํธ
print("โ ๋ชจ๋ ํฐํธ ๋ก๋ ์คํจ. PIL ๊ธฐ๋ณธ ํฐํธ๋ฅผ ์ฌ์ฉํฉ๋๋ค. ๊ธ์๊ฐ ๊นจ์ง ์ ์์ต๋๋ค.")
try:
return ImageFont.load_default()
except Exception as e:
print(f"โ ๊ธฐ๋ณธ ํฐํธ ๋ก๋๋ ์คํจ: {e}")
return None
def get_system_emoji_fonts():
"""์์คํ
์์ ์ด๋ชจ์ง ํฐํธ ๊ฒฝ๋ก๋ฅผ ์ฐพ์ต๋๋ค."""
system_emoji_fonts = []
# Windows ์์คํ
ํฐํธ ๊ฒฝ๋ก
windows_fonts = [
Path("C:/Windows/Fonts/seguiemj.ttf"),
Path("C:/Windows/Fonts/NotoColorEmoji.ttf"),
Path("C:/Windows/Fonts/seguisym.ttf"),
]
# macOS ์์คํ
ํฐํธ ๊ฒฝ๋ก
macos_fonts = [
Path("/System/Library/Fonts/Apple Color Emoji.ttc"),
Path("/Library/Fonts/Apple Color Emoji.ttc"),
Path("/System/Library/Fonts/NotoColorEmoji.ttf"),
]
# Linux ์์คํ
ํฐํธ ๊ฒฝ๋ก
linux_fonts = [
Path("/usr/share/fonts/truetype/noto-color-emoji/NotoColorEmoji.ttf"),
Path("/usr/share/fonts/TTF/NotoColorEmoji.ttf"),
Path("/usr/local/share/fonts/NotoColorEmoji.ttf"),
]
for font_path in windows_fonts + macos_fonts + linux_fonts:
if font_path.exists():
system_emoji_fonts.append(font_path)
return system_emoji_fonts
def get_emoji_font(size=16):
"""
์ด๋ชจ์ง ์ ์ฉ ํฐํธ๋ฅผ ๋ก๋ํฉ๋๋ค.
๋ค์ํ ํฐํธ ํ์ผ๊ณผ ํฌ๊ธฐ ์ต์
์ ์๋ํ์ฌ robustํ๊ฒ ์ฒ๋ฆฌํฉ๋๋ค.
"""
# ์์ ํ ํฝ์
ํฌ๊ธฐ ๋ฒ์ ์ ์ฉ (8-72)
safe_size = max(8, min(72, size))
# ์ด๋ชจ์ง ํฐํธ ํ๋ณด๋ค (์ฐ์ ์์ ์)
emoji_font_candidates = [
FONTS_DIR / "NotoColorEmoji-Regular.ttf",
FONTS_DIR / "NotoColorEmoji.ttf",
FONTS_DIR / "AppleColorEmoji.ttc", # macOS ์์คํ
ํฐํธ
FONTS_DIR / "seguiemj.ttf", # Windows ์์คํ
ํฐํธ
FONTS_DIR / "TwitterColorEmoji.ttf", # ๋์ฒด ์ด๋ชจ์ง ํฐํธ
]
# ์์คํ
์ด๋ชจ์ง ํฐํธ๋ ์ถ๊ฐ
emoji_font_candidates.extend(get_system_emoji_fonts())
# ์ฌ๋ฌ ํฌ๊ธฐ ์ต์
์๋ (ํฝ์
ํฌ๊ธฐ ๋ฌธ์ ํด๊ฒฐ)
size_options = [safe_size, 16, 14, 12, 18, 20, 24]
for font_path in emoji_font_candidates:
if font_path.exists():
# ํฐํธ ํ์ผ ๊ธฐ๋ณธ ๊ฒ์ฆ
try:
file_size = font_path.stat().st_size
if file_size < 1024: # 1KB ๋ฏธ๋ง์ด๋ฉด ์์๋ ํ์ผ์ผ ๊ฐ๋ฅ์ฑ
print(f"โ ๏ธ ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ํ์ผ ํฌ๊ธฐ๊ฐ ๋๋ฌด ์์ ({file_size} bytes) - ๊ฑด๋๋")
continue
except Exception as e:
print(f"โ ๏ธ ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ํ์ผ ์ํ ํ์ธ ์คํจ: {e}")
continue
for try_size in size_options:
try:
font = ImageFont.truetype(str(font_path), try_size)
# ํฐํธ ๋ก๋ ํ ๊ฐ๋จํ ๊ฒ์ฆ (์ด๋ชจ์ง ๋ ๋๋ง ํ
์คํธ)
try:
# ๊ฐ๋จํ ํ
์คํธ๋ก ํฐํธ ๊ธฐ๋ฅ ํ
์คํธ
test_img = Image.new('RGB', (50, 50), 'white')
test_draw = ImageDraw.Draw(test_img)
test_draw.text((10, 10), "๐", font=font, fill='black')
if try_size != safe_size:
print(f"๐ก ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ํฌ๊ธฐ {safe_size}โ{try_size}๋ก ์กฐ์ ํ์ฌ ๋ก๋ ์ฑ๊ณต")
else:
print(f"โ
์ด๋ชจ์ง ํฐํธ '{font_path.name}' ๋ก๋ ์ฑ๊ณต (ํฌ๊ธฐ: {try_size})")
return font
except Exception as test_e:
print(f"โ ๏ธ ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ๋ ๋๋ง ํ
์คํธ ์คํจ: {test_e}")
# ๋ ๋๋ง ํ
์คํธ ์คํจํด๋ ํฐํธ๋ ๋ฐํ (์ผ๋ถ ๊ธฐ๋ฅ๋ง ์ ํ๋ ์ ์์)
return font
except (OSError, IOError) as e:
if "invalid pixel size" in str(e).lower():
# ๋ค์ ํฌ๊ธฐ๋ก ์๋
continue
elif "cannot load font" in str(e).lower():
print(f"โ ๏ธ ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ์์๋จ - ๋ค๋ฅธ ํฐํธ๋ก ์๋")
break # ๋ค๋ฅธ ํฐํธ๋ก ์๋
else:
print(f"โ ๏ธ ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ํฌ๊ธฐ {try_size} ๋ก๋ ์คํจ: {e}")
break # ๋ค๋ฅธ ํฐํธ๋ก ์๋
except Exception as e:
print(f"โ ๏ธ ์ด๋ชจ์ง ํฐํธ '{font_path.name}' ํฌ๊ธฐ {try_size} ๋ก๋ ์ค ์ค๋ฅ: {e}")
break # ๋ค๋ฅธ ํฐํธ๋ก ์๋
# ๋ชจ๋ ์ด๋ชจ์ง ํฐํธ ์คํจ ์ ์ผ๋ฐ ๋ค๊ตญ์ด ํฐํธ๋ก ๋์ฒด
print("โ ๏ธ ๋ชจ๋ ์ด๋ชจ์ง ํฐํธ ๋ก๋ ์คํจ. ์ผ๋ฐ ํฐํธ๋ก ๋์ฒดํฉ๋๋ค.")
fallback_fonts = [
FONTS_DIR / "NotoSans-Regular.ttf",
FONTS_DIR / "NotoSansKR-Regular.ttf",
FONTS_DIR / "NotoSansKR-Regular.otf"
]
for fallback_path in fallback_fonts:
if fallback_path.exists():
for try_size in [14, 12, 16, 18]: # ๋ ๋ณด์์ ์ธ ํฌ๊ธฐ๋ค
try:
font = ImageFont.truetype(str(fallback_path), try_size)
print(f"๐ก ์ด๋ชจ์ง ๋์ฒด ํฐํธ '{fallback_path.name}' ๋ก๋ ์ฑ๊ณต (ํฌ๊ธฐ: {try_size})")
return font
except:
continue
# ์ตํ์ ์๋จ - PIL ๊ธฐ๋ณธ ํฐํธ
print("โ ๏ธ ๋ชจ๋ ํฐํธ ๋ก๋ ์คํจ. PIL ๊ธฐ๋ณธ ํฐํธ๋ฅผ ์ฌ์ฉํฉ๋๋ค.")
try:
return ImageFont.load_default()
except Exception as e:
print(f"โ ๊ธฐ๋ณธ ํฐํธ ๋ก๋๋ ์คํจ: {e}")
return None
def draw_text_with_emoji(draw, text, position, main_font, emoji_font, align='left', color='#000000'):
"""
์ด๋ชจ์ง์ ์ผ๋ฐ ํ
์คํธ๋ฅผ ํผํฉํ์ฌ ๋ ๋๋งํฉ๋๋ค.
align: 'left', 'center', 'right'
์์ ์ฑ๊ณผ ํธํ์ฑ์ ๊ฐํํ์ต๋๋ค.
"""
if not emoji_font or not main_font:
# ํฐํธ๊ฐ ์์ผ๋ฉด ๊ธฐ๋ณธ ์ฒ๋ฆฌ
safe_font = main_font or emoji_font
if not safe_font:
try:
safe_font = ImageFont.load_default()
except:
print("โ ํฐํธ ๋ก๋ ์คํจ๋ก ํ
์คํธ ๋ ๋๋ง์ ๊ฑด๋๋๋๋ค.")
return
try:
if align == 'center':
bbox = draw.textbbox((0, 0), text, font=safe_font)
x = position[0] - (bbox[2] - bbox[0]) // 2
draw.text((x, position[1]), text, fill=color, font=safe_font)
else:
draw.text(position, text, fill=color, font=safe_font)
except Exception as e:
print(f"โ ๏ธ ๊ธฐ๋ณธ ํ
์คํธ ๋ ๋๋ง ์คํจ: {e}")
return
# ์ด๋ชจ์ง์ ์ผ๋ฐ ํ
์คํธ๋ฅผ ๋ถ๋ฆฌ
import re
emoji_pattern = re.compile(r'[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF\U00002600-\U000027BF\U0001F900-\U0001F9FF\U0001F018-\U0001F270]')
# ์ด๋ชจ์ง ์์น ์ฐพ๊ธฐ
emoji_positions = []
try:
for match in emoji_pattern.finditer(text):
emoji_positions.append((match.start(), match.end(), match.group()))
except Exception as e:
print(f"โ ๏ธ ์ด๋ชจ์ง ํจํด ๊ฒ์ ์คํจ: {e}")
emoji_positions = []
if not emoji_positions:
# ์ด๋ชจ์ง๊ฐ ์์ผ๋ฉด ๊ธฐ๋ณธ ๋ ๋๋ง
try:
if align == 'center':
bbox = draw.textbbox((0, 0), text, font=main_font)
x = position[0] - (bbox[2] - bbox[0]) // 2
draw.text((x, position[1]), text, fill=color, font=main_font)
else:
draw.text(position, text, fill=color, font=main_font)
except Exception as e:
print(f"โ ๏ธ ์ผ๋ฐ ํ
์คํธ ๋ ๋๋ง ์คํจ: {e}")
return
# ํ
์คํธ๋ฅผ ์ด๋ชจ์ง์ ์ผ๋ฐ ํ
์คํธ๋ก ๋ถํ ํ์ฌ ๋ ๋๋ง
current_x = position[0]
if align == 'center':
# ์ ์ฒด ํ
์คํธ ๋๋น ๊ณ์ฐ
total_width = 0
last_end = 0
try:
for start, end, emoji in emoji_positions:
# ์ด๋ชจ์ง ์์ ์ผ๋ฐ ํ
์คํธ
if start > last_end:
text_part = text[last_end:start]
try:
bbox = draw.textbbox((0, 0), text_part, font=main_font)
total_width += bbox[2] - bbox[0]
except Exception as e:
print(f"โ ๏ธ ํ
์คํธ ๋๋น ๊ณ์ฐ ์คํจ: {e}")
# ๋๋ต์ ์ธ ๋๋น ์ถ์
total_width += len(text_part) * 10
# ์ด๋ชจ์ง
try:
bbox = draw.textbbox((0, 0), emoji, font=emoji_font)
total_width += bbox[2] - bbox[0]
except Exception as e:
print(f"โ ๏ธ ์ด๋ชจ์ง ๋๋น ๊ณ์ฐ ์คํจ: {e}")
# ์ด๋ชจ์ง ๊ธฐ๋ณธ ๋๋น ์ถ์
total_width += 20
last_end = end
# ๋ง์ง๋ง ์ผ๋ฐ ํ
์คํธ
if last_end < len(text):
text_part = text[last_end:]
try:
bbox = draw.textbbox((0, 0), text_part, font=main_font)
total_width += bbox[2] - bbox[0]
except Exception as e:
print(f"โ ๏ธ ๋ง์ง๋ง ํ
์คํธ ๋๋น ๊ณ์ฐ ์คํจ: {e}")
total_width += len(text_part) * 10
current_x = position[0] - total_width // 2
except Exception as e:
print(f"โ ๏ธ ์ค์ ์ ๋ ฌ ๋๋น ๊ณ์ฐ ์คํจ: {e}")
current_x = position[0] # ์ข์ธก ์ ๋ ฌ๋ก ํด๋ฐฑ
# ์ค์ ๋ ๋๋ง
last_end = 0
try:
for start, end, emoji in emoji_positions:
# ์ด๋ชจ์ง ์์ ์ผ๋ฐ ํ
์คํธ
if start > last_end:
text_part = text[last_end:start]
try:
draw.text((current_x, position[1]), text_part, fill=color, font=main_font)
bbox = draw.textbbox((0, 0), text_part, font=main_font)
current_x += bbox[2] - bbox[0]
except Exception as e:
print(f"โ ๏ธ ์ผ๋ฐ ํ
์คํธ ๋ ๋๋ง ์คํจ: {e}")
current_x += len(text_part) * 10 # ๋๋ต์ ์ธ ์ด๋
# ์ด๋ชจ์ง
try:
draw.text((current_x, position[1]), emoji, fill=color, font=emoji_font)
bbox = draw.textbbox((0, 0), emoji, font=emoji_font)
current_x += bbox[2] - bbox[0]
except Exception as e:
print(f"โ ๏ธ ์ด๋ชจ์ง '{emoji}' ๋ ๋๋ง ์คํจ: {e}")
# ์ด๋ชจ์ง ๋ ๋๋ง ์คํจ ์ ๋์ฒด ํ
์คํธ๋ก ์ฒ๋ฆฌ
try:
alt_text = f"[{emoji}]"
draw.text((current_x, position[1]), alt_text, fill=color, font=main_font)
bbox = draw.textbbox((0, 0), alt_text, font=main_font)
current_x += bbox[2] - bbox[0]
except Exception as e2:
print(f"โ ๏ธ ์ด๋ชจ์ง ๋์ฒด ํ
์คํธ ๋ ๋๋ง๋ ์คํจ: {e2}")
current_x += 20 # ๊ธฐ๋ณธ ์ด๋
last_end = end
# ๋ง์ง๋ง ์ผ๋ฐ ํ
์คํธ
if last_end < len(text):
text_part = text[last_end:]
try:
draw.text((current_x, position[1]), text_part, fill=color, font=main_font)
except Exception as e:
print(f"โ ๏ธ ๋ง์ง๋ง ํ
์คํธ ๋ ๋๋ง ์คํจ: {e}")
except Exception as e:
print(f"โ ๏ธ ํผํฉ ํ
์คํธ ๋ ๋๋ง ์ค ์ค๋ฅ: {e}")
# ์ ์ฒด ์คํจ ์ ๊ธฐ๋ณธ ํฐํธ๋ก ์ ์ฒด ํ
์คํธ ๋ ๋๋ง
try:
draw.text(position, text, fill=color, font=main_font)
except Exception as e2:
print(f"โ ๏ธ ํด๋ฐฑ ๋ ๋๋ง๋ ์คํจ: {e2}")
def extract_text_from_file(file_path: str) -> tuple[str, str]:
if not file_path or not os.path.exists(file_path):
return "", "ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค."
try:
# Upstage ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ์ด๋ฏธ์ง์ ๋ฌธ์๋ฅผ ์ฒ๋ฆฌํฉ๋๋ค. JPG๋ ์ฌ๊ธฐ์ ํฌํจ๋ฉ๋๋ค.
pages = UpstageDocumentParseLoader(file_path, ocr="force").load()
extracted_text = "\n\n".join([p.page_content for p in pages if p.page_content])
if not extracted_text.strip():
return "", "ํ์ผ์์ ํ
์คํธ๋ฅผ ์ถ์ถํ ์ ์์์ต๋๋ค. ๋ด์ฉ์ด ๋น์ด์๊ฑฐ๋ ์ธ์์ด ์ด๋ ต์ต๋๋ค."
return extracted_text, "์ฑ๊ณต"
except Exception as e:
# ์ค๋ฅ ๋ฐ์ ์ ๋ ๊ตฌ์ฒด์ ์ธ ๋ฉ์์ง ๋ฐํ
error_message = f"ํ์ผ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ํ์ผ์ด ์์๋์๊ฑฐ๋ ์ง์ํ์ง ์๋ ํ์์ผ ์ ์์ต๋๋ค.\n(์๋ฒ ์ค๋ฅ: {str(e)})"
print(f"โ ํ
์คํธ ์ถ์ถ ์คํจ: {error_message}")
return "", error_message
def perform_rule_based_analysis(contract_text: str) -> dict:
alerts, safety_score = [], 100
try:
# 1. ๊ธฐ์กด์ ํค์๋ ๊ธฐ๋ฐ ๋ถ์ (์ ์ง)
categories = {
"๋ณด์ฆ๊ธ_๋ฐํ": {"keywords": ["๋ณด์ฆ๊ธ", "๋ฐํ", "์ฆ์", "๊ณ์ฝ์ข
๋ฃ"], "risk": "CRITICAL"},
"๊ถ๋ฆฌ๊ด๊ณ_์ ์ง": {"keywords": ["๊ถ๋ฆฌ๊ด๊ณ", "์ต์ผ", "๊ทผ์ ๋น", "๋ํญ๋ ฅ"], "risk": "CRITICAL"},
"์ ์ธ์๊ธ๋์ถ": {"keywords": ["๋์ถ", "๋ถ๊ฐ", "๋ฌดํจ", "์ ์ธ์๊ธ"], "risk": "WARNING"},
"์์ _์๋ฌด": {"keywords": ["์์ ", "ํ์", "ํ์", "์๋ฆฌ"], "risk": "ADVISORY"},
"ํน์ฝ์ฌํญ": {"keywords": ["ํน์ฝ", "๊ธฐํ์ฌํญ", "์ถ๊ฐ์กฐ๊ฑด"], "risk": "ADVISORY"}
}
for cat_name, info in categories.items():
display_name = cat_name.replace('_', ' ').title()
keyword_count = sum(1 for kw in info['keywords'] if kw in contract_text)
if keyword_count < len(info['keywords']) * 0.5:
if info['risk'] == "CRITICAL":
safety_score -= 40
alerts.append(f"๐จ [์น๋ช
์ !] {display_name}: ๊ด๋ จ ์กฐํญ์ด ๋๋ฝ๋์๊ฑฐ๋ ๋ฏธ๋นํ์ฌ ์ฌ๊ฐํ ์ํ์ด ๋ฐ์ํ ์ ์์ต๋๋ค!")
elif info['risk'] == "WARNING":
safety_score -= 20
alerts.append(f"โ ๏ธ [์ํ] {display_name}: ๊ด๋ จ ์กฐํญ์ด ๋ถ์กฑํ์ฌ ์ฃผ์๊ฐ ํ์ํฉ๋๋ค.")
else:
safety_score -= 10
alerts.append(f"๐ก [๊ถ์ฅ] {display_name}: ๋ถ์ ์๋ฐฉ์ ์ํด ๊ด๋ จ ์กฐํญ ๋ณด๊ฐ์ ๊ถ์ฅํฉ๋๋ค.")
else:
alerts.append(f"โ
[{display_name}] ๊ด๋ จ ์กฐํญ์ด ํ์ธ๋์์ต๋๋ค.")
safety_score = max(0, safety_score)
# 2. ๐ฅ ์๋์ธ ์ด๋ฆ ์ถ์ถ ๋ฐ ์์ต ์ฑ๋ฌด ๋ถ์ดํ์ ๋ช
๋จ ์กฐํ (ํต์ฌ ๊ธฐ๋ฅ ์ถ๊ฐ)
print(" [์๋์ธ ๊ฒ์ฌ] ์๋์ธ ์ ์ ์กฐํ ์์...")
landlord_name = extract_landlord_name_robustly(contract_text)
if landlord_name == "์ด๋ฆ ์๋ ์ถ์ถ ์คํจ":
alerts.append("โ ๏ธ [์๋์ธ ๊ฒ์ฌ] ๊ณ์ฝ์์์ ์๋์ธ ์ด๋ฆ์ ์๋์ผ๋ก ์ฐพ์ง ๋ชปํ์ต๋๋ค. ์ง์ ํ์ธ์ด ํ์ํฉ๋๋ค.")
else:
found_defaulter = False
try:
with open(DEFAULTER_LIST_PATH, 'r', encoding='utf-8-sig') as f:
# CSV ํ์ผ์ ๋ชจ๋ ํ์ ๋ฏธ๋ฆฌ ๋ฆฌ์คํธ๋ก ๋ก๋ํ์ฌ ๊ฒ์ ํจ์จ์ฑ ์ฆ๋
defaulter_list = list(csv.DictReader(f))
for row in defaulter_list:
# ์ด๋ฆ ๋น๊ต ์ ๊ณต๋ฐฑ ์ ๊ฑฐ ํ ๋น๊ต
defaulter_name = row.get('์ฑ๋ช
', '').strip().replace(' ', '')
if landlord_name == defaulter_name:
safety_score = 0 # << ์น๋ช
์ ์ํ์ด๋ฏ๋ก ์์ ์ ์ 0์ ์ผ๋ก ์กฐ์
alerts.append(f"๐จ๐จ๐จ [์น๋ช
์ ์ํ!] ์๋์ธ '{landlord_name}'์ด(๊ฐ) ์์ต ์ฑ๋ฌด ๋ถ์ดํ์ ๋ช
๋จ์ ํฌํจ๋์ด ์์ต๋๋ค! **๊ณ์ฝ์ ์ฆ์ ์ค๋จํ๊ณ ์ ๋ฌธ๊ฐ์ ์๋ดํ์ธ์.**")
found_defaulter = True
break
if not found_defaulter:
alerts.append(f"โ
[์๋์ธ ๊ฒ์ฌ] ์๋์ธ('{landlord_name}')์(๋) ์์ต ์ฑ๋ฌด ๋ถ์ดํ์ ๋ช
๋จ์ ์์ต๋๋ค.")
except FileNotFoundError:
alerts.append(f"โ ๏ธ [์๋์ธ ๊ฒ์ฌ] ์์ต ์ฑ๋ฌด๋ถ์ดํ์ ๋ช
๋จ ํ์ผ์ ์ฐพ์ ์ ์์ด ์กฐํ๊ฐ ๋ถ๊ฐ๋ฅํฉ๋๋ค. ({DEFAULTER_LIST_PATH})")
except Exception as e:
alerts.append(f"โ ๏ธ [์๋์ธ ๊ฒ์ฌ] ๋ช
๋จ ํ์ผ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {e}")
except Exception as e:
alerts.append(f"โ ๏ธ ๊ท์น ๊ธฐ๋ฐ ๋ถ์ ์ค ์ค๋ฅ ๋ฐ์: {e}")
safety_score = -1
# ์์ ์ ์ ์์ผ๋ก ์ ๋ ฌํ์ฌ ์ค์ํ ๊ฒฝ๊ณ ๊ฐ ์๋ก ์ค๊ฒ ํจ
alerts.sort(key=lambda x: ('๐จ' not in x, 'โ ๏ธ' not in x, '๐ก' not in x, 'โ
' not in x))
return {"alerts": alerts, "safety_score": safety_score}
def google_text_to_speech(text, lang_code="KO"):
if not GOOGLE_API_KEY:
return None, "Google API ํค๊ฐ ์ค์ ๋์ง ์์ ์์ฑ ์์ฑ์ด ๋ถ๊ฐ๋ฅํฉ๋๋ค."
# ํน์๋ฌธ์ ์ผ๋ถ ์ ๊ฑฐ (์์ฑ ๋ณํ ํ์ง ํฅ์)
text = re.sub(r"[^\w\s๊ฐ-ํฃ.,!?]", "", text, flags=re.UNICODE)
text_chunks = split_text_for_tts(text)
voice_map = {
"KO": {"languageCode": "ko-KR", "name": "ko-KR-Wavenet-A"},
"EN": {"languageCode": "en-US", "name": "en-US-Wavenet-F"},
"JA": {"languageCode": "ja-JP", "name": "ja-JP-Wavenet-A"},
"ZH": {"languageCode": "cmn-CN", "name": "cmn-CN-Wavenet-A"},
"UK": {"languageCode": "uk-UA", "name": "uk-UA-Wavenet-A"}, # ์ฐํฌ๋ผ์ด๋์ด
"VI": {"languageCode": "vi-VN", "name": "vi-VN-Wavenet-A"} # ๋ฒ ํธ๋จ์ด
}
if lang_code.upper() not in voice_map:
return None, f"์ง์ํ์ง ์๋ ์ธ์ด ์ฝ๋: {lang_code}"
try:
# ๊ธด ํ
์คํธ์ ๊ฒฝ์ฐ ์ฒซ ๋ฒ์งธ ์ฒญํฌ๋ง ์ฒ๋ฆฌํ์ฌ ์ํ ์ ๊ณต (Gradio์์๋ ์ ์ฒด๋ฅผ ์ฒ๋ฆฌํ๋ฉด ์๊ฐ์ด ๋๋ฌด ์ค๋ ๊ฑธ๋ฆด ์ ์์)
first_chunk = text_chunks[0] if text_chunks else ""
if not first_chunk:
return None, "์์ฑ์ผ๋ก ๋ณํํ ํ
์คํธ๊ฐ ์์ต๋๋ค."
request_body = {
"input": {"text": first_chunk},
"voice": voice_map[lang_code.upper()],
"audioConfig": {"audioEncoding": "MP3", "speakingRate": 0.9, "pitch": -2}
}
response = requests.post(TTS_API_URL, data=json.dumps(request_body), timeout=30)
if response.status_code == 200:
audio_content = base64.b64decode(response.json()['audioContent'])
# Gradio์์๋ ์์ ํ์ผ์ ์ฌ์ฉํ๋ ๊ฒ์ด ์์ ์
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
tmp_file.write(audio_content)
# ๋ฉ์์ง ๊ฐ์
msg = "์์ฑ ์์ฑ ์๋ฃ!"
if len(text_chunks) > 1:
msg = f"์์ฑ ์์ฑ ์๋ฃ ๐ต "
return tmp_file.name, msg
else:
return None, f"TTS API ์ค๋ฅ: {response.text}"
except ConnectionError as e:
print(f"โ TTS ๋คํธ์ํฌ ์ฐ๊ฒฐ ์ค๋ฅ: {e}")
return None, "โ ๋คํธ์ํฌ ์ฐ๊ฒฐ์ด ๋ถ์์ ํ์ฌ ์์ฑ ์์ฑ์ ์คํจํ์ต๋๋ค."
except TimeoutError as e:
print(f"โ TTS ์๋ต ์๊ฐ ์ด๊ณผ: {e}")
return None, "โ ์์ฑ ์์ฑ ์๊ฐ์ด ์ด๊ณผ๋์์ต๋๋ค. ํ
์คํธ๋ฅผ ์ค์ด๊ฑฐ๋ ๋ค์ ์๋ํด์ฃผ์ธ์."
except requests.exceptions.RequestException as e:
print(f"โ TTS API ์์ฒญ ์ค๋ฅ: {e}")
return None, f"โ ์์ฑ ์์ฑ API ์์ฒญ ์คํจ: {e}"
except Exception as e:
print(f"โ TTS ์ค ์์ธ ๋ฐ์: {e}")
return None, f"โ ์์ฑ ์์ฑ ์ค ์ค๋ฅ: {e}"
RETRIEVER = None
def initialize_retriever():
"""์ ์ญ RAG ๊ฒ์๊ธฐ๋ฅผ ์ด๊ธฐํํฉ๋๋ค."""
global RETRIEVER
if os.path.exists(CHROMA_DB_PATH):
try:
vectorstore = Chroma(
persist_directory=CHROMA_DB_PATH,
embedding_function=UpstageEmbeddings(model="solar-embedding-1-large")
)
RETRIEVER = vectorstore.as_retriever(search_kwargs={"k": 5})
print("โ
RAG ๊ฒ์๊ธฐ(Retriever) ์ด๊ธฐํ ์๋ฃ.")
except Exception as e:
print(f"โ RAG ๊ฒ์๊ธฐ ์ด๊ธฐํ ์คํจ: {e}")
else:
print("โ ๏ธ Vector DB ๊ฒฝ๋ก๋ฅผ ์ฐพ์ ์ ์์ด RAG ๊ฒ์๊ธฐ๋ฅผ ์ด๊ธฐํํ ์ ์์ต๋๋ค.")
# ๐จ ์ด๋ฏธ์ง ์์ฑ ๋ฐ UI ๊ด๋ จ ํจ์๋ค
# ๐จ ์ด๋ฏธ์ง ์์ฑ์ ์ํ ์์ ๋ฐ ํฐํธ ์ค์ (PIL ํด๋ฐฑ์ฉ) - ์ด๋ก์ ํ
๋ง
COLORS = {
'bg': '#f0f9ff',
'white': '#ffffff',
'primary': '#10b981',
'success': '#059669',
'warning': '#f59e0b',
'danger': '#ef4444',
'text': '#1f2937',
'muted': '#6b7280',
'border': '#d1fae5',
'accent': '#047857'
}
EMBED_HEAD = """
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- ๋ค๊ตญ์ด ์ง์์ ์ํ Noto Sans ํฐํธ ํจ๋ฐ๋ฆฌ -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;500;700&family=Noto+Sans+KR:wght@400;500;700&family=Noto+Sans+JP:wght@400;500;700&family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--card-bg: #ffffff;
--bg: #f0fdf4;
--border: #d1fae5;
--text: #1f2937;
--text-weak: #4b5563;
--muted: #6b7280;
--primary: #10b981;
--primary-dark: #059669;
--accent: #047857;
--shadow: rgba(16, 185, 129, 0.1);
--badge-bg: #ecfdf5;
--badge-text: #065f46;
--badge-border: #a7f3d0;
}
@media (prefers-color-scheme: dark) {
:root {
--card-bg: #0f172a;
--bg: #020617;
--border: #1e293b;
--text: #e2e8f0;
--text-weak: #cbd5e1;
--muted: #94a3b8;
--primary: #34d399;
--primary-dark: #10b981;
--accent: #059669;
--shadow: rgba(16, 185, 129, 0.2);
--badge-bg: #064e3b;
--badge-text: #6ee7b7;
--badge-border: #065f46;
}
}
html, body {
background: var(--bg);
color: var(--text);
font-family: 'Noto Sans KR', 'Noto Sans', 'Noto Sans JP', 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Malgun Gothic', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
line-height: 1.7;
}
</style>
"""
# ๐ฅ FIXED: ์ค๋ฐ๊ฟ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ CSS
DEFAULT_EMBED_CSS = """
.report-wrap { max-width: 980px; margin: 0 auto; padding: 32px; }
.report-card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 20px; overflow: hidden; box-shadow: 0 10px 35px var(--shadow); }
.report-header { background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); padding: 32px; color: #fff; }
.report-header h1 { margin: 0 0 8px 0; font-size: 26px; font-weight: 700; }
.report-header .meta { font-size: 14px; opacity: .9; }
.report-section { padding: 28px 32px; border-top: 1px solid var(--border); }
.report-section:last-child { border-bottom: none; }
.report-section h2 { margin: 0 0 16px 0; font-size: 20px; font-weight: 700; color: var(--text); padding-bottom: 8px; border-bottom: 2px solid var(--primary); display: inline-block;}
.alerts { display: grid; gap: 12px; }
.alert { padding: 14px 18px; border-radius: 12px; border: 1px solid transparent; display: flex; align-items: center; gap: 10px; }
.alert::before { font-size: 20px; }
.alert.critical { border-color:#fecaca; background:#fff1f2; color:#b91c1c; }
.alert.critical::before { content: '๐จ'; }
.alert.warn { border-color:#fde68a; background:#fffbeb; color: #b45309; }
.alert.warn::before { content: 'โ ๏ธ'; }
.alert.ok { border-color:#bbf7d0; background:#f0fdf4; color: #15803d; }
.alert.ok::before { content: 'โ
'; }
@media (prefers-color-scheme: dark) {
.alert.critical { background:#2d1516; border-color:#7f1d1d; color:#fca5a5; }
.alert.warn { background:#2d230d; border-color:#7c5800; color:#fde047; }
.alert.ok { background:#112a1a; border-color:#14532d; color:#86efac; }
}
.grade { display:inline-block; padding: 8px 14px; border-radius:999px; border:1px solid rgba(255,255,255,.5); font-weight:700; background: rgba(255,255,255,.2); backdrop-filter: blur(5px); }
.footer-note { color: var(--muted); font-size: 13px; text-align:center; padding: 24px; background: var(--bg); }
.badge { display:inline-block; padding:4px 10px; border-radius: 8px; background: var(--badge-bg); color: var(--badge-text); border:1px solid var(--badge-border); font-size:13px; font-weight: 500;}
.report-section p { margin: 0 0 12px 0; color: var(--text-weak); }
.report-section li { margin-bottom: 8px; color: var(--text-weak); }
.report-section a { color: var(--accent); text-decoration: none; font-weight: 500; }
.report-section a:hover { text-decoration: underline; }
.report-section strong { font-weight: 700; color: var(--text); }
/* ๐ฅ FIXED: ์ฝ๋ ๋ธ๋ก ๋ฐ ๊ธด ํ
์คํธ ์ค๋ฐ๊ฟ ์ฒ๋ฆฌ */
.report-section pre, .translation-content pre {
white-space: pre-wrap !important;
word-wrap: break-word !important;
overflow-wrap: break-word !important;
background: var(--badge-bg);
padding: 1rem;
border-radius: 8px;
border: 1px solid var(--border);
}
.report-section code, .translation-content code {
white-space: pre-wrap !important;
word-wrap: break-word !important;
overflow-wrap: break-word !important;
font-family: monospace;
font-size: 0.9em;
padding: 2px 6px;
border-radius: 4px;
background: var(--badge-bg);
}
/* ๐ฅ FIXED: ํ
์ด๋ธ ๋ฐ์ํ ์ฒ๋ฆฌ (๋ฒ ํธ๋จ์ด ์ง์ ๊ฐํ) */
.report-section table, .translation-content table {
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
background: white;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.report-section table { table-layout: fixed; }
.translation-content table { table-layout: auto; }
.translation-content .table-wrapper {
overflow-x: auto;
margin: 20px 0;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.report-section th, .report-section td, .translation-content th, .translation-content td {
border: 1px solid var(--border);
padding: 12px 16px;
word-wrap: break-word;
overflow-wrap: break-word;
vertical-align: top;
}
.report-section th {
background-color: var(--badge-bg);
font-weight: 600;
}
.translation-content th {
background: var(--primary);
color: white;
font-weight: 600;
border-bottom: 2px solid var(--primary-dark);
}
.translation-content td {
border-bottom: 1px solid var(--border);
}
.translation-content tr:nth-child(even) {
background: var(--bg-light);
}
.translation-content tr:hover {
background: var(--bg-hover);
}
/* ๐ฅ FIXED: ๊ธด ๋จ์ด ๊ฐ์ ์ค๋ฐ๊ฟ์ผ๋ก ๋ ์ด์์ ๊นจ์ง ๋ฐฉ์ง */
.report-section *, .translation-content * {
word-break: break-word;
overflow-wrap: break-word;
}
/* ๋ฒ์ญ ๊ฒฐ๊ณผ ์ ์ฉ ์คํ์ผ ์ถ๊ฐ */
.translation-content {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 16px;
padding: 24px;
margin: 8px 0;
box-shadow: 0 4px 20px var(--shadow);
line-height: 1.7;
/* ๋ฒ ํธ๋จ์ด ํน์ ๋ฌธ์ ์ง์์ ์ํ ํฐํธ ์ค์ */
font-family: 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', sans-serif;
}
.translation-content h1, .translation-content h2, .translation-content h3 {
color: var(--primary);
margin-top: 24px;
margin-bottom: 16px;
}
.translation-content h1 {
font-size: 24px;
font-weight: 700;
border-bottom: 2px solid var(--primary);
padding-bottom: 8px;
}
.translation-content h2 {
font-size: 20px;
font-weight: 600;
}
.translation-content h3 {
font-size: 18px;
font-weight: 500;
}
.translation-content p {
margin-bottom: 12px;
color: var(--text-weak);
}
.translation-content ul, .translation-content ol {
margin: 16px 0;
padding-left: 24px;
}
.translation-content li {
margin-bottom: 8px;
color: var(--text-weak);
}
.translation-content strong {
color: var(--text);
font-weight: 600;
}