yongyeol commited on
Commit
4b487ce
ยท
verified ยท
1 Parent(s): 9fa516f

Create src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +111 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,113 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
 
3
  import streamlit as st
4
+ from datetime import datetime
5
+ from transformers import pipeline
6
 
7
+ # Gemma ๋ชจ๋ธ ๋กœ๋”ฉ
8
+ @st.cache_resource
9
+ def load_model():
10
+ return pipeline("text-generation", model="google/gemma-2-2b-it", max_new_tokens=512)
11
+
12
+ llm = load_model()
13
+
14
+ # ํ•™๊ต ์ •๋ณด ๋ฐ ์ผ์ • ๊ฐ€์ ธ์˜ค๊ธฐ ํ•จ์ˆ˜
15
+ def get_school_info(region_code, school_name, api_key):
16
+ 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}"
17
+ res = requests.get(url)
18
+ data = res.json()
19
+ school = data.get("schoolInfo", [{}])[1].get("row", [{}])[0]
20
+ return school.get("SD_SCHUL_CODE"), school.get("ATPT_OFCDC_SC_CODE")
21
+
22
+ def get_schedule(region_code, school_code, year, api_key):
23
+ from_ymd = f"{year}0101"
24
+ to_ymd = f"{year}1231"
25
+ url = f"https://open.neis.go.kr/hub/SchoolSchedule?KEY={api_key}&Type=json&pIndex=1&pSize=500&ATPT_OFCDC_SC_CODE={region_code}&SD_SCHUL_CODE={school_code}&AA_FROM_YMD={from_ymd}&AA_TO_YMD={to_ymd}"
26
+ res = requests.get(url)
27
+ data = res.json()
28
+ rows = data.get("SchoolSchedule", [{}])[1].get("row", [])
29
+ return rows
30
+
31
+ def summarize_schedule(rows, school_name, year):
32
+ lines = []
33
+ for row in rows:
34
+ date = row["AA_YMD"]
35
+ dt = datetime.strptime(date, "%Y%m%d").strftime("%-mๆœˆ %-dๆ—ฅ")
36
+ event = row["EVENT_NM"]
37
+ lines.append(f"{dt}: {event}")
38
+ text = "\n".join(lines)
39
+ prompt = f"{school_name}๊ฐ€ {year}๋…„๋„์— ๊ฐ€์ง€๋Š” ํ•™์‚ฌ์ผ์ •์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:\n{text}\n์ฃผ์š” ์ผ์ •์„ ๊ฐ€๋ณ€์ ์œผ๋กœ ์š”์•ฝํ•ด์ฃผ์„ธ์š”."
40
+ result = llm([{"role": "user", "content": prompt}])
41
+ return result[0]["generated_text"].replace(prompt, "").strip()
42
+
43
+ # Streamlit UI
44
+ st.set_page_config(page_title="ํ•™์‚ฌ์ผ์ • ์บ˜๋ฆฐ๋”", layout="centered")
45
+ st.title("๐Ÿ“… ํ•™์‚ฌ์ผ์ • ์บ˜๋ฆฐ๋” + AI ์š”์•ฝ")
46
+ st.markdown("NEIS API์—์„œ ํ•™์‚ฌ์ผ์ •์„ ๋ถˆ๋Ÿฌ์˜ค๊ณ  FullCalendar๋กœ ์‹œ๊ฐํ™”ํ•ฉ๋‹ˆ๋‹ค.")
47
+
48
+ region_options = {
49
+ "B10": "์„œ์šธ", "C10": "๋ถ€์‚ฐ", "D10": "๋Œ€๊ตฌ", "E10": "์ธ์ฒœ", "F10": "๊ด‘์ฃผ", "G10": "๋Œ€์ „",
50
+ "H10": "์šธ์‚ฐ", "I10": "์„ธ์ข…", "J10": "๊ฒฝ๊ธฐ", "K10": "๊ฐ•์›", "M10": "์ถฉ๋ถ", "N10": "์ถฉ๋‚จ",
51
+ "P10": "์ „๋ถ", "Q10": "์ „๋‚จ", "R10": "๊ฒฝ๋ถ", "S10": "๊ฒฝ๋‚จ", "T10": "์ œ์ฃผ"
52
+ }
53
+
54
+ with st.form("query_form"):
55
+ region = st.selectbox("์ง€์—ญ ๊ต์œก์ฒญ", options=list(region_options.keys()), format_func=lambda x: f"{region_options[x]} ({x})")
56
+ school_name = st.text_input("ํ•™๊ต๋ช…", placeholder="์˜ˆ: ์ƒ๋ฆฌ์ดˆ๋“ฑํ•™๊ต")
57
+ year = st.selectbox("๋…„๋„", options=[2022, 2023, 2024, 2025], index=2)
58
+ submitted = st.form_submit_button("๐Ÿ“… ํ•™์‚ฌ์ผ์ • ๋ถˆ๋Ÿฌ์˜ค๊ธฐ")
59
+
60
+ if submitted:
61
+ with st.spinner("์ผ์ • ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘..."):
62
+ api_key = os.environ.get("NEIS_API_KEY", "a69e08342c8947b4a52cd72789a5ecaf")
63
+ school_code, region_code = get_school_info(region, school_name, api_key)
64
+ if not school_code:
65
+ st.error("ํ•™๊ต ์ •๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
66
+ else:
67
+ schedule_rows = get_schedule(region_code, school_code, year, api_key)
68
+ if not schedule_rows:
69
+ st.info("ํ•ด๋‹น ์กฐ๊ฑด์˜ ํ•™์‚ฌ์ผ์ •์ด ์—†์Šต๋‹ˆ๋‹ค.")
70
+ else:
71
+ # ์ผ์ • ๋ฐ์ดํ„ฐ๋ฅผ HTML ์บ˜๋ฆฐ๋”์— ๋„ฃ๊ธฐ ์œ„ํ•œ JSON ์ƒ์„ฑ
72
+ events = [
73
+ {
74
+ "title": row["EVENT_NM"],
75
+ "start": datetime.strptime(row["AA_YMD"], "%Y%m%d").strftime("%Y-%m-%d")
76
+ }
77
+ for row in schedule_rows
78
+ ]
79
+
80
+ import json
81
+ event_json = json.dumps(events, ensure_ascii=False)
82
+
83
+ # FullCalendar ์‚ฝ์ž…
84
+ st.components.v1.html(f"""
85
+ <html>
86
+ <head>
87
+ <link href='https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.css' rel='stylesheet' />
88
+ <script src='https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.js'></script>
89
+ <script>
90
+ document.addEventListener('DOMContentLoaded', function() {{
91
+ var calendarEl = document.getElementById('calendar');
92
+ var calendar = new FullCalendar.Calendar(calendarEl, {{
93
+ initialView: 'dayGridMonth',
94
+ locale: 'ko',
95
+ height: 600,
96
+ events: {event_json}
97
+ }});
98
+ calendar.render();
99
+ }});
100
+ </script>
101
+ </head>
102
+ <body>
103
+ <div id='calendar'></div>
104
+ </body>
105
+ </html>
106
+ """, height=650)
107
+
108
+ with st.expander("โœจ 1๋…„์น˜ ์š”์•ฝ ๋ณด๊ธฐ", expanded=False):
109
+ if st.button("๐Ÿค– ์š”์•ฝ ์ƒ์„ฑํ•˜๊ธฐ"):
110
+ with st.spinner("Gemma ๋ชจ๋ธ์ด ์š”์•ฝ ์ค‘..."):
111
+ summary = summarize_schedule(schedule_rows, school_name, year)
112
+ st.success("์š”์•ฝ ์™„๋ฃŒ!")
113
+ st.markdown(f"**{school_name} {year}๋…„ ํ•™์‚ฌ์ผ์ • ์š”์•ฝ:**\n\n{summary}")