Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| from PyPDF2 import PdfReader | |
| import os | |
| # PDF ํ ์คํธ ๋ฏธ๋ฆฌ ์ฝ์ด์ค๊ธฐ | |
| def extract_pdf_text(pdf_paths): | |
| full_text = "" | |
| for path in pdf_paths: | |
| reader = PdfReader(path) | |
| for page in reader.pages: | |
| text = page.extract_text() | |
| if text: | |
| full_text += text + "\n" | |
| return full_text.strip() | |
| # ๋ฏธ๋ฆฌ ์ง์ ๋ PDF ๋ฌธ์๋ค | |
| pdf_context = extract_pdf_text([ | |
| "assets/Programming-Fundamentals-1570222270.pdf", | |
| "assets/1๋ถํ์ด์ฌ_๊ฐ์์๋ฃ_์ ์ฒด.pdf" | |
| ]) | |
| # Inference Client ์ค์ - ๋ชจ๋ธ ๋ณ๊ฒฝ๋จ | |
| client = InferenceClient( | |
| model="mistralai/Mistral-7B-Instruct-v0.1", | |
| token=os.getenv("HUGGINGFACEHUB_API_TOKEN") # ๋ฐ๋์ ๋ฑ๋ก ํ์ | |
| ) | |
| def respond(message, history, system_message, max_tokens, temperature, top_p): | |
| messages = [{"role": "system", "content": system_message}] | |
| # history ๊ธฐ๋ฐ message ๊ตฌ์ฑ | |
| for user_msg, bot_msg in history: | |
| if user_msg: | |
| messages.append({"role": "user", "content": user_msg}) | |
| if bot_msg: | |
| messages.append({"role": "assistant", "content": bot_msg}) | |
| # ๋ฌธ์ ๊ธฐ๋ฐ ์ง๋ฌธ ๊ตฌ์ฑ | |
| messages.append({ | |
| "role": "user", | |
| "content": f"๋ค์์ ํ์ด์ฌ ํ๋ก๊ทธ๋๋ฐ ๋ฌธ์์ ๋๋ค:\n\n{pdf_context}\n\n์ง๋ฌธ: {message}" | |
| }) | |
| response = "" | |
| for chunk in client.chat_completion( | |
| messages=messages, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| stream=True, | |
| ): | |
| delta = chunk.choices[0].delta.content | |
| if delta: | |
| response += delta | |
| yield response | |
| demo = gr.ChatInterface( | |
| fn=respond, | |
| additional_inputs=[ | |
| gr.Textbox(value="You are a helpful assistant answering based on the programming reference.", label="System message"), | |
| gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), | |
| gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), | |
| gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"), | |
| ], | |
| title="๐ ํ์ด์ฌ API ๋ ํผ๋ฐ์ค ์ฑ๋ด (Mistral ๊ธฐ๋ฐ)", | |
| description="ํ๊ตญ๊ณต๋ ์์ ์๋ฃ ๊ธฐ๋ฐ์ผ๋ก ์ง๋ฌธ์ ๋ต๋ณํ๋ ์ฑ๋ด์ ๋๋ค." | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |