File size: 3,438 Bytes
af72a8e |
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 |
import os
import requests
import gradio as gr
from datetime import datetime
from llama_cpp import Llama # GPT4ALLμ©
# βββββββββββββββββββββββββ λͺ¨λΈ λ‘λ© βββββββββββββββββββββββββ
llm = Llama(model_path="./ggjt-model.bin")
# βββββββββββββββββββββββββ NEIS API νΈμΆ ν¨μ βββββββββββββββββββββββββ
def get_school_info(region_code, school_name, api_key):
url = f"https://open.neis.go.kr/hub/schoolInfo?KEY={api_key}&Type=json&pIndex=1&pSize=1&SCHUL_NM={school_name}&ATPT_OFCDC_SC_CODE={region_code}"
res = requests.get(url)
data = res.json()
school = data.get("schoolInfo", [{}])[1].get("row", [{}])[0]
return school.get("SD_SCHUL_CODE"), school.get("ATPT_OFCDC_SC_CODE")
def get_schedule(region_code, school_code, year, month, api_key):
from_ymd = f"{year}{month:02}01"
to_ymd = f"{year}{month:02}31"
url = f"https://open.neis.go.kr/hub/SchoolSchedule?KEY={api_key}&Type=json&pIndex=1&pSize=100&ATPT_OFCDC_SC_CODE={region_code}&SD_SCHUL_CODE={school_code}&AA_FROM_YMD={from_ymd}&AA_TO_YMD={to_ymd}"
res = requests.get(url)
data = res.json()
return data.get("SchoolSchedule", [{}])[1].get("row", [])
# βββββββββββββββββββββββββ GPT4ALL μλ΅ μμ± βββββββββββββββββββββββββ
def generate_gpt_answer(user_question, events):
context = "\n".join([f"{e['EVENT_NM']} : {e['AA_YMD']}" for e in events])
prompt = f"""
### Instruction:
λ€μμ μ리μ΄λ±νκ΅μ 2024λ
7μ νμ¬μΌμ μ
λλ€:
{context}
μ§λ¬Έ: "{user_question}"
μ νμ¬μΌμ μ λ³΄λ§ μ°Έκ³ ν΄μ μ§λ¬Έμ ν΄λΉνλ λ μ§λ₯Ό μ°Ύμ, μμ°μ€λ½κ³ κ°κ²°ν νκ΅μ΄ λ¬Έμ₯μΌλ‘ λ΅ν΄μ£ΌμΈμ. μ: "2024λ
7μ 24μΌμ
λλ€."
### Response:
"""
result = ""
for output in llm(prompt, stop=["###"], stream=True):
result += output["choices"][0]["text"]
return result.strip()
# βββββββββββββββββββββββββ μ 체 μ²λ¦¬ ν¨μ βββββββββββββββββββββββββ
def answer_question(user_question):
api_key = os.environ.get("NEIS_API_KEY", "a69e08342c8947b4a52cd72789a5ecaf")
school_name = "μ리μ΄λ±νκ΅"
region_code = "R10"
year = 2024
month = 7
school_code, region_code = get_school_info(region_code, school_name, api_key)
events = get_schedule(region_code, school_code, year, month, api_key)
if not events:
return "νμ¬μΌμ μ 보λ₯Ό λΆλ¬μ€μ§ λͺ»νμ΅λλ€."
return generate_gpt_answer(user_question, events)
# βββββββββββββββββββββββββ Gradio μΈν°νμ΄μ€ βββββββββββββββββββββββββ
description = "π
μ리μ΄λ±νκ΅ 2024λ
7μ νμ¬μΌμ κΈ°λ° GPT μ±λ΄μ
λλ€. μ: 'μ¬λ¦λ°©νμ μΈμ μΌ?'"
gr.Interface(fn=answer_question,
inputs=gr.Textbox(lines=2, placeholder="μ: μ¬λ¦λ°©νμμ μΈμ μΌ?", label="μ§λ¬Έ μ
λ ₯"),
outputs=gr.Textbox(label="λ΅λ³"),
title="π GPT4ALL νμ¬μΌμ Q&A",
description=description).launch()
|