File size: 5,759 Bytes
805c0cd
 
 
 
 
 
 
 
 
 
 
 
9d26c64
805c0cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09f8eff
 
 
 
 
 
 
 
 
 
9d26c64
805c0cd
 
 
9d26c64
 
805c0cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d26c64
 
 
 
805c0cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d26c64
 
805c0cd
 
 
 
9d26c64
 
 
805c0cd
 
 
 
 
 
22b2ce1
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
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import gradio as gr
import pandas as pd
import io
from torch.utils.data import DataLoader, Dataset
from torch.optim import AdamW
from sklearn.model_selection import train_test_split

# ๋ชจ๋ธ๊ณผ ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ
MODEL_NAME = "beomi/kcbert-base"
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)  # 3๊ฐœ ํด๋ž˜์Šค๋กœ ๋ณ€๊ฒฝ

# ๋ฐ์ดํ„ฐ์…‹ ํด๋ž˜์Šค ์ •์˜
class CustomDataset(Dataset):
    def __init__(self, dataframe, tokenizer, max_len=128):
        self.tokenizer = tokenizer
        self.data = dataframe
        self.max_len = max_len

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        item = self.data.iloc[index]
        description = str(item['description'])
        label = item['label']

        encoding = self.tokenizer.encode_plus(
            description,
            add_special_tokens=True,
            max_length=self.max_len,
            return_token_type_ids=False,
            padding='max_length',
            truncation=True,
            return_attention_mask=True,
            return_tensors='pt',
        )

        return {
            'input_ids': encoding['input_ids'].flatten(),
            'attention_mask': encoding['attention_mask'].flatten(),
            'labels': torch.tensor(label, dtype=torch.long)
        }

# ํ›ˆ๋ จ ๋ฐ์ดํ„ฐ ์ค€๋น„ ๋ฐ ๋ชจ๋ธ ํ›ˆ๋ จ
def train_model():
    csv_data = """description,gender
"๊ทธ๋Š” ์ถ•๊ตฌ๋ฅผ ์ •๋ง ์ข‹์•„ํ•˜๊ณ , ๊ทผ์œก์งˆ์˜ ๋ชธ๋งค๋ฅผ ๊ฐ€์กŒ๋‹ค.",๋‚จ์ž
"๊ทธ๋…€๋Š” ๊ธด ๋จธ๋ฆฌ๋ฅผ ๊ฐ€์กŒ๊ณ , ๋ถ„ํ™์ƒ‰ ์›ํ”ผ์Šค๋ฅผ ์ž…์—ˆ๋‹ค.",์—ฌ์ž
"์งง์€ ๋จธ๋ฆฌ์— ์ •์žฅ์„ ์ž…์€ ๊ทธ๋Š” ํšŒ์˜์— ์ฐธ์„ํ–ˆ๋‹ค.",๋‚จ์ž
"์•„๋ฆ„๋‹ค์šด ๋ชฉ์†Œ๋ฆฌ๋กœ ๋…ธ๋ž˜ํ•˜๋Š” ๊ทธ๋…€๋Š” ๊ฐ€์ˆ˜๋‹ค.",์—ฌ์ž
"๊ทธ์˜ ์ทจ๋ฏธ๋Š” ์ž๋™์ฐจ ์ •๋น„์™€ ์ปดํ“จํ„ฐ ๊ฒŒ์ž„์ด๋‹ค.",๋‚จ์ž
"๊ทธ๋…€๋Š” ์„ฌ์„ธํ•œ ์†๊ธธ๋กœ ์•„๊ธฐ ์ธํ˜•์„ ๋งŒ๋“ค์—ˆ๋‹ค.",์—ฌ์ž
"๊ตฐ๋Œ€์—์„œ ๋ง‰ ์ œ๋Œ€ํ•œ ๊ทธ๋Š” ์”ฉ์”ฉํ•ด ๋ณด์˜€๋‹ค.",๋‚จ์ž
"๊ทธ๋…€๋Š” ์นœ๊ตฌ๋“ค๊ณผ ์ˆ˜๋‹ค ๋– ๋Š” ๊ฒƒ์„ ์ข‹์•„ํ•œ๋‹ค.",์—ฌ์ž
"๊ฐ•๋ ฅํ•œ ๋ฆฌ๋”์‹ญ์œผ๋กœ ํŒ€์„ ์ด๋„๋Š” ๋ชจ์Šต์ด ์ธ์ƒ์ ์ด์—ˆ๋‹ค.",๋‚จ์ž
"์ž์‹ ์ด ์ง์ ‘ ๋งŒ๋“  ์ฟ ํ‚ค๋ฅผ ์ฃผ๋ณ€์— ๋‚˜๋ˆ„์–ด์ฃผ๊ณค ํ•œ๋‹ค.",์—ฌ์ž
"์ •๋ฏผ์ง€",์ฒœ์‚ฌ
"""
    
    data = pd.read_csv(io.StringIO(csv_data))
    # 3๊ฐœ ํด๋ž˜์Šค๋กœ ๋ผ๋ฒจ ๋ณ€๊ฒฝ: ๋‚จ์ž=0, ์—ฌ์ž=1, ์ฒœ์‚ฌ=2
    data['label'] = data['gender'].apply(lambda x: 0 if x == '๋‚จ์ž' else (1 if x == '์—ฌ์ž' else 2))
    train_data, _ = train_test_split(data, test_size=0.2, random_state=42)
    
    train_dataset = CustomDataset(train_data, tokenizer)
    train_loader = DataLoader(train_dataset, batch_size=2)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.to(device)
    
    optimizer = AdamW(model.parameters(), lr=5e-5)
    
    print("๋ชจ๋ธ ํ›ˆ๋ จ ์‹œ์ž‘...")
    model.train()
    for epoch in range(3):
        for batch in train_loader:
            optimizer.zero_grad()
            input_ids = batch['input_ids'].to(device)
            attention_mask = batch['attention_mask'].to(device)
            labels = batch['labels'].to(device)

            outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
            loss = outputs.loss
            loss.backward()
            optimizer.step()
        print(f"Epoch {epoch + 1} ์™„๋ฃŒ")
    
    print("๋ชจ๋ธ ํ›ˆ๋ จ ์™„๋ฃŒ!")

# ์˜ˆ์ธก ํ•จ์ˆ˜
def predict_gender(text):
    if not text.strip():
        return "ํ…์ŠคํŠธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.eval()
    
    encoding = tokenizer.encode_plus(
        text,
        add_special_tokens=True,
        max_length=128,
        return_token_type_ids=False,
        padding='max_length',
        truncation=True,
        return_attention_mask=True,
        return_tensors='pt',
    )
    
    input_ids = encoding['input_ids'].to(device)
    attention_mask = encoding['attention_mask'].to(device)

    with torch.no_grad():
        outputs = model(input_ids, attention_mask=attention_mask)
        probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)
        prediction = torch.argmax(outputs.logits, dim=1).flatten().item()
        confidence = probabilities[0][prediction].item()

    # 3๊ฐœ ํด๋ž˜์Šค ๋งคํ•‘: 0=๋‚จ์ž, 1=์—ฌ์ž, 2=์ฒœ์‚ฌ
    gender_map = {0: "๋‚จ์ž", 1: "์—ฌ์ž", 2: "์ฒœ์‚ฌ"}
    gender = gender_map[prediction]
    
    return f"์˜ˆ์ธก ์„ฑ๋ณ„: {gender} (์‹ ๋ขฐ๋„: {confidence:.2%})"

# ์•ฑ ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ ํ›ˆ๋ จ
print("์•ฑ ์ดˆ๊ธฐํ™” ์ค‘...")
train_model()

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
iface = gr.Interface(
    fn=predict_gender,
    inputs=gr.Textbox(
        lines=3, 
        placeholder="์„ฑ๋ณ„์„ ์˜ˆ์ธกํ•  ํ…์ŠคํŠธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.\n์˜ˆ: '๊ทธ๋Š” ์ถ•๊ตฌ๋ฅผ ์ข‹์•„ํ•˜๊ณ  ๊ทผ์œก์งˆ์ด๋‹ค.'",
        label="ํ…์ŠคํŠธ ์ž…๋ ฅ"
    ),
    outputs=gr.Textbox(label="์˜ˆ์ธก ๊ฒฐ๊ณผ"),
    title="๐Ÿค– AI ์„ฑ๋ณ„ ์˜ˆ์ธก๊ธฐ (3๋ถ„๋ฅ˜)",
    description="์ž…๋ ฅ๋œ ํ…์ŠคํŠธ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์„ฑ๋ณ„์„ ์˜ˆ์ธกํ•ฉ๋‹ˆ๋‹ค. (๋‚จ์ž/์—ฌ์ž/์ฒœ์‚ฌ)",
    examples=[
        ["๊ทธ๋Š” ์ถ•๊ตฌ๋ฅผ ์ •๋ง ์ข‹์•„ํ•˜๊ณ , ๊ทผ์œก์งˆ์˜ ๋ชธ๋งค๋ฅผ ๊ฐ€์กŒ๋‹ค."],
        ["๊ทธ๋…€๋Š” ๊ธด ๋จธ๋ฆฌ๋ฅผ ๊ฐ€์กŒ๊ณ , ๋ถ„ํ™์ƒ‰ ์›ํ”ผ์Šค๋ฅผ ์ž…์—ˆ๋‹ค."],
        ["์งง์€ ๋จธ๋ฆฌ์— ์ •์žฅ์„ ์ž…์€ ๊ทธ๋Š” ํšŒ์˜์— ์ฐธ์„ํ–ˆ๋‹ค."],
        ["์•„๋ฆ„๋‹ค์šด ๋ชฉ์†Œ๋ฆฌ๋กœ ๋…ธ๋ž˜ํ•˜๋Š” ๊ทธ๋…€๋Š” ๊ฐ€์ˆ˜๋‹ค."],
        ["๊ทธ๋“ค์€ ์ฑ… ์ฝ๊ธฐ๋ฅผ ์ข‹์•„ํ•˜๊ณ  ์กฐ์šฉํ•œ ์„ฑ๊ฒฉ์ด๋‹ค."],
        ["์š”๋ฆฌ์™€ ์ฒญ์†Œ๋ฅผ ๋ชจ๋‘ ์ž˜ํ•˜๋ฉฐ ์ง‘์•ˆ์ผ์„ ๋„๋งก์•„ ํ•œ๋‹ค."]
    ],
    theme=gr.themes.Soft()
)

# ์•ฑ ์‹คํ–‰
if __name__ == "__main__":
    iface.launch()