Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| # from retriever.vectordb_rerank import search_documents # ๐ง RAG ๊ฒ์๊ธฐ ๋ถ๋ฌ์ค๊ธฐ | |
| from services.rag_pipeline import rag_pipeline | |
| model_name = "dasomaru/gemma-3-4bit-it-demo" | |
| # 1. ๋ชจ๋ธ/ํ ํฌ๋์ด์ 1ํ ๋ก๋ฉ | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) | |
| # ๐ model์ CPU๋ก๋ง ๋จผ์ ์ฌ๋ฆผ (GPU ์์ง ์์) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| torch_dtype=torch.float16, # 4bit model์ด๋๊น | |
| device_map="auto", # โ ์ค์: ์๋์ผ๋ก GPU ํ ๋น | |
| trust_remote_code=True, | |
| ) | |
| # 2. ์บ์ ๊ด๋ฆฌ | |
| search_cache = {} | |
| def generate_response(query: str): | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| "dasomaru/gemma-3-4bit-it-demo", | |
| trust_remote_code=True, | |
| ) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| "dasomaru/gemma-3-4bit-it-demo", | |
| torch_dtype=torch.float16, # 4bit model์ด๋๊น | |
| device_map="auto", # โ ์ค์: ์๋์ผ๋ก GPU ํ ๋น | |
| trust_remote_code=True, | |
| ) | |
| model.to("cuda") | |
| if query in search_cache: | |
| print(f"โก ์บ์ ์ฌ์ฉ: '{query}'") | |
| return search_cache[query] | |
| # ๐ฅ rag_pipeline์ ํธ์ถํด์ ๊ฒ์ + ์์ฑ | |
| # ๊ฒ์ | |
| top_k = 5 | |
| results = rag_pipeline(query, top_k=top_k) | |
| # ๊ฒฐ๊ณผ๊ฐ list์ผ ๊ฒฝ์ฐ ํฉ์น๊ธฐ | |
| if isinstance(results, list): | |
| results = "\n\n".join(results) | |
| search_cache[query] = results | |
| # return results | |
| inputs = tokenizer(results, return_tensors="pt").to(model.device) # โ model.device | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=512, | |
| temperature=0.7, | |
| top_p=0.9, | |
| top_k=50, | |
| do_sample=True, | |
| ) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # 3. Gradio ์ธํฐํ์ด์ค | |
| demo = gr.Interface( | |
| fn=generate_response, | |
| # inputs=gr.Textbox(lines=2, placeholder="์ง๋ฌธ์ ์ ๋ ฅํ์ธ์"), | |
| inputs="text", | |
| outputs="text", | |
| title="Law RAG Assistant", | |
| description="๋ฒ๋ น ๊ธฐ๋ฐ RAG ํ์ดํ๋ผ์ธ ํ ์คํธ", | |
| ) | |
| # demo.launch(server_name="0.0.0.0", server_port=7860) # ๐ API ๋ฐฐํฌ ์ค๋น ๊ฐ๋ฅ | |
| # demo.launch() | |
| demo.launch(debug=True) | |