File size: 12,487 Bytes
352a4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7b2e65
352a4b6
 
 
 
 
 
 
 
 
f7b2e65
 
352a4b6
 
f7b2e65
352a4b6
 
 
 
 
f7b2e65
352a4b6
 
 
f7b2e65
 
 
352a4b6
 
f7b2e65
352a4b6
 
 
 
f7b2e65
352a4b6
 
 
 
 
 
 
 
f7b2e65
352a4b6
 
 
f7b2e65
 
352a4b6
 
 
 
 
 
 
 
 
 
 
 
f7b2e65
 
352a4b6
 
 
f7b2e65
352a4b6
 
 
 
 
f7b2e65
352a4b6
f7b2e65
 
352a4b6
 
 
f7b2e65
 
352a4b6
 
 
f7b2e65
352a4b6
 
 
 
 
f7b2e65
 
352a4b6
 
 
 
 
 
f7b2e65
 
352a4b6
 
 
 
 
 
 
f7b2e65
 
352a4b6
 
 
f7b2e65
 
352a4b6
f7b2e65
352a4b6
 
 
 
 
 
 
f7b2e65
 
352a4b6
f7b2e65
 
352a4b6
f7b2e65
352a4b6
f7b2e65
 
 
352a4b6
f7b2e65
 
 
 
 
 
352a4b6
f7b2e65
352a4b6
f7b2e65
352a4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
f7b2e65
352a4b6
 
 
f7b2e65
352a4b6
 
 
 
 
 
 
 
 
 
 
 
f7b2e65
352a4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
f7b2e65
352a4b6
 
 
 
 
 
 
 
f7b2e65
 
352a4b6
f7b2e65
 
 
 
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
import logging
from flask import Blueprint, render_template, request, jsonify, send_from_directory
from pathlib import Path
import shutil # For zipping the cache directory
import json # For parsing streamed JSON data

import os
import config
import utils
from llm_client import make_chat_completion_request, is_initialized as llm_is_initialized
from cache_store import cache
from cache_store import cache_directory
import requests

logger = logging.getLogger(__name__)

main_bp = Blueprint('main', __name__)

# LLM client is initialized in app.py create_app()

# --- Serve the cache directory as a zip file ---
@main_bp.route('/download_cache')
def download_cache_zip():
    """μΊμ‹œ 디렉토리λ₯Ό μ••μΆ•ν•˜μ—¬ λ‹€μš΄λ‘œλ“œλ₯Ό μœ„ν•΄ μ œκ³΅ν•©λ‹ˆλ‹€."""
    zip_filename = "radexplain-cache.zip"
    # Create the zip file in a temporary directory
    # Using /tmp is common in containerized environments
    temp_dir = "/tmp"
    zip_base_path = os.path.join(temp_dir, "radexplain-cache") # shutil adds .zip
    zip_filepath = zip_base_path + ".zip"

    # Ensure the cache directory exists before trying to zip it
    if not os.path.isdir(cache_directory):
        logger.error(f"μΊμ‹œ 디렉토리λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: {cache_directory}")
        return jsonify({"error": f"μ„œλ²„μ—μ„œ μΊμ‹œ 디렉토리λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: {cache_directory}"}), 500

    try:
        logger.info(f"μΊμ‹œ λ””λ ‰ν† λ¦¬μ˜ μ••μΆ• 파일 생성 쀑: {cache_directory} -> {zip_filepath}")
        shutil.make_archive(
            zip_base_path, # This is the base name, shutil adds the .zip extension
            "zip",
            cache_directory, # This is the root directory to archive
        )
        logger.info("μ••μΆ• 파일이 μ„±κ³΅μ μœΌλ‘œ μƒμ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        # Send the file and then clean it up
        return send_from_directory(temp_dir, zip_filename, as_attachment=True)
    except Exception as e:
        logger.error(f"μΊμ‹œ 디렉토리 μ••μΆ• 파일 생성 λ˜λŠ” 전솑 쀑 였λ₯˜ λ°œμƒ: {e}", exc_info=True)
        return jsonify({"error": f"μ••μΆ• 파일 생성 λ˜λŠ” 전솑 쀑 였λ₯˜ λ°œμƒ: {e}"}), 500

@main_bp.route('/')
def index():
    """메인 HTML νŽ˜μ΄μ§€λ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€."""
    # The backend now only provides the list of available reports.
    # The frontend will be responsible for selecting a report,
    # fetching its details (text, image path), and managing the current state.
    if not config.AVAILABLE_REPORTS:
        logger.warning("μ„€μ •μ—μ„œ λ³΄κ³ μ„œλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€. AVAILABLE_REPORTSκ°€ λΉ„μ–΄μžˆμŠ΅λ‹ˆλ‹€.")

    return render_template(
        'index.html',
        available_reports=config.AVAILABLE_REPORTS
    )

@main_bp.route('/get_report_details/<report_name>')
def get_report_details(report_name):
    """μ£Όμ–΄μ§„ λ³΄κ³ μ„œ 이름에 λŒ€ν•œ ν…μŠ€νŠΈ λ‚΄μš©κ³Ό 이미지 경둜λ₯Ό κ°€μ Έμ˜΅λ‹ˆλ‹€."""
    selected_report_info = next((item for item in config.AVAILABLE_REPORTS if item['name'] == report_name), None)

    if not selected_report_info:
        logger.error(f"상세 정보λ₯Ό κ°€μ Έμ˜¬ λ•Œ λ³΄κ³ μ„œ '{report_name}'을(λ₯Ό) 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
        return jsonify({"error": f"λ³΄κ³ μ„œ '{report_name}'을(λ₯Ό) 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."}), 404

    report_file = selected_report_info.get('report_file')
    image_file = selected_report_info.get('image_file') 

    report_text_content = "" # Default to empty if no report file is configured.

    if report_file:
        actual_server_report_path = config.BASE_DIR / report_file

        try:
            report_text_content = actual_server_report_path.read_text(encoding='utf-8').strip()
        except Exception as e:
            logger.error(f"λ³΄κ³ μ„œ '{report_name}'의 파일 {actual_server_report_path} 읽기 였λ₯˜: {e}", exc_info=True)
            return jsonify({"error": "λ³΄κ³ μ„œ νŒŒμΌμ„ μ½λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."}), 500
    # If report_file was empty, report_text_content remains "".

    image_type_from_config = selected_report_info.get('image_type')
    display_image_type = '흉뢀 X-레이' if image_type_from_config == 'CXR' else ('CT' if image_type_from_config == 'CT' else '의료 μ˜μƒ')

    return jsonify({"text": report_text_content, "image_file": image_file, "image_type": display_image_type})

@main_bp.route('/explain', methods=['POST'])
def explain_sentence():
    """base64둜 μΈμ½”λ”©λœ 이미지와 ν•¨κ»˜ LLM APIλ₯Ό μ‚¬μš©ν•˜μ—¬ μ„€λͺ… μš”μ²­μ„ μ²˜λ¦¬ν•©λ‹ˆλ‹€."""
    if not llm_is_initialized():
         logger.error("LLM ν΄λΌμ΄μ–ΈνŠΈ(REST API)κ°€ μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. μš”μ²­μ„ μ²˜λ¦¬ν•  수 μ—†μŠ΅λ‹ˆλ‹€.")
         return jsonify({"error": "LLM ν΄λΌμ΄μ–ΈνŠΈ(REST API)κ°€ μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. API 킀와 베이슀 URL을 ν™•μΈν•˜μ„Έμš”."}), 500

    data = request.get_json()
    if not data or 'sentence' not in data or 'report_name' not in data:
        logger.warning("μš”μ²­ νŽ˜μ΄λ‘œλ“œμ— 'sentence' λ˜λŠ” 'report_name'이 λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        return jsonify({"error": "μš”μ²­μ— 'sentence' λ˜λŠ” 'report_name'이 λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€"}), 400

    selected_sentence = data['sentence']
    report_name = data['report_name']
    logger.info(f"μ„€λͺ… μš”μ²­ μˆ˜μ‹ : '{selected_sentence}' (λ³΄κ³ μ„œ: '{report_name}')")

    # --- Find the selected report info ---
    selected_report_info = next((item for item in config.AVAILABLE_REPORTS if item['name'] == report_name), None)

    if not selected_report_info:
        logger.error(f"μ‚¬μš© κ°€λŠ₯ν•œ λ³΄κ³ μ„œμ—μ„œ '{report_name}'을(λ₯Ό) 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
        return jsonify({"error": f"λ³΄κ³ μ„œ '{report_name}'을(λ₯Ό) 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."}), 404

    image_file = selected_report_info.get('image_file')
    report_file = selected_report_info.get('report_file')
    image_type = selected_report_info.get('image_type')

    if not image_file:
        logger.error(f"λ³΄κ³ μ„œ '{report_name}'의 μ„€μ •μ—μ„œ 이미지 λ˜λŠ” λ³΄κ³ μ„œ 파일 경둜(static κΈ°μ€€ μƒλŒ€κ²½λ‘œ)κ°€ λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        return jsonify({"error": f"λ³΄κ³ μ„œ '{report_name}'의 파일 섀정이 λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€."}), 500

    # Construct absolute server paths using BASE_DIR as image_file and report_file include "static/"
    server_image_path = config.BASE_DIR / image_file

    
    # --- Prepare Base64 Image for API ---
    if not server_image_path.is_file():
        logger.error(f"이미지 νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: {server_image_path}")
        return jsonify({"error": f"λ³΄κ³ μ„œ '{report_name}'의 이미지 νŒŒμΌμ„ μ„œλ²„μ—μ„œ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."}), 500

    base64_image_data_url = utils.image_to_base64_data_url(str(server_image_path))
    if not base64_image_data_url:
        logger.error("이미지λ₯Ό base64둜 μΈμ½”λ”©ν•˜λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.")
        return jsonify({"error": "API μš”μ²­μ„ μœ„ν•œ 이미지 인코딩에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€"}), 500

    logger.info("APIλ₯Ό μœ„ν•œ base64 데이터 URL둜 이미지가 μ„±κ³΅μ μœΌλ‘œ μΈμ½”λ”©λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")

    full_report_text = ""
    if report_file: # Only attempt to read if a report file is configured
        server_report_path = config.BASE_DIR / report_file
        try:
            full_report_text = server_report_path.read_text(encoding='utf-8')
        except FileNotFoundError:
            logger.error(f"λ³΄κ³ μ„œ νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€: {server_report_path}")
            return jsonify({"error": f"λ³΄κ³ μ„œ '{report_name}'의 νŒŒμΌμ„ μ„œλ²„μ—μ„œ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."}), 500
        except Exception as e:
            logger.error(f"λ³΄κ³ μ„œ 파일 {server_report_path} 읽기 였λ₯˜: {e}", exc_info=True)
            return jsonify({"error": "λ³΄κ³ μ„œ νŒŒμΌμ„ μ½λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."}), 500
    else: # If report_file is not configured (e.g. empty string from selected_report_info)
        logger.info(f"λ³΄κ³ μ„œ '{report_name}'에 λŒ€ν•œ λ³΄κ³ μ„œ 파일이 μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. μ‹œμŠ€ν…œ ν”„λ‘¬ν”„νŠΈμ— 전체 λ³΄κ³ μ„œ ν…μŠ€νŠΈ 없이 μ§„ν–‰ν•©λ‹ˆλ‹€.")

    # 이미지 νƒ€μž…μ— λ”°λ₯Έ ν•œκΈ€ ν‘œμ‹œ
    image_type_korean = '흉뢀 X-레이' if image_type == 'CXR' else ('CT' if image_type == 'CT' else '의료 μ˜μƒ')
    
    system_prompt = (
        "당신은 μΌλ°˜μΈμ„ λŒ€μƒμœΌλ‘œ μ„€λͺ…ν•˜λŠ” μž„μƒμ˜μž…λ‹ˆλ‹€. "
        f"ν•™μŠ΅ 쀑인 μ‚¬μš©μžκ°€ 방사선 λ³΄κ³ μ„œμ˜ ν•œ λ¬Έμž₯을 μ œκ³΅ν–ˆκ³  ν•¨κ»˜ 제곡된 {image_type_korean} μ˜μƒμ„ 보고 μžˆμŠ΅λ‹ˆλ‹€. "
        "λ‹Ήμ‹ μ˜ μž„λ¬΄λŠ” 제곡된 λ¬Έμž₯만의 의미λ₯Ό κ°„λ‹¨ν•˜κ³  λͺ…ν™•ν•œ μš©μ–΄λ‘œ μ„€λͺ…ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€. μ „λ¬Έ μš©μ–΄μ™€ μ•½μ–΄λ₯Ό μ„€λͺ…ν•˜μ„Έμš”. κ°„κ²°ν•˜κ²Œ μœ μ§€ν•˜μ„Έμš”. "
        "λ¬Έμž₯의 의미λ₯Ό μ§μ ‘μ μœΌλ‘œ μ„€λͺ…ν•˜μ„Έμš”. 'λ„€' λ˜λŠ” 'μ•Œκ² μŠ΅λ‹ˆλ‹€'와 같은 λ„μž… 문ꡬλ₯Ό μ‚¬μš©ν•˜μ§€ 말고, λ¬Έμž₯ μžμ²΄λ‚˜ λ³΄κ³ μ„œ 자체λ₯Ό μ–ΈκΈ‰ν•˜μ§€ λ§ˆμ„Έμš”(예: '이 λ¬Έμž₯은...'). "
        f"{f'μ€‘μš”ν•œ 점은, μ‚¬μš©μžκ°€ {image_type_korean} μ˜μƒμ„ 보고 μžˆμœΌλ―€λ‘œ, ν•΄λ‹Ήλ˜λŠ” 경우 μ„€λͺ…을 μ΄ν•΄ν•˜κΈ° μœ„ν•΄ μ˜μƒμ˜ μ–΄λŠ 뢀뢄을 봐야 ν•˜λŠ”μ§€ μ•ˆλ‚΄λ₯Ό μ œκ³΅ν•˜μ„Έμš”. ' if image_type != 'CT' else ''}"
        "μ‚¬μš©μžκ°€ λͺ…μ‹œμ μœΌλ‘œ μ œκ³΅ν•˜μ§€ μ•Šμ€ λ³΄κ³ μ„œμ˜ λ‹€λ₯Έ λΆ€λΆ„μ΄λ‚˜ λ¬Έμž₯에 λŒ€ν•΄μ„œλŠ” λ…Όμ˜ν•˜μ§€ λ§ˆμ„Έμš”. ν…μŠ€νŠΈμ— μžˆλŠ” μ‚¬μ‹€λ§Œμ„ κ³ μˆ˜ν•˜μ„Έμš”. μΆ”λ‘ ν•˜μ§€ λ§ˆμ„Έμš”. \n"
        "===\n"
        f"μ°Έκ³ λ₯Ό μœ„ν•œ 전체 λ³΄κ³ μ„œ:\n{full_report_text}"
    )
    user_prompt_text = f"방사선 λ³΄κ³ μ„œμ˜ 이 λ¬Έμž₯을 μ„€λͺ…ν•΄μ£Όμ„Έμš”: '{selected_sentence}'"

    messages_for_api = [
        {"role": "system", "content": system_prompt},
        {
            "role": "user",
            "content": [
                {"type": "text", "text": user_prompt_text}
            ]
        }
    ]

    cache_key = f"explain::{report_name}::{selected_sentence}"
    cached_result = cache.get(cache_key)
    if cached_result:
        logger.info("μΊμ‹œλœ μ„€λͺ…을 λ°˜ν™˜ν•©λ‹ˆλ‹€.")
        return jsonify({"explanation": cached_result})

    try:
        logger.info("base64 이미지와 ν•¨κ»˜ LLM API(REST)둜 μš”μ²­μ„ 전솑 쀑...")
        response = make_chat_completion_request(
            model="tgi",
            messages=messages_for_api,
            top_p=None,
            temperature=0,
            max_tokens=250,
            stream=True,
            seed=None,
            stop=None,
            frequency_penalty=None,
            presence_penalty=None
        )
        logger.info("LLM API(REST)λ‘œλΆ€ν„° 응닡 μŠ€νŠΈλ¦Όμ„ μˆ˜μ‹ ν–ˆμŠ΅λ‹ˆλ‹€.")

        explanation_parts = []
        for line in response.iter_lines():
            if line:
                decoded_line = line.decode('utf-8')
                if decoded_line.startswith('data: '):
                    json_data_str = decoded_line[len('data: '):].strip()
                    if json_data_str == "[DONE]":
                        break
                    try:
                        chunk = json.loads(json_data_str)
                        if chunk.get("choices") and chunk["choices"][0].get("delta") and chunk["choices"][0]["delta"].get("content"):
                            explanation_parts.append(chunk["choices"][0]["delta"]["content"])
                    except json.JSONDecodeError:
                        logger.warning(f"슀트림 μ²­ν¬μ—μ„œ JSON을 λ””μ½”λ”©ν•  수 μ—†μŠ΅λ‹ˆλ‹€: {json_data_str}")
                        # Depending on API, might need to handle partial JSON or other errors
                elif decoded_line.strip() == "[DONE]": # Some APIs might send [DONE] without "data: "
                    break

        explanation = "".join(explanation_parts).strip()
        if explanation:
            cache.set(cache_key, explanation, expire=None)

        logger.info("μ„€λͺ…이 μ„±κ³΅μ μœΌλ‘œ μƒμ„±λ˜μ—ˆμŠ΅λ‹ˆλ‹€." if explanation else "APIλ‘œλΆ€ν„° 빈 μ„€λͺ…을 λ°›μ•˜μŠ΅λ‹ˆλ‹€.")
        return jsonify({"explanation": explanation or "APIλ‘œλΆ€ν„° μ„€λͺ… λ‚΄μš©μ„ λ°›μ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€."})
    except requests.exceptions.RequestException as e:
        logger.error(f"LLM API(REST) 호좜 쀑 였λ₯˜ λ°œμƒ: {e}", exc_info=True)
        user_error_message = ("μ„€λͺ… 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. μ„œλΉ„μŠ€κ°€ μΌμ‹œμ μœΌλ‘œ μ‚¬μš©ν•  수 μ—†μœΌλ©° "
                              "ν˜„μž¬ μ‹œμž‘ 쀑일 수 μžˆμŠ΅λ‹ˆλ‹€. μž μ‹œ ν›„ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.")
        return jsonify({"error": user_error_message}), 500