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
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
import gradio as gr
import torch

try:
    from unsloth import FastLanguageModel
except ImportError:
    print("Unsloth๊ฐ€ ์„ค์น˜๋˜์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์„ค์น˜ ์ค‘...")
    import subprocess
    subprocess.check_call(["pip", "install", "unsloth"])
    from unsloth import FastLanguageModel

# Hugging Face์— ์—…๋กœ๋“œ๋œ ๋ชจ๋ธ ์‚ฌ์šฉ
MODEL_NAME = "huggingface-KREW/Llama-3.1-8B-Spider-SQL-Ko"

print(f"Loading model from Hugging Face: {MODEL_NAME}")

# Unsloth๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ชจ๋ธ๊ณผ ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ
try:
    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name=MODEL_NAME,
        max_seq_length=2048,
        dtype=None,  # ์ž๋™ ๊ฐ์ง€
        load_in_4bit=True,  # 4๋น„ํŠธ ์–‘์žํ™” ์‚ฌ์šฉ
    )
    
    # ์ถ”๋ก  ๋ชจ๋“œ๋กœ ์„ค์ •
    FastLanguageModel.for_inference(model)
    print("Model loaded successfully with Unsloth!")
    
except Exception as e:
    print(f"Error loading model with Unsloth: {e}")
    print("\n๋ชจ๋ธ์ด Hugging Face์— ์ œ๋Œ€๋กœ ์—…๋กœ๋“œ๋˜์ง€ ์•Š์•˜์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
    print("๋กœ์ปฌ ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋ชจ๋ธ์„ ๋‹ค์‹œ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”.")
    raise

# Example databases and questions
examples = [
    {
        "db_id": "department_management",
        "question": "๊ฐ ๋ถ€์„œ๋ณ„ ์ง์› ์ˆ˜๋ฅผ ๋ณด์—ฌ์ฃผ์„ธ์š”.",
        "schema": """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ:
ํ…Œ์ด๋ธ”: department
์ปฌ๋Ÿผ:
  - Department_ID (number) (๊ธฐ๋ณธ ํ‚ค)
  - Name (text)
  - Creation (text)
  - Ranking (number)
  - Budget_in_Billions (number)
  - Num_Employees (number)
ํ…Œ์ด๋ธ”: head
์ปฌ๋Ÿผ:
  - head_ID (number) (๊ธฐ๋ณธ ํ‚ค)
  - name (text)
  - born_state (text)
  - age (number)
ํ…Œ์ด๋ธ”: management
์ปฌ๋Ÿผ:
  - department_ID (number) (๊ธฐ๋ณธ ํ‚ค)
  - head_ID (number)
  - temporary_acting (text)

์™ธ๋ž˜ ํ‚ค ๊ด€๊ณ„:
  - management.head_ID โ†’ head.head_ID
  - management.department_ID โ†’ department.Department_ID"""
    },
    {
        "db_id": "concert_singer",
        "question": "๊ฐ€์žฅ ๋งŽ์€ ์ฝ˜์„œํŠธ๋ฅผ ์—ฐ ๊ฐ€์ˆ˜๋Š” ๋ˆ„๊ตฌ์ธ๊ฐ€์š”?",
        "schema": """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ:
ํ…Œ์ด๋ธ”: singer
์ปฌ๋Ÿผ:
  - Singer_ID (number) (๊ธฐ๋ณธ ํ‚ค)
  - Name (text)
  - Country (text)
  - Song_Name (text)
  - Song_release_year (text)
  - Age (number)
  - Is_male (text)
ํ…Œ์ด๋ธ”: concert
์ปฌ๋Ÿผ:
  - concert_ID (number) (๊ธฐ๋ณธ ํ‚ค)
  - concert_Name (text)
  - Theme (text)
  - Stadium_ID (number)
  - Year (text)
ํ…Œ์ด๋ธ”: singer_in_concert
์ปฌ๋Ÿผ:
  - concert_ID (number)
  - Singer_ID (number)

์™ธ๋ž˜ ํ‚ค ๊ด€๊ณ„:
  - singer_in_concert.Singer_ID โ†’ singer.Singer_ID
  - singer_in_concert.concert_ID โ†’ concert.concert_ID"""
    },
    {
        "db_id": "pets_1",
        "question": "๊ฐ€์žฅ ๋‚˜์ด๊ฐ€ ๋งŽ์€ ๊ฐœ์˜ ์ด๋ฆ„์€ ๋ฌด์—‡์ธ๊ฐ€์š”?",
        "schema": """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ:
ํ…Œ์ด๋ธ”: Student
์ปฌ๋Ÿผ:
  - StuID (number) (๊ธฐ๋ณธ ํ‚ค)
  - LName (text)
  - Fname (text)
  - Age (number)
  - Sex (text)
  - Major (number)
  - Advisor (number)
  - city_code (text)
ํ…Œ์ด๋ธ”: Has_Pet
์ปฌ๋Ÿผ:
  - StuID (number)
  - PetID (number)
ํ…Œ์ด๋ธ”: Pets
์ปฌ๋Ÿผ:
  - PetID (number) (๊ธฐ๋ณธ ํ‚ค)
  - PetType (text)
  - pet_age (number)
  - weight (number)"""
    },
    {
        "db_id": "car_1",
        "question": "๋ฏธ๊ตญ์‚ฐ ์ž๋™์ฐจ ์ค‘ ๊ฐ€์žฅ ๋น ๋ฅธ ์ž๋™์ฐจ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?",
        "schema": """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ:
ํ…Œ์ด๋ธ”: continents
์ปฌ๋Ÿผ:
  - ContId (number) (๊ธฐ๋ณธ ํ‚ค)
  - Continent (text)
ํ…Œ์ด๋ธ”: countries
์ปฌ๋Ÿผ:
  - CountryId (number) (๊ธฐ๋ณธ ํ‚ค)
  - CountryName (text)
  - Continent (number)
ํ…Œ์ด๋ธ”: car_makers
์ปฌ๋Ÿผ:
  - Id (number) (๊ธฐ๋ณธ ํ‚ค)
  - Maker (text)
  - FullName (text)
  - Country (number)
ํ…Œ์ด๋ธ”: model_list
์ปฌ๋Ÿผ:
  - ModelId (number) (๊ธฐ๋ณธ ํ‚ค)
  - Maker (number)
  - Model (text)
ํ…Œ์ด๋ธ”: car_names
์ปฌ๋Ÿผ:
  - MakeId (number) (๊ธฐ๋ณธ ํ‚ค)
  - Model (text)
  - Make (text)
ํ…Œ์ด๋ธ”: cars_data
์ปฌ๋Ÿผ:
  - Id (number) (๊ธฐ๋ณธ ํ‚ค)
  - MPG (text)
  - Cylinders (number)
  - Edispl (text)
  - Horsepower (text)
  - Weight (number)
  - Accelerate (number)
  - Year (number)"""
    },
    {
        "db_id": "tvshow",
        "question": "๊ฐ€์žฅ ๋†’์€ ํ‰์ ์„ ๋ฐ›์€ TV ์‡ผ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?",
        "schema": """๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ:
ํ…Œ์ด๋ธ”: TV_Channel
์ปฌ๋Ÿผ:
  - id (number) (๊ธฐ๋ณธ ํ‚ค)
  - series_name (text)
  - Country (text)
  - Language (text)
  - Content (text)
  - Pixel_aspect_ratio_PAR (text)
  - Hight_definition_TV (text)
  - Pay_per_view_PPV (text)
  - Package_Option (text)
ํ…Œ์ด๋ธ”: TV_series
์ปฌ๋Ÿผ:
  - id (number)
  - Episode (text)
  - Air_Date (text)
  - Rating (text)
  - Share (text)
  - 18_49_Rating_Share (text)
  - Viewers_m (text)
  - Weekly_Rank (number)
  - Channel (number)
ํ…Œ์ด๋ธ”: Cartoon
์ปฌ๋Ÿผ:
  - id (number) (๊ธฐ๋ณธ ํ‚ค)
  - Title (text)
  - Directed_by (text)
  - Written_by (text)
  - Original_air_date (text)
  - Production_code (number)
  - Channel (number)"""
    }
]

def generate_sql(question, db_id, schema_info):
    """Generate SQL query using the model."""
    # Create prompt with schema
    prompt = f"""๋‹น์‹ ์€ ์ž์—ฐ์–ด ์งˆ๋ฌธ์„ SQL ์ฟผ๋ฆฌ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ์ „๋ฌธ AI ์–ด์‹œ์Šคํ„ดํŠธ์ž…๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž๊ฐ€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ์ •๋ณด๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด ์ผ์ƒ ์–ธ์–ด๋กœ ์งˆ๋ฌธํ•˜๋ฉด, ๋‹น์‹ ์€ ํ•ด๋‹น ์งˆ๋ฌธ์„ ์ •ํ™•ํ•œ SQL ์ฟผ๋ฆฌ๋กœ ๋ณ€ํ™˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

{schema_info}

์งˆ๋ฌธ: {question}
SQL:"""
    
    # ์ฑ„ํŒ… ๋ฉ”์‹œ์ง€๋กœ ํฌ๋งทํŒ…
    messages = [{"role": "user", "content": prompt}]
    
    # ์ฑ„ํŒ… ํ…œํ”Œ๋ฆฟ ์ ์šฉ
    inputs = tokenizer.apply_chat_template(
        messages,
        tokenize=True,
        add_generation_prompt=True,
        return_tensors="pt"
    ).to(model.device)
    
    # Generate
    with torch.no_grad():
        outputs = model.generate(
            inputs,
            max_new_tokens=256,
            temperature=0.1,
            top_p=0.95,
            do_sample=True,
            use_cache=True
        )
    
    # Decode
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    
    # Extract SQL after the prompt
    if prompt in response:
        sql_part = response.split(prompt)[-1].strip()
    else:
        sql_part = response
    
    # Clean up the response
    if sql_part.startswith("assistant"):
        sql_part = sql_part[len("assistant"):].strip()
    
    # Extract SQL query
    lines = sql_part.split('\n')
    sql_query = ""
    for line in lines:
        line = line.strip()
        if line.lower().startswith(('select', 'with', '(select')):
            sql_query = line
            # Continue collecting lines until we hit a semicolon or empty line
            for next_line in lines[lines.index(line)+1:]:
                next_line = next_line.strip()
                if not next_line or next_line.startswith(('์งˆ๋ฌธ', '๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค')):
                    break
                sql_query += " " + next_line
                if next_line.endswith(';'):
                    break
            break
    
    # Clean up SQL
    sql_query = sql_query.strip()
    if sql_query.endswith(';'):
        sql_query = sql_query[:-1]
    
    return sql_query if sql_query else "SQL ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."

def process_question(question, db_id, custom_schema=None):
    """Process user question and generate SQL query."""
    if not question or not db_id:
        return "์งˆ๋ฌธ๊ณผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ID๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    
    # Use custom schema if provided, otherwise find from examples
    if custom_schema and custom_schema.strip():
        schema_info = custom_schema
    else:
        # Find schema from examples
        schema_info = None
        for example in examples:
            if example["db_id"] == db_id:
                schema_info = example["schema"]
                break
        
        if not schema_info:
            return "์Šคํ‚ค๋งˆ ์ •๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ์ปค์Šคํ…€ ์Šคํ‚ค๋งˆ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    
    # Generate SQL
    try:
        sql_query = generate_sql(question, db_id, schema_info)
        return sql_query
    except Exception as e:
        return f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="Spider SQL Generator - Korean", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # ๐Ÿ•ท๏ธ Spider SQL Generator - Korean
    
    ํ•œ๊ตญ์–ด ์งˆ๋ฌธ์„ SQL ์ฟผ๋ฆฌ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” Llama 3.1 8B ๋ชจ๋ธ์ž…๋‹ˆ๋‹ค.
    
    ## ๐Ÿ“Š ์„ฑ๋Šฅ
    - **Exact Match**: 42.65%
    - **Execution Accuracy**: 65.47%
    - **Training**: Spider ๋ฐ์ดํ„ฐ์…‹ (ํ•œ๊ตญ์–ด ๋ฒˆ์—ญ)
    """)
    
    with gr.Row():
        with gr.Column():
            db_id_input = gr.Textbox(
                label="๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ID",
                placeholder="์˜ˆ: department_management",
                value="department_management"
            )
            
            question_input = gr.Textbox(
                label="์งˆ๋ฌธ (ํ•œ๊ตญ์–ด)",
                placeholder="์˜ˆ: ๊ฐ ๋ถ€์„œ๋ณ„ ์ง์› ์ˆ˜๋ฅผ ๋ณด์—ฌ์ฃผ์„ธ์š”.",
                lines=2
            )
            
            with gr.Accordion("์Šคํ‚ค๋งˆ ์ •๋ณด (์„ ํƒ์‚ฌํ•ญ)", open=False):
                schema_input = gr.Textbox(
                    label="์ปค์Šคํ…€ ์Šคํ‚ค๋งˆ",
                    placeholder="์ปค์Šคํ…€ ์Šคํ‚ค๋งˆ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”. ๋น„์›Œ๋‘๋ฉด ์˜ˆ์ œ ์Šคํ‚ค๋งˆ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.",
                    lines=10
                )
            
            submit_btn = gr.Button("SQL ์ƒ์„ฑ", variant="primary", size="lg")
        
        with gr.Column():
            output = gr.Textbox(
                label="์ƒ์„ฑ๋œ SQL ์ฟผ๋ฆฌ",
                lines=4,
                elem_classes=["code"]
            )
            
            gr.Markdown("""
            ### ๐Ÿ’ก ์‚ฌ์šฉ ํŒ
            - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ID๋Š” ์˜ˆ์ œ์—์„œ ์„ ํƒํ•˜๊ฑฐ๋‚˜ ์ง์ ‘ ์ž…๋ ฅํ•˜์„ธ์š”
            - ์งˆ๋ฌธ์€ ํ•œ๊ตญ์–ด๋กœ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์ž‘์„ฑํ•˜์„ธ์š”
            - ์Šคํ‚ค๋งˆ ์ •๋ณด๋Š” ์„ ํƒ์‚ฌํ•ญ์ž…๋‹ˆ๋‹ค
            """)
    
    # Examples
    gr.Markdown("### ๐Ÿ“š ์˜ˆ์ œ (ํด๋ฆญํ•˜์—ฌ ์‚ฌ์šฉ)")
    gr.Examples(
        examples=[
            [ex["db_id"], ex["question"], ex["schema"]] for ex in examples
        ],
        inputs=[db_id_input, question_input, schema_input],
        outputs=output,
        fn=process_question,
        cache_examples=False
    )
    
    # Submit action
    submit_btn.click(
        fn=process_question,
        inputs=[question_input, db_id_input, schema_input],
        outputs=output
    )
    
    # Model info
    gr.Markdown(f"""
    ---
    ### ๐Ÿค– ๋ชจ๋ธ ์ •๋ณด
    - **Hugging Face**: [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME})
    - **Base Model**: Llama 3.1 8B
    - **Fine-tuning**: LoRA with Unsloth
    - **Dataset**: Spider (Korean translated)
    """)

# Launch the app
if __name__ == "__main__":
    demo.launch(share=True)