Spaces:
Sleeping
Sleeping
File size: 9,549 Bytes
1e1f1bf | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | import os, uuid, json, time
import redis as redis_lib
import pandas as pd
import anthropic
from sqlalchemy import create_engine, text
from dotenv import load_dotenv
from pathlib import Path
load_dotenv(Path(__file__).parent.parent / ".env")
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
AUTOCOMPLETE_KEY = "equipment:autocomplete"
BASE_DIR = Path(__file__).parent
EXCEL_EQUIPMENT = BASE_DIR / "์์_์ค๋น.xlsx"
EXCEL_TYPES = BASE_DIR / "์์์
์ข
_๋ถ๋ฅ.xlsx"
CSV_SURVIVAL = BASE_DIR / "์์ธ_์์์
_์ ์๊ธฐ์
์์กด์จ_20260511154402.csv"
DB_URL = os.environ["DATABASE_URL"].replace("postgresql+asyncpg://", "postgresql://")
API_KEY = os.environ["ANTHROPIC_API_KEY"]
KOSIS_CATEGORIES = [
"ํ์ ์ผ๋ฐ ์์์ ์
", "ํ์ ๋ฉด ์๋ฆฌ ์ ๋ฌธ์ ", "ํ์ ์ก๋ฅ ์๋ฆฌ ์ ๋ฌธ์ ",
"ํ์ ํด์ฐ๋ฌผ ์๋ฆฌ ์ ๋ฌธ์ ", "์ค์ ์์์ ์
", "์ผ์ ์์์ ์
",
"์์์ ์์์ ์
", "๊ธฐํ ์ธ๊ตญ์ ์์์ ์
", "์ ๊ณผ์ ์
",
"ํผ์ ํ๋ฒ๊ฑฐ ์๋์์น ๋ฐ ์ ์ฌ ์์์ ์
", "์นํจ ์ ๋ฌธ์ ",
"๊น๋ฐฅ ๋ฐ ๊ธฐํ ๊ฐ์ด ์์์ ์
", "๊ฐ์ด ์์ ํฌ์ฅ ํ๋งค ์ ๋ฌธ์ ",
"์๋งฅ์ฃผ ์ ๋ฌธ์ ", "๊ธฐํ ์ฃผ์ ์
", "์ปคํผ ์ ๋ฌธ์ ", "๊ธฐํ ๋น์์ฝ์ฌ ์๋ฃ์ ์
",
]
# ๋จ๋์ฃผ์ ์ ์๋น์ค ์ ๊ณต ์ํจ -> ์๋ฝ ๋ถ๋ฅ ์ ๊ฑฐ
BUILDING_USE = {
"1์ข
๊ทผ๋ฆฐ": ["์ ๊ณผ์ ", "์นดํ", "๋ก์ง", "๋์ ํธ ์ ๋ฌธ์ ", "๋ฒ ์ด์ปค๋ฆฌ ์นดํ", "๋ธ๋ฐ์น ์นดํ",
"ํ ์คํธ๊ฐ๊ฒ", "ํฌ์ฅ๋ง์ฐจ", "์ฃฝ์ง"],
"2์ข
๊ทผ๋ฆฐ": ["๊ณ ๊ธฐ๊ตฌ์ด ์ ๋ฌธ์ ", "์ค๋ธ์ค๋ธ์ง", "ํ์ ์์ง", "์ค๊ตญ์ง", "์ผ์์ง",
"๋๋จ์์์ ์๋น", "์ธ๋ ์๋น", "ํ์ง", "๋ทํ", "๋ถ์์ง", "ํจ์คํธํธ๋",
"์นํจ ์ ๋ฌธ์ ", "ํผ์ ์ ๋ฌธ์ ", "ํ๋ฒ๊ฑฐ ์ ๋ฌธ์ ", "๊ตญ๋ฐฅ์ง (๋ํ์ฅ, ์ฅ์๊ฐ ์ก์๋ฅ)",
"๊ตญ์์ง", "๋ง๋ ์ฐ๋นต์ง", "๊ตญ๋ฌผ์๋ฆฌ ์ ๋ฌธ์ ", "์ฐ๋ญ ์ ๋ฌธ์ ", "์๊ผฌ์น ์ ๋ฌธ์ ",
"๋ง๋ผํ๊ฐ๊ฒ", "ํฌ์ผ ์ ๋ฌธ์ ", "ํ์คํ ์ ๋ฌธ์ ", "๋์๋ฝ ์ ๋ฌธ์ ",
"์กฑ๋ฐ, ๋ณด์ ์ ๋ฌธ์ ", "๊ณฑ์ฐฝ, ๋ง์ฐฝ ์ ๋ฌธ์ ", "๋ญ๋ฐ ์ ๋ฌธ์ ", "๋ฌดํ๋ฆฌํ ๊ณ ๊ธฐ์ง",
"๊ผฌ์น ์ ๋ฌธ์ ", "์ด์์นด์ผ", "ํ์ ์ด๋ฐฅ ์ง", "์คํ
์ดํฌ ์ ๋ฌธ์ ",
"์๋ฌ๋ ์ ๋ฌธ์ ", "๋ผ๋ฉ ์ ๋ฌธ์ ", "์ค๋ง์นด์ธ", "๊น๋ฐฅ ์ ๋ฌธ์ ", "์๋์์น ์ ๋ฌธ์ ","ํธํ์ง", "๊ณ ๊ธฐ์ฃผ์ ", "์์ธ๋ฐ", "์นตํ
์ผ๋ฐ"]
}
def load_equipment():
df = pd.read_excel(EXCEL_EQUIPMENT)
rows = []
for category in df.columns:
for name in df[category].dropna():
name = str(name).strip()
if name:
rows.append({"id": str(uuid.uuid4()), "name": name, "category": category})
return rows
def load_restaurant_types():
df = pd.read_excel(EXCEL_TYPES, header=None)
rows = []
for name in df[0].dropna():
name = str(name).strip()
if name:
building_use = next(
(code for code, names in BUILDING_USE.items() if name in names), "2์ข
๊ทผ๋ฆฐ"
)
rows.append({
"id": str(uuid.uuid4()),
"name": name,
"building_use_code": building_use,
})
return rows
def load_survival_rates():
df = pd.read_csv(CSV_SURVIVAL, encoding="CP949")
df = df.iloc[1:].reset_index(drop=True)
df.columns = ["์
์ข
","1y_19","2y_19","3y_19","4y_19","5y_19",
"1y_20","2y_20","3y_20","4y_20","5y_20",
"1y_21","2y_21","3y_21","4y_21","5y_21"]
num_cols = df.columns[1:]
df[num_cols] = df[num_cols].apply(pd.to_numeric, errors="coerce")
df["avg_1y"] = ((df["1y_19"]+df["1y_20"]+df["1y_21"])/3).round(2)
df["avg_3y"] = ((df["3y_19"]+df["3y_20"]+df["3y_21"])/3).round(2)
df["avg_5y"] = ((df["5y_19"]+df["5y_20"]+df["5y_21"])/3).round(2)
return df[["์
์ข
","avg_1y","avg_3y","avg_5y"]].set_index("์
์ข
").to_dict("index")
def llm_map_kosis(client, restaurant_name):
res = client.messages.create(
model="claude-opus-4-5",
max_tokens=50,
messages=[{"role": "user", "content":
f"์์์ ์
์ข
'{restaurant_name}'์ ์๋ KOSIS ํต๊ณ ์นดํ
๊ณ ๋ฆฌ ์ค ์ด๋์ ํด๋นํด?\n"
f"๊ฐ์ฅ ์ ์ฌํ ์นดํ
๊ณ ๋ฆฌ ํ๋๋ง ๊ณจ๋ผ์ ์ ํํ ๊ทธ ์ด๋ฆ๋ง ์๋ตํด. ๋ค๋ฅธ ๋ง ํ์ง ๋ง.\n\n"
f"{json.dumps(KOSIS_CATEGORIES, ensure_ascii=False)}"
}]
)
return res.content[0].text.strip()
def llm_map_equipment(client, restaurant_name, equipment_list):
res = client.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
messages=[{"role": "user", "content":
f"์์์ ์
์ข
: {restaurant_name}\n\n"
f"์๋ ์ค๋น ๋ชฉ๋ก์์ ์ด ์
์ข
์ฐฝ์
์ ํ์ํ ์ค๋น๋ฅผ ์ ํํด์ค.\n"
f"- required: ์์ผ๋ฉด ์์
๋ถ๊ฐ๋ฅํ ํ์ ์ค๋น\n"
f"- optional: ์์ผ๋ฉด ์ข์ง๋ง ์์ด๋ ๋๋ ์ค๋น\n"
f"- weight: ํด๋น ์ค๋น๊ฐ ์
์ข
ํน์ฑ์ ์ผ๋ง๋ ๋ํํ๋์ง (0.1 ~ 1.0)\n\n"
f"์ค๋น ๋ชฉ๋ก:\n{json.dumps(equipment_list, ensure_ascii=False)}\n\n"
f"๋ฐ๋์ ์๋ JSON ํ์์ผ๋ก๋ง ์๋ตํด. ๋ค๋ฅธ ๋ง ํ์ง ๋ง.\n"
f'[{{"name": "์ค๋น๋ช
", "is_required": true, "weight": 0.9}}]'
}]
)
raw = res.content[0].text.strip().replace("```json","").replace("```","").strip()
print(f" RAW: {raw[:200]}")
return json.loads(raw)
def insert_equipment(engine, rows):
with engine.begin() as conn:
for r in rows:
conn.execute(text(
"INSERT INTO equipment (id, name, category) VALUES (:id, :name, :category) ON CONFLICT (name) DO NOTHING"
), r)
print(f"[equipment] {len(rows)}๊ฐ ์๋ฃ")
def insert_restaurant_types(engine, rows):
with engine.begin() as conn:
for r in rows:
conn.execute(text(
"INSERT INTO restaurant_types (id, name, building_use_code) VALUES (:id, :name, :building_use_code) ON CONFLICT (name) DO NOTHING"
), r)
print(f"[restaurant_types] {len(rows)}๊ฐ ์๋ฃ")
def update_kosis_and_survival(engine, rt_rows, survival_rates, client):
with engine.begin() as conn:
for r in rt_rows:
kosis_cat = llm_map_kosis(client, r["name"])
sv = survival_rates.get(kosis_cat, {})
conn.execute(text("""
UPDATE restaurant_types
SET kosis_category=:kosis, survival_rate_1y=:s1, survival_rate_3y=:s3, survival_rate_5y=:s5
WHERE id=:id
"""), {"id": r["id"], "kosis": kosis_cat,
"s1": sv.get("avg_1y"), "s3": sv.get("avg_3y"), "s5": sv.get("avg_5y")})
print(f" {r['name']} โ {kosis_cat}")
time.sleep(0.3)
print("[KOSIS ๋งคํ + ์์กด์จ ์๋ฃ]")
def insert_equipment_map(engine, rt_rows, eq_rows, client):
eq_names = [e["name"] for e in eq_rows]
eq_by_name = {e["name"]: e["id"] for e in eq_rows}
with engine.begin() as conn:
for r in rt_rows:
print(f" ๋งคํ ์ค: {r['name']}")
try:
items = llm_map_equipment(client, r["name"], eq_names)
except Exception as e:
print(f" [ERROR] {r['name']}: {e}")
import traceback; traceback.print_exc()
continue
for item in items:
eq_id = eq_by_name.get(item["name"])
if not eq_id:
continue
conn.execute(text("""
INSERT INTO restaurant_equipment_map (restaurant_type_id, equipment_id, is_required, weight)
VALUES (:rt_id, :eq_id, :req, :w)
ON CONFLICT DO NOTHING
"""), {"rt_id": r["id"], "eq_id": eq_id,
"req": item.get("is_required", True), "w": item.get("weight", 1.0)})
time.sleep(0.5)
print("[restaurant_equipment_map ์๋ฃ]")
def cache_equipment_to_redis(eq_rows):
r = redis_lib.from_url(REDIS_URL, decode_responses=True)
pipe = r.pipeline()
pipe.delete("equipment:autocomplete")
for eq in eq_rows:
name = eq["name"]
pipe.zadd("equipment:autocomplete", {name: 0})
pipe.hset(f"equipment:detail:{name}", mapping={
"id": eq["id"],
"category": eq["category"],
})
pipe.execute()
r.close()
print(f"[Redis] equipment:autocomplete {len(eq_rows)}๊ฐ ์บ์ฑ ์๋ฃ")
def main():
print("=== seed_data.py ์์ ===")
client = anthropic.Anthropic(api_key=API_KEY)
engine = create_engine(DB_URL)
eq_rows = load_equipment()
insert_equipment(engine, eq_rows)
cache_equipment_to_redis(eq_rows)
rt_rows = load_restaurant_types()
insert_restaurant_types(engine, rt_rows)
survival_rates = load_survival_rates()
update_kosis_and_survival(engine, rt_rows, survival_rates, client)
with engine.connect() as conn:
result = conn.execute(text("SELECT id, name FROM equipment"))
eq_rows = [{"id": str(r.id), "name": r.name} for r in result.fetchall()]
insert_equipment_map(engine, rt_rows, eq_rows, client)
print("=== ์๋ฃ ===")
if __name__ == "__main__":
main() |