calchat / app.py
yongyeol's picture
Create app.py
af72a8e verified
raw
history blame
3.44 kB
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()