File size: 2,126 Bytes
e221c83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
import os
import logging

# ๋ชจ๋ธ์„ ์ €์žฅํ•  ์ „์—ญ ๋ณ€์ˆ˜
_classifier = None

def load_emotion_classifier():
    global _classifier
    # ๋ชจ๋ธ์ด ์ด๋ฏธ ๋กœ๋“œ๋˜์—ˆ๋‹ค๋ฉด, ์ฆ‰์‹œ ๋ฐ˜ํ™˜
    if _classifier is not None:
        return _classifier

    # ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜๋‹ค๋ฉด, ๋กœ๋“œ ์‹œ์ž‘
    MODEL_ID = "taehoon222/korean-emotion-classifier-final"

    logging.info(f"Hugging Face Hub ๋ชจ๋ธ '{MODEL_ID}'์—์„œ ๋ชจ๋ธ์„ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค...")
    try:
        logging.info("ํ† ํฌ๋‚˜์ด์ € ๋กœ๋”ฉ ์ค‘...")
        tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
        logging.info("๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘...")
        model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
        logging.info("Hugging Face Hub ๋ชจ๋ธ ๋กœ๋”ฉ ์„ฑ๊ณต!")
    except Exception as e:
        logging.error(f"๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘ ์˜ค๋ฅ˜: {e}")
        return None
    
    device = 0 if torch.cuda.is_available() else -1
    if device == 0:
        logging.info("Device set to use cuda (GPU)")
    else:
        logging.info("Device set to use cpu")
    
    # ๋กœ๋“œ๋œ ๋ชจ๋ธ์„ ์ „์—ญ ๋ณ€์ˆ˜์— ์ €์žฅ
    _classifier = pipeline("text-classification", model=model, tokenizer=tokenizer, device=device)
    return _classifier

def predict_emotion(text, top_k=3):
    logging.info(f"predict_emotion ํ•จ์ˆ˜ ํ˜ธ์ถœ๋จ. ํ…์ŠคํŠธ ๊ธธ์ด: {len(text) if text else 0}, top_k={top_k}")
    classifier = load_emotion_classifier()
    if not text or not text.strip():
        logging.warning("๋ถ„์„ํ•  ํ…์ŠคํŠธ๊ฐ€ ๋น„์–ด์žˆ๊ฑฐ๋‚˜ ๊ณต๋ฐฑ์ž…๋‹ˆ๋‹ค.")
        return []
    if classifier is None:
        logging.error("๊ฐ์ • ๋ถ„์„ ์—”์ง„์ด ์ค€๋น„๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
        return []
    
    try:
        logging.info(f"๋ถ„๋ฅ˜๊ธฐ ์‹คํ–‰ ์ค‘... ํ…์ŠคํŠธ: {text[:50]}...") 
        results = classifier(text, top_k=top_k)
        logging.info(f"๋ถ„๋ฅ˜ ๊ฒฐ๊ณผ (Top {top_k}): {results}")
        return results
    except Exception as e:
        logging.error(f"๊ฐ์ • ๋ถ„๋ฅ˜ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
        return []