
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
이번엔 제대로 로딩은 잘 되었지만.... 입력시 오류가 났습니다.
그래서 debug창에다가 오류도 표기했는데... 어떤지 분석해 주실 수 있나요?


import gradio as gr
import openai
# OpenAI API 키 설정
API_KEY = "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"
# OpenAI 클라이언트를 생성하여 API 호출 준비
openai_client = openai.Client(api_key=API_KEY)
# 분류할 레이블 정의
labels = [
"여성/가족",
"남성",
"성소수자",
"인종/국적",
"연령",
"지역",
"종교",
"기타 혐오",
"악플/욕설",
"clean", # 중립적인 텍스트일 경우 'clean' 레이블로 분류
]
# 시스템 프롬프트를 정의하여 GPT-4o에게 작업 설명
# 입력된 텍스트를 각 레이블로 분류하고, 각 레이블에 대한 0~1 사이의 점수를 반환하도록 요청
system_prompt = f"""Your task is to classify the input text into the following categories of hate speech and give a score from 0 to 1 for each category.
The categories are: {','.join(labels)}.
Additionally, provide a score for 'clean' if the text is neutral.
"""
def generate_answer(text):
# GPT에게 혐오 발언 카테고리 점수를 요청하기 위한 메시지 구성
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Text to classify and score: {text}"}
]
response = openai_client.chat.completions.create(
model="gpt-4o",
messages=messages,
max_tokens=1024
)
response = response.choices[0].message.content
print(response)
return response
def checkHateSpeech(text):
# GPT-4o API를 호출하여 입력 텍스트에 대해 카테고리별 점수를 가져옴
result = generate_answer(text)
# 레이블별 확률 값을 저장할 딕셔너리 초기화
probs_by_labels = {}
# 미리 정의한 레이블 리스트를 순회하면서 결과에서 해당 레이블의 점수를 추출
for label in labels:
if label in result: # GPT-4o의 응답에 레이블이 포함되어 있는지 확인
try:
# 응답에서 "레이블: 점수" 형식의 문자열을 찾아 점수만 추출
# 예를 들어 "여성/가족: 0.85"에서 0.85를 추출
score = float(result.split(f"{label}:")[1].split()[0].strip())
except (IndexError, ValueError):
# 점수를 추출하는 과정에서 에러가 발생하면 기본값 0.0을 사용
score = 0.0
else:
# 결과에 해당 레이블이 없으면 기본값 0.0으로 설정
score = 0.0
# 레이블과 해당 점수를 딕셔너리에 저장
probs_by_labels[label] = score
# 레이블별 확률 값 딕셔너리를 반환
return probs_by_labels
gr.Interface(
fn=checkHateSpeech,
inputs=gr.Textbox(label="악플 탐지를 위한 텍스트"),
outputs=gr.Label(
label="결과", num_top_classes=5
),
examples=[
"사랑해요~",
"이건 정말 끔찍한 말이야.",
],
).launch(share=True, debug=True)
