File size: 15,324 Bytes
747ccea fe67895 90e9b67 0fbbd89 f779047 54a4802 3c698c1 0e5afe0 0fbbd89 6da265e c36dc6b 6da265e c36dc6b 6da265e 0fbbd89 90e9b67 c3ae439 90e9b67 c36dc6b de57dc5 6da265e 747ccea 0fbbd89 8f71308 0fbbd89 d8a457b 0fbbd89 d8a457b 0fbbd89 ca69132 1071ed2 0fbbd89 d8a457b 0fbbd89 f6e3821 1071ed2 747ccea 90e9b67 0fbbd89 d8a457b 4f42976 90e9b67 4f42976 90e9b67 c3ae439 90e9b67 8321675 0fbbd89 4f42976 0fbbd89 f6e3821 0fbbd89 884361c 0fbbd89 4f42976 f6e3821 4f42976 c8b6371 ca69132 0fbbd89 ca69132 d8a457b ca69132 f6e3821 0fbbd89 c8b6371 d8a457b 4f42976 d8a457b 4f42976 c8b6371 f6e3821 0fbbd89 f6e3821 2bb387f f6e3821 0fbbd89 f6e3821 c8b6371 f6e3821 c8b6371 f6e3821 0fbbd89 66fa514 8f71308 3c698c1 2bb387f f6e3821 8f71308 f6e3821 dea516f 3c698c1 66fa514 4f42976 dea516f 3c698c1 2442eca 1071ed2 3c698c1 6fd59f1 884361c d8a457b 884361c 71edfae 95a32d4 dea516f 71edfae 3c698c1 2013128 1071ed2 0fbbd89 3c698c1 d8a457b 0fbbd89 d8a457b 3c698c1 1071ed2 3c698c1 2013128 0fbbd89 d8a457b 2013128 d8a457b 3c698c1 1071ed2 3c698c1 d8a457b 2013128 3c698c1 707bf52 1071ed2 707bf52 1071ed2 3c698c1 1071ed2 6fd59f1 884361c 95a32d4 884361c c8b6371 ca69132 c8b6371 f6e3821 ca69132 c8b6371 ca69132 884361c ca69132 884361c ca69132 884361c 6fd59f1 dea516f 3c698c1 747ccea 0fbbd89 |
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 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 |
import gradio as gr
from huggingface_hub import InferenceClient
import os
import pandas as pd
from typing import List, Dict, Tuple
# μΆλ‘ API ν΄λΌμ΄μΈνΈ μ€μ
hf_client = InferenceClient(
"CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN")
)
def load_code(filename: str) -> str:
try:
with open(filename, 'r', encoding='utf-8') as file:
return file.read()
except FileNotFoundError:
return f"{filename} νμΌμ μ°Ύμ μ μμ΅λλ€."
except Exception as e:
return f"νμΌμ μ½λ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
def load_parquet(filename: str) -> str:
try:
df = pd.read_parquet(filename, engine='pyarrow')
return df.head(10).to_markdown(index=False)
except FileNotFoundError:
return f"{filename} νμΌμ μ°Ύμ μ μμ΅λλ€."
except Exception as e:
return f"νμΌμ μ½λ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
# μ½λ νμΌ λ‘λ
fashion_code = load_code('fashion.cod')
uhdimage_code = load_code('uhdimage.cod')
MixGEN_code = load_code('mgen.cod')
def respond(
message: str,
history: List[Dict[str, str]],
system_message: str = "",
max_tokens: int = 1000,
temperature: float = 0.7,
top_p: float = 0.9,
parquet_data: Dict = None
) -> str:
# μμ€ν
ν둬ννΈ μ€μ
system_prefix = """λ°λμ νκΈλ‘ λ΅λ³ν κ². λλ μ£Όμ΄μ§ λ°μ΄ν°λ₯Ό κΈ°λ°μΌλ‘ "μλΉμ€ μ¬μ© μ€λͺ
λ° μλ΄, Q&Aλ₯Ό νλ μν μ΄λ€". μμ£Ό μΉμ νκ³ μμΈνκ² Markdown νμμΌλ‘ μμ±νλΌ. λλ λ°μ΄ν°λ₯Ό κΈ°λ°μΌλ‘ μ¬μ© μ€λͺ
λ° μ§μ μλ΅μ μ§ννλ©°, μ΄μ©μμκ² λμμ μ£Όμ΄μΌ νλ€. μ΄μ©μκ° κΆκΈν΄ν λ§ν λ΄μ©μ μΉμ νκ² μλ €μ£Όλλ‘ νλΌ. λ°μ΄ν° μ 체 λ΄μ©μ λν΄μλ 보μμ μ μ§νκ³ , λ―Όκ°ν μ 보λ 곡κ°νμ§ λ§λΌ."""
# Parquet λ°μ΄ν° ν¬ν¨
if parquet_data:
df = pd.read_json(parquet_data)
parquet_content = df.head(10).to_markdown(index=False)
system_prefix += f"\n\nμ
λ‘λλ Parquet νμΌ λ΄μ©:\n```markdown\n{parquet_content}\n```"
# μμ€ν
λ©μμ§μ λν κΈ°λ‘ κ²°ν©
messages = [{"role": "system", "content": system_prefix}]
for chat in history:
messages.append({"role": chat['role'], "content": chat['content']})
# λ§μ§λ§ λ©μμ§λ μ΄λ―Έ historyμ μμΌλ―λ‘ μΆκ°νμ§ μμ΅λλ€.
try:
# λͺ¨λΈμ λ©μμ§ μ μ‘ λ° μλ΅ λ°κΈ°
response = ""
for msg in hf_client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
token = msg.choices[0].delta.get('content', None)
if token:
response += token
yield response
except Exception as e:
yield f"μΆλ‘ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
def upload_csv(file_path: str) -> Tuple[str, str]:
try:
# CSV νμΌ μ½κΈ°
df = pd.read_csv(file_path, sep=',')
# νμ μ»¬λΌ νμΈ
required_columns = {'id', 'text', 'label', 'metadata'}
available_columns = set(df.columns)
missing_columns = required_columns - available_columns
if missing_columns:
return f"CSV νμΌμ λ€μ νμ 컬λΌμ΄ λλ½λμμ΅λλ€: {', '.join(missing_columns)}", ""
# λ°μ΄ν° ν΄λ μ§
df.drop_duplicates(inplace=True)
df.fillna('', inplace=True)
# λ°μ΄ν° μ ν μ΅μ ν
df = df.astype({'id': 'int32', 'text': 'string', 'label': 'category', 'metadata': 'string'})
# Parquet νμΌλ‘ λ³ν
parquet_filename = os.path.splitext(os.path.basename(file_path))[0] + '.parquet'
df.to_parquet(parquet_filename, engine='pyarrow', compression='snappy')
return f"{parquet_filename} νμΌμ΄ μ±κ³΅μ μΌλ‘ μ
λ‘λλκ³ λ³νλμμ΅λλ€.", parquet_filename
except Exception as e:
return f"CSV νμΌ μ
λ‘λ λ° λ³ν μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}", ""
def upload_parquet(file_path: str) -> Tuple[str, str, str]:
try:
# Parquet νμΌ μ½κΈ°
df = pd.read_parquet(file_path, engine='pyarrow')
# MarkdownμΌλ‘ λ³ννμ¬ λ―Έλ¦¬λ³΄κΈ°
parquet_content = df.head(10).to_markdown(index=False)
# DataFrameμ JSONμΌλ‘ λ³ν
parquet_json = df.to_json()
return "Parquet νμΌμ΄ μ±κ³΅μ μΌλ‘ μ
λ‘λλμμ΅λλ€.", parquet_content, parquet_json
except Exception as e:
return f"Parquet νμΌ μ
λ‘λ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}", "", ""
def text_to_parquet(text: str) -> Tuple[str, str, str]:
try:
# ν
μ€νΈλ₯Ό DataFrameμΌλ‘ λ³ν (κ° νμ μ½€λ§λ‘ ꡬλΆ)
data = [line.split(',') for line in text.strip().split('\n')]
df = pd.DataFrame(data, columns=['id', 'text', 'label', 'metadata'])
# λ°μ΄ν° μ ν μ΅μ ν
df = df.astype({'id': 'int32', 'text': 'string', 'label': 'category', 'metadata': 'string'})
# Parquet νμΌλ‘ λ³ν
parquet_filename = 'text_to_parquet.parquet'
df.to_parquet(parquet_filename, engine='pyarrow', compression='snappy')
# Parquet νμΌ λ΄μ© 미리보기
parquet_content = load_parquet(parquet_filename)
return f"{parquet_filename} νμΌμ΄ μ±κ³΅μ μΌλ‘ λ³νλμμ΅λλ€.", parquet_content, parquet_filename
except Exception as e:
return f"ν
μ€νΈ λ³ν μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}", "", ""
# CSS μ€μ
css = """
footer {
visibility: hidden;
}
#chatbot-container, #chatbot-data-upload {
height: 700px;
overflow-y: scroll;
}
#chatbot-container .message, #chatbot-data-upload .message {
font-size: 14px;
}
/* μ
λ ₯μ°½ λ°°κ²½μ λ° κΈμμ λ³κ²½ */
textarea, input[type="text"] {
background-color: #ffffff; /* ν°μ λ°°κ²½ */
color: #000000; /* κ²μ μ κΈμ */
}
/* νμΌ μ
λ‘λ μμ λμ΄ μ‘°μ */
#parquet-upload-area {
max-height: 150px;
overflow-y: auto;
}
/* μ΄κΈ° μ€λͺ
κΈμ¨ ν¬κΈ° μ‘°μ */
#initial-description {
font-size: 14px;
}
"""
# Gradio Blocks μΈν°νμ΄μ€ μ€μ
with gr.Blocks(css=css) as demo:
gr.Markdown("# My RAG: LLMμ΄ λλ§μ λ°μ΄ν°λ‘ νμ΅ν μ½ν
μΈ μμ±/λ΅λ³", elem_id="initial-description")
gr.Markdown(
"### 1) λλ§μ λ°μ΄ν°λ₯Ό μ
λ ₯ λλ CSV μ
λ‘λλ‘ Parquet λ°μ΄ν°μ
μλ λ³ν 2) Parquet λ°μ΄ν°μ
μ μ
λ‘λνλ©΄, LLMμ΄ λ§μΆ€ νμ΅ λ°μ΄ν°λ‘ νμ©νμ¬ μλ΅\n"
"### Tip) 'μμ 'λ₯Ό ν΅ν΄ λ€μν νμ© λ°©λ²μ 체ννκ³ μμ©ν΄ 보μΈμ, λ°μ΄ν°μ
μ
λ‘λμ 미리보기λ 10κ±΄λ§ μΆλ ₯",
elem_id="initial-description"
)
# 첫 λ²μ§Έ ν: μ±λ΄ λ°μ΄ν° μ
λ‘λ (ν μ΄λ¦ λ³κ²½: "My λ°μ΄ν°μ
+LLM")
with gr.Tab("My λ°μ΄ν°μ
+LLM"):
gr.Markdown("### LLMκ³Ό λννκΈ°")
chatbot_data_upload = gr.Chatbot(label="μ±λ΄", type="messages", elem_id="chatbot-data-upload")
msg_data_upload = gr.Textbox(label="λ©μμ§ μ
λ ₯", placeholder="μ¬κΈ°μ λ©μμ§λ₯Ό μ
λ ₯νμΈμ...")
send_data_upload = gr.Button("μ μ‘")
with gr.Accordion("μμ€ν
ν둬ννΈ λ° μ΅μ
μ€μ ", open=False):
system_message = gr.Textbox(label="System Message", value="λλ AI μ‘°μΈμ μν μ΄λ€.")
max_tokens = gr.Slider(minimum=1, maximum=8000, value=1000, label="Max Tokens")
temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="Temperature")
top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P")
def handle_message_data_upload(
message: str,
history: List[Dict[str, str]],
system_message: str,
max_tokens: int,
temperature: float,
top_p: float,
parquet_data: str
):
history = history or []
try:
# μ¬μ©μμ λ©μμ§λ₯Ό νμ€ν 리μ μΆκ°
history.append({"role": "user", "content": message})
# μλ΅ μμ±
response_gen = respond(
message, history, system_message, max_tokens, temperature, top_p, parquet_data
)
partial_response = ""
for partial in response_gen:
partial_response = partial
# λν λ΄μ μ
λ°μ΄νΈ
display_history = history + [
{"role": "assistant", "content": partial_response}
]
yield display_history, ""
# μ΄μμ€ν΄νΈμ μλ΅μ νμ€ν 리μ μΆκ°
history.append({"role": "assistant", "content": partial_response})
except Exception as e:
response = f"μΆλ‘ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
history.append({"role": "assistant", "content": response})
yield history, ""
send_data_upload.click(
handle_message_data_upload,
inputs=[
msg_data_upload,
chatbot_data_upload,
system_message,
max_tokens,
temperature,
top_p,
gr.State(), # parquet_data_stateλ μλμμ μ
λ°μ΄νΈλ©λλ€.
],
outputs=[chatbot_data_upload, msg_data_upload],
queue=True
)
# μμ μΆκ°
with gr.Accordion("μμ ", open=False):
gr.Examples(
examples=[
["μ
λ‘λλ λ°μ΄ν°μ
μ λν΄ μμ½ μ€λͺ
νλΌ."],
["μ
λ‘λλ λ°μ΄ν°μ
νμΌμ νμ΅ λ°μ΄ν°λ‘ νμ©νμ¬, λ³Έ μλΉμ€λ₯Ό SEO μ΅μ ννμ¬ λΈλ‘κ·Έ ν¬μ€νΈ(κ°μ, λ°°κ²½ λ° νμμ±, κΈ°μ‘΄ μ μ¬ μ ν/μλΉμ€μ λΉκ΅νμ¬ νΉμ₯μ , νμ©μ², κ°μΉ, κΈ°λν¨κ³Ό, κ²°λ‘ μ ν¬ν¨)λ‘ 4000 ν ν° μ΄μ μμ±νλΌ"],
["μ
λ‘λλ λ°μ΄ν°μ
νμΌμ νμ΅ λ°μ΄ν°λ‘ νμ©νμ¬, μ¬μ© λ°©λ²κ³Ό μ°¨λ³μ , νΉμ§, κ°μ μ μ€μ¬μΌλ‘ 4000 ν ν° μ΄μ μ νλΈ μμ μ€ν¬λ¦½νΈ ννλ‘ μμ±νλΌ"],
["μ
λ‘λλ λ°μ΄ν°μ
νμΌμ νμ΅ λ°μ΄ν°λ‘ νμ©νμ¬, μ ν μμΈ νμ΄μ§ νμμ λ΄μ©μ 4000 ν ν° μ΄μ μμΈν μ€λͺ
νλΌ"],
["μ
λ‘λλ λ°μ΄ν°μ
νμΌμ νμ΅ λ°μ΄ν°λ‘ νμ©νμ¬, FAQ 20건μ μμΈνκ² μμ±νλΌ. 4000ν ν° μ΄μ μ¬μ©νλΌ."],
["μ
λ‘λλ λ°μ΄ν°μ
νμΌμ νμ΅ λ°μ΄ν°λ‘ νμ©νμ¬, νΉν μΆμμ νμ©ν κΈ°μ λ° λΉμ¦λμ€ λͺ¨λΈ μΈ‘λ©΄μ ν¬ν¨νμ¬ νΉν μΆμμ ꡬμ±μ λ§κ² νμ μ μΈ μ°½μ λ°λͺ
λ΄μ©μ μ€μ¬μΌλ‘ 4000 ν ν° μ΄μ μμ±νλΌ."],
],
inputs=msg_data_upload,
label="μμ μ ν",
)
# Parquet νμΌ μ
λ‘λλ₯Ό νλ©΄ νλ¨μΌλ‘ μ΄λ
gr.Markdown("### Parquet νμΌ μ
λ‘λ")
with gr.Row():
with gr.Column():
parquet_upload = gr.File(
label="Parquet νμΌ μ
λ‘λ", type="filepath", elem_id="parquet-upload-area"
)
parquet_upload_button = gr.Button("μ
λ‘λ")
parquet_upload_status = gr.Textbox(label="μ
λ‘λ μν", interactive=False)
parquet_preview_chat = gr.Markdown(label="Parquet νμΌ λ―Έλ¦¬λ³΄κΈ°")
parquet_data_state = gr.State()
def handle_parquet_upload(file_path: str):
message, parquet_content, parquet_json = upload_parquet(file_path)
if parquet_json:
return message, parquet_content, parquet_json
else:
return message, "", ""
parquet_upload_button.click(
handle_parquet_upload,
inputs=parquet_upload,
outputs=[parquet_upload_status, parquet_preview_chat, parquet_data_state]
)
# λ λ²μ§Έ ν: λ°μ΄ν° λ³ν (ν μ΄λ¦ λ³κ²½: "CSV to My λ°μ΄ν°μ
")
with gr.Tab("CSV to My λ°μ΄ν°μ
"):
gr.Markdown("### CSV νμΌ μ
λ‘λ λ° Parquet λ³ν")
with gr.Row():
with gr.Column():
csv_file = gr.File(label="CSV νμΌ μ
λ‘λ", type="filepath")
upload_button = gr.Button("μ
λ‘λ λ° λ³ν")
upload_status = gr.Textbox(label="μ
λ‘λ μν", interactive=False)
parquet_preview = gr.Markdown(label="Parquet νμΌ λ―Έλ¦¬λ³΄κΈ°")
download_button = gr.File(label="Parquet νμΌ λ€μ΄λ‘λ", interactive=False)
def handle_csv_upload(file_path: str):
message, parquet_filename = upload_csv(file_path)
if parquet_filename:
parquet_content = load_parquet(parquet_filename)
return message, parquet_content, parquet_filename
else:
return message, "", None
upload_button.click(
handle_csv_upload,
inputs=csv_file,
outputs=[upload_status, parquet_preview, download_button]
)
# μΈ λ²μ§Έ ν: ν
μ€νΈ to csv to parquet λ³ν (ν μ΄λ¦ λ³κ²½: "Text to My λ°μ΄ν°μ
")
with gr.Tab("Text to My λ°μ΄ν°μ
"):
gr.Markdown("### ν
μ€νΈλ₯Ό μ
λ ₯νλ©΄ CSVλ‘ λ³ν ν ParquetμΌλ‘ μλ μ νλ©λλ€.")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="ν
μ€νΈ μ
λ ₯ (κ° νμ `id,text,label,metadata` νμμΌλ‘ μ
λ ₯)",
lines=10,
placeholder="μ: 1,Sample Text,Label1,Metadata1\n2,Another Text,Label2,Metadata2"
)
convert_button = gr.Button("λ³ν λ° λ€μ΄λ‘λ")
convert_status = gr.Textbox(label="λ³ν μν", interactive=False)
parquet_preview_convert = gr.Markdown(label="Parquet νμΌ λ―Έλ¦¬λ³΄κΈ°")
download_parquet_convert = gr.File(label="Parquet νμΌ λ€μ΄λ‘λ", interactive=False)
def handle_text_to_parquet(text: str):
message, parquet_content, parquet_filename = text_to_parquet(text)
if parquet_filename:
return message, parquet_content, parquet_filename
else:
return message, "", None
convert_button.click(
handle_text_to_parquet,
inputs=text_input,
outputs=[convert_status, parquet_preview_convert, download_parquet_convert]
)
gr.Markdown("### [email protected]", elem_id="initial-description")
if __name__ == "__main__":
demo.launch()
|