Kims12 commited on
Commit
5d429a8
·
verified ·
1 Parent(s): 94501ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -93
app.py CHANGED
@@ -5,126 +5,66 @@ import os
5
  # Cohere Command R+ 모델 ID 정의
6
  COHERE_MODEL = "CohereForAI/c4ai-command-r-plus-08-2024"
7
 
8
- def get_client(hf_token):
9
- """
10
- Cohere Command R+ 모델을 위한 InferenceClient 생성.
11
- hf_token은 Gradio secrets를 통해 제공.
12
- """
13
  if not hf_token:
14
  raise ValueError("HuggingFace API 토큰이 필요합니다.")
15
  return InferenceClient(COHERE_MODEL, token=hf_token)
16
 
17
- def respond_cohere_qna(
18
- question: str,
19
- system_message: str,
20
- max_tokens: int,
21
- temperature: float,
22
- top_p: float,
23
- hf_token: str
24
- ):
25
  """
26
- Cohere Command R+ 모델을 이용해 번의 질문(question)에 대한 답변을 반환하는 함수.
27
  """
28
- try:
29
- client = get_client(hf_token)
30
- except ValueError as e:
31
- return f"오류: {str(e)}"
32
-
33
- messages = [
34
- {"role": "system", "content": system_message},
35
- {"role": "user", "content": question}
36
- ]
37
 
38
  try:
39
- response_full = client.chat_completion(
40
- messages,
41
- max_tokens=max_tokens,
42
- temperature=temperature,
43
- top_p=top_p,
 
 
 
 
44
  )
45
- assistant_message = response_full.choices[0].message.content
46
- return assistant_message
47
  except Exception as e:
48
  return f"오류가 발생했습니다: {str(e)}"
49
 
50
- # 고급 설정 (코드 내에서만 정의)
51
- SYSTEM_MESSAGE = """##[기본규칙]
52
- 1. 반드시 한국어(한글)로 작성하라.
53
- 2. 너는 가장 주목받는 마케터이며 블로그 마케팅 전문가이다.
54
- 3. 특히 너는 '정보성(Informative)' 전문 블로그 마케팅 전문가이다.
55
- 4. 정보 제공에 초점을 맞추어 작성한다.
56
-
57
- ##[텍스트 작성 규칙]
58
- 1. 소주제를 5개로 구분하여 2000자 이상되도록 작성하라.
59
- 2. 전체 맥락을 이해하고 문장의 일관성을 유지하라.
60
- 3. 절대로 참고글을 한문장 이상 그대로 출력하지 말 것.
61
- 4. 주제와 상황에 맞는 적절한 어휘를 선택하라.
62
- 5. 한글 어휘의 난이도는 쉽게 작성하라.
63
- 6. 절대 문장의 끝에 '답니다'를 사용하지 말 것.
64
-
65
- ###[정보성 블로그 작성 규칙]
66
- 1. 독자가 얻고자 하는 유용한 정보와 흥미로운 정보를 제공하도록 작성하라.
67
- 2. 독자의 공감을 이끌어내고 궁금증을 해결하도록 작성하라.
68
- 3. 독자의 관심사를 충족시키도록 작성하라.
69
- 4. 독자에게 이득이 되는 정보를 작성하라.
70
-
71
- ##[제외 규칙]
72
- 1. 반드시 비속어 및 욕설(expletive, abusive language, slang)은 제외하라.
73
- 2. 반드시 참고글의 링크(URL)는 제외하라.
74
- 3. 참고글에서 '링크를 확인해주세요'와 같은 링크 이동의 문구는 제외하라.
75
- 4. 참고글에 있는 작성자, 화자, 유튜버, 기자(Writer, speaker, YouTuber, reporter)의 이름, 애칭, 닉네임(Name, Nkickname)은 반드시 제외하라.
76
- 5. 반드시 문장의 끝부분이 어색한 한국어 표현은 제외하라('예요', '답니다', '해요', '해주죠', '됐죠', '됐어요', '고요' 등.)
77
- """
78
- MAX_TOKENS = 4000
79
- TEMPERATURE = 0.7
80
- TOP_P = 0.95
81
-
82
  with gr.Blocks() as demo:
83
  gr.Markdown("# 블로그 생성기")
84
 
85
- # HuggingFace 토큰 (secrets 사용)
86
- hf_token = os.getenv("HF_TOKEN")
87
-
88
- # 입력 필드
89
  with gr.Row():
90
  tone = gr.Radio(
 
91
  choices=["친근하게", "일반적인", "전문적인"],
92
- label="말투바꾸기",
93
  value="일반적인"
94
  )
 
95
  ref1 = gr.Textbox(label="참조글 1", lines=3)
96
  ref2 = gr.Textbox(label="참조글 2", lines=3)
97
  ref3 = gr.Textbox(label="참조글 3", lines=3)
98
 
99
- # 결과 출력
100
- answer_output = gr.Textbox(label="생성된 블로그 글", lines=10, interactive=False)
101
 
102
- # 전송 버튼
103
- submit_button = gr.Button("생성")
104
 
105
- def generate_blog(tone, ref1, ref2, ref3):
106
- # HuggingFace 토큰은 함수 내부에서 직접 사용
107
- hf_token_value = os.getenv("HF_TOKEN")
108
- if not hf_token_value:
109
- return "HuggingFace 토큰이 설정되지 않았습니다."
110
-
111
- # 프롬프트 구성
112
- prompt = f"말투: {tone}\n참조글 1: {ref1}\n참조글 2: {ref2}\n참조글 3: {ref3}"
113
- return respond_cohere_qna(
114
- question=prompt,
115
- system_message=SYSTEM_MESSAGE,
116
- max_tokens=MAX_TOKENS,
117
- temperature=TEMPERATURE,
118
- top_p=TOP_P,
119
- hf_token=hf_token_value
120
- )
121
-
122
- submit_button.click(
123
  fn=generate_blog,
124
- inputs=[tone, ref1, ref2, ref3], # hf_token은 제외
125
- outputs=answer_output
126
  )
127
 
128
- # 메인 실행부
129
  if __name__ == "__main__":
130
- demo.launch()
 
 
 
 
 
5
  # Cohere Command R+ 모델 ID 정의
6
  COHERE_MODEL = "CohereForAI/c4ai-command-r-plus-08-2024"
7
 
8
+ # Hugging Face API 토큰을 환경 변수에서 가져옴
9
+ def get_client():
10
+ hf_token = os.getenv("HF_TOKEN")
 
 
11
  if not hf_token:
12
  raise ValueError("HuggingFace API 토큰이 필요합니다.")
13
  return InferenceClient(COHERE_MODEL, token=hf_token)
14
 
15
+ def generate_blog(tone: str, ref1: str, ref2: str, ref3: str):
 
 
 
 
 
 
 
16
  """
17
+ Cohere Command R+ 모델을 사용하여 블로그 글을 생성하는 함수
18
  """
19
+ system_message = f"""반드시 한글로 답변할 것.
20
+ 너는 최고의 비서이며 요청에 따라 주어진 말투를 사용하여 블로그를 작성한다.
21
+ 말투: {tone}.
22
+ """
23
+ question = f"참조글 1: {ref1}\n참조글 2: {ref2}\n참조글 3: {ref3}\n블로그 글을 생성하라."
 
 
 
 
24
 
25
  try:
26
+ client = get_client()
27
+ response = client.chat_completion(
28
+ messages=[
29
+ {"role": "system", "content": system_message},
30
+ {"role": "user", "content": question}
31
+ ],
32
+ max_tokens=4000,
33
+ temperature=0.7,
34
+ top_p=0.95
35
  )
36
+ return response.choices[0].message.content
 
37
  except Exception as e:
38
  return f"오류가 발생했습니다: {str(e)}"
39
 
40
+ # Gradio 인터페이스 구축
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  with gr.Blocks() as demo:
42
  gr.Markdown("# 블로그 생성기")
43
 
 
 
 
 
44
  with gr.Row():
45
  tone = gr.Radio(
46
+ label="말투 바꾸기",
47
  choices=["친근하게", "일반적인", "전문적인"],
 
48
  value="일반적인"
49
  )
50
+
51
  ref1 = gr.Textbox(label="참조글 1", lines=3)
52
  ref2 = gr.Textbox(label="참조글 2", lines=3)
53
  ref3 = gr.Textbox(label="참조글 3", lines=3)
54
 
55
+ output = gr.Textbox(label="생성된 블로그 글", lines=10, interactive=False)
 
56
 
57
+ generate_button = gr.Button("생성하기")
 
58
 
59
+ generate_button.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  fn=generate_blog,
61
+ inputs=[tone, ref1, ref2, ref3],
62
+ outputs=output
63
  )
64
 
 
65
  if __name__ == "__main__":
66
+ demo.launch()
67
+
68
+ # requirements.txt
69
+ gradio
70
+ huggingface-hub==4.44.1