Spaces:
Runtime error
Runtime error
| from geopy.distance import geodesic | |
| from util.dbquery import connection | |
| import requests, os | |
| from datetime import datetime, timedelta | |
| def find_nearest_markets(lat, lon): | |
| conn = connection() | |
| mycursor = conn.cursor() | |
| query = "SELECT Market_name_KR, Latitude, Longitude FROM Market_Info" | |
| mycursor.execute(query) | |
| markets = mycursor.fetchall() | |
| distances = [] | |
| for market in markets: | |
| market_name, market_lat, market_lon = market | |
| distance = geodesic((lat, lon), (market_lat, market_lon)).kilometers | |
| distances.append({"์ด๋ฆ":market_name, "์๋":market_lat, "๊ฒฝ๋":market_lon, "๊ฑฐ๋ฆฌ":distance}) | |
| # ๊ฑฐ๋ฆฌ์ ๋ฐ๋ผ ์์ฅ์ ์ ๋ ฌ | |
| distances.sort(key=lambda x: x['๊ฑฐ๋ฆฌ']) | |
| return distances[:10] | |
| def get_market_location(market_name): | |
| conn = connection() | |
| #์ ๋ ฅ๋ฐ์ ์์ฅ ๋ช ์ ๋ํ ์๋์ ๊ฒฝ๋ ์ฐพ๊ธฐ | |
| mycursor1 = conn.cursor() | |
| query1 = f"SELECT Latitude, Longitude FROM Market_Info WHERE Market_name_KR = \'{market_name}\'" | |
| mycursor1.execute(query1) | |
| market_info = mycursor1.fetchall() | |
| market_lat = market_info[0][0] | |
| market_lon = market_info[0][1] | |
| return market_lat, market_lon | |
| def find_nearest_place(market_name): | |
| conn = connection() | |
| #์ ๋ ฅ๋ฐ์ ์์ฅ ๋ช ์ ๋ํ ์๋์ ๊ฒฝ๋ ์ฐพ๊ธฐ | |
| mycursor1 = conn.cursor() | |
| query1 = f"SELECT Latitude, Longitude FROM Market_Info WHERE Market_name_KR = \'{market_name}\'" | |
| mycursor1.execute(query1) | |
| market_info = mycursor1.fetchall() | |
| market_lat = market_info[0][0] | |
| market_lon = market_info[0][1] | |
| print(f"{market_name} : {market_lat}, {market_lon}") | |
| #์์ฅ๊ณผ ๊ฐ์ฅ ๊ฐ๊น์ด ๊ฑฐ๋ฆฌ์ ์ธ๊ตฌ ์ ๋ณด | |
| mycursor2 = conn.cursor() | |
| query2 = "SELECT id, Latitude, Longitude FROM Population" | |
| mycursor2.execute(query2) | |
| coordinate = mycursor2.fetchall() | |
| # # ๊ฐ์ฅ ๊ฐ๊น์ด ์ฅ์๋ช ๊ณผ ๊ฑฐ๋ฆฌ ์ด๊ธฐํ | |
| nearest_place = None | |
| min_distance = float('inf') | |
| index = 1 | |
| for id, lat, lon in coordinate: | |
| place_lat = lat | |
| place_lon = lon | |
| # ์์ฅ๊ณผ ๊ฑฐ๋ฆฌ ๊ณ์ฐ | |
| distance = geodesic((market_lat, market_lon), (place_lat, place_lon)).kilometers | |
| # ๊ฐ์ฅ ๊ฐ๊น์ด ๊ฑฐ๋ฆฌ ์ ๋ฐ์ดํธ | |
| if distance < min_distance: | |
| min_distance = distance | |
| mycursor3 = conn.cursor() | |
| query3 = f"SELECT Area_name_KR FROM Population WHERE Latitude=\'{place_lat}\' AND Longitude=\'{place_lon}\'" | |
| mycursor3.execute(query3) | |
| nearest_place = mycursor3.fetchall()[0][0] | |
| return id, nearest_place, min_distance | |
| def get_season_data_by_month(month): | |
| # ์ ์ฒ ์ ๋ณด api | |
| url = "http://211.237.50.150:7080/openapi/{}/json/Grid_20171128000000000572_1/1/1000" | |
| # API ํธ์ถ | |
| KEY = os.environ['FOOD_API'] | |
| response = requests.get(url.format(KEY), params={'M_DISTCTNS': f"{month}์"}) | |
| if response.status_code == 200: | |
| data = response.json() | |
| output = [{"์ด๋ฆ":d['PRDLST_NM'],"์ ์ฒ ":d['M_DISTCTNS'],"๊ธฐ๊ฐ":d['PRDCTN__ERA'],"์ง์ญ":d['MTC_NM']} for d in data['Grid_20171128000000000572_1']['row']] | |
| return output | |
| else: | |
| return 'API ํธ์ถ ์คํจ' | |
| def get_season_data_by_name(name): | |
| # ์ ์ฒ ์ ๋ณด api | |
| url = "http://211.237.50.150:7080/openapi/{}/json/Grid_20171128000000000572_1/1/1000" | |
| # API ํธ์ถ | |
| KEY = os.environ['FOOD_API'] | |
| response = requests.get(url.format(KEY), params={'PRDLST_NM': f"{name.split(' ')[0]}"}) | |
| if response.status_code == 200: | |
| data = response.json() | |
| if len(data['Grid_20171128000000000572_1']['row']) == 0: | |
| return {"์ด๋ฆ" : name.split(' ')[0], "์ ์ฒ " : -1, "detail" : "์ ๋ณด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค"} | |
| output = { | |
| "์ด๋ฆ" : data['Grid_20171128000000000572_1']['row'][0]['PRDLST_NM'], | |
| "์ ์ฒ " : data['Grid_20171128000000000572_1']['row'][0]['M_DISTCTNS'], | |
| "๊ธฐ๊ฐ" : data['Grid_20171128000000000572_1']['row'][0]['PRDCTN__ERA'], | |
| "์ง์ญ" : data['Grid_20171128000000000572_1']['row'][0]['MTC_NM'], | |
| "์นดํ ๊ณ ๋ฆฌ" : data['Grid_20171128000000000572_1']['row'][0]['PRDLST_CL'], | |
| "ํจ๋ฅ" : data['Grid_20171128000000000572_1']['row'][0]['EFFECT'], | |
| "๊ธฐํ" : data['Grid_20171128000000000572_1']['row'][0]['PURCHASE_MTH'] | |
| } | |
| return output | |
| else: | |
| return 'API ํธ์ถ ์คํจ' | |
| # ํน์ ์ฅ์์ ์ ๋ณด ๋๋ ๊ฐ์ฅ ๊ฐ๊น์ด ์ฅ์์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ ํจ์ | |
| def get_congestion_data(place_name, index): | |
| # ์์ธ ์ค์๊ฐ ์ธ๊ตฌ๋ฐ์ดํฐ API ์๋ํฌ์ธํธ | |
| url = 'http://openapi.seoul.go.kr:8088/{}/json/citydata_ppltn/{}/{}/{}' | |
| # API ํธ์ถ | |
| KEY = os.environ['POPULATION_API'] | |
| response = requests.get(url.format(KEY, index, index, place_name)) | |
| # API ์๋ต ํ์ธ | |
| if response.status_code == 200: | |
| data = response.json() | |
| congestion = process_congestion_data(data) | |
| return congestion | |
| else: | |
| return 'API ํธ์ถ ์คํจ' | |
| # ํผ์ก๋ ์ฒ๋ฆฌ | |
| def process_congestion_data(data): | |
| # print(data) | |
| print(data['SeoulRtd.citydata_ppltn'][0]['PPLTN_TIME']) | |
| congestion = data['SeoulRtd.citydata_ppltn'][0]['AREA_CONGEST_LVL'] | |
| print(f"{data['SeoulRtd.citydata_ppltn'][0]['AREA_NM']} : {congestion}({data['SeoulRtd.citydata_ppltn'][0]['AREA_CONGEST_MSG']})") | |
| return congestion, data['SeoulRtd.citydata_ppltn'][0]['AREA_CONGEST_MSG'] | |
| #์์ฅ ๊ท๋ชจ ๊ด๋ จ | |
| def determine_market_size(market_name): | |
| conn = connection() | |
| #์ ๋ ฅ๋ฐ์ ์์ฅ ๋ช ์ ๋ํ ์๋์ ๊ฒฝ๋ ์ฐพ๊ธฐ | |
| mycursor1 = conn.cursor() | |
| query1 = f"SELECT Building_scale, Num_of_stores FROM Market_Info WHERE Market_name_KR = \'{market_name}\'" | |
| mycursor1.execute(query1) | |
| market_info = mycursor1.fetchall() | |
| area = market_info[0][0] | |
| store_count = market_info[0][1] | |
| print(f"๋ฉด์ :{area}, ์ ํฌ์:{store_count}") | |
| # ์ ํฌ ์๋ฅผ ๊ธฐ์ค์ผ๋ก ์์ฅ์ ๊ท๋ชจ ๋ถ๋ฅ | |
| market_size = "" | |
| if store_count < 100: | |
| market_size = '์ํ' | |
| elif store_count < 500: | |
| market_size = '์คํ' | |
| elif store_count < 1000: | |
| market_size = '์ค๋ํ' | |
| else: | |
| market_size = '๋ํ' | |
| return market_size, area, store_count | |
| def get_monthly_average_price(product_name): | |
| conn = connection() | |
| try: | |
| with conn.cursor(dictionary=True) as cursor: | |
| three_years_ago = datetime.now() - timedelta(days=3*365) | |
| query = """ | |
| SELECT AVG(Product_price) AS avg_price, YEAR(UpdateDate) AS year, MONTH(UpdateDate) AS month | |
| FROM Markets | |
| WHERE Product_name = %s AND UpdateDate >= %s | |
| GROUP BY YEAR(UpdateDate), MONTH(UpdateDate) | |
| ORDER BY YEAR(UpdateDate), MONTH(UpdateDate); | |
| """ | |
| cursor.execute(query, (product_name, three_years_ago)) | |
| result = cursor.fetchall() | |
| result.reverse() | |
| monthly_prices = [{"year": row["year"], "month": row["month"], "avg_price": int(row["avg_price"])} for row in result] | |
| return monthly_prices | |
| finally: | |
| conn.close() | |
| def get_lowest_price_markets(product_name): | |
| conn = connection() | |
| try: | |
| with conn.cursor(dictionary=True) as cursor: | |
| query = """ | |
| SELECT Market_name_KR AS market, Product_price AS price, UpdateDate AS date | |
| FROM Markets | |
| WHERE Product_name = %s AND UpdateDate >= NOW() - INTERVAL 2 MONTH AND Product_price > 0 | |
| ORDER BY Product_price ASC | |
| LIMIT 3; | |
| """ | |
| cursor.execute(query, (product_name,)) | |
| result = cursor.fetchall() | |
| return result | |
| finally: | |
| conn.close() | |
| def get_all_product_names(): | |
| conn = connection() # ์์์ ์ ์ํ connection() ํจ์๋ฅผ ์ฌ์ฉํ์ฌ DB์ ์ฐ๊ฒฐ | |
| product_names = [] # ํ๋ชฉ๋ช ์ ์ ์ฅํ ๋น ๋ฆฌ์คํธ ์ด๊ธฐํ | |
| try: | |
| with conn.cursor() as cursor: | |
| # SQL ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ ๊ณ ์ ํ ํ๋ชฉ๋ช ์ ์กฐํ | |
| query = "SELECT DISTINCT Product_name FROM Markets" | |
| cursor.execute(query) | |
| # ์กฐํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ๋ณต ์ฒ๋ฆฌ | |
| for row in cursor.fetchall(): | |
| product_names.append(row[0]) # ๊ฐ ํ๋ชฉ๋ช ์ ๋ฆฌ์คํธ์ ์ถ๊ฐ | |
| finally: | |
| conn.close() # ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ ์ข ๋ฃ | |
| with open("data/products.txt", "w", encoding = "utf-8") as f: | |
| for p in product_names: | |
| if p!='s' and p!='' and p!=' ': | |
| f.write(p) | |
| f.write('\n') | |
| return product_names # ํ๋ชฉ๋ช ๋ฆฌ์คํธ ๋ฐํ | |
| def get_cheapest_products_this_month(market_name): | |
| conn = connection() | |
| try: | |
| with conn.cursor(dictionary=True) as cursor: | |
| current_year = datetime.now().year | |
| market_query = """ | |
| SELECT Product_name, AVG(Product_price) AS avg_price | |
| FROM Markets | |
| WHERE Market_name_KR = %s AND UpdateDate >= NOW() - INTERVAL 2 MONTH AND Product_price > 0 | |
| GROUP BY Product_name | |
| """ | |
| cursor.execute(market_query, (market_name,)) | |
| market_prices = cursor.fetchall() | |
| national_query = """ | |
| SELECT Product_name, AVG(Product_price) AS avg_price | |
| FROM Markets | |
| WHERE YEAR(UpdateDate) = %s AND UpdateDate >= NOW() - INTERVAL 2 MONTH AND Product_price > 0 | |
| GROUP BY Product_name | |
| """ | |
| cursor.execute(national_query, (current_year,)) | |
| national_prices = {row['Product_name']: row['avg_price'] for row in cursor.fetchall()} | |
| cheapest_products = [] | |
| for product in market_prices: | |
| national_avg_price = national_prices.get(product['Product_name']) | |
| if national_avg_price and product['avg_price'] < national_avg_price: | |
| discount_rate = (national_avg_price - product['avg_price']) / national_avg_price * 100 # ํ ์ธ์จ ๊ณ์ฐ | |
| cheapest_products.append({ | |
| '์ด๋ฆ': product['Product_name'], | |
| 'ํ ์ธ์จ': int(discount_rate), | |
| '์์ธ': int(product['avg_price']), | |
| 'ํ๊ท ': int(national_avg_price), | |
| }) | |
| # ํ ์ธ์จ์ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ๊ณ ์์ 3๊ฐ๋ง ์ ํ | |
| cheapest_products = sorted(cheapest_products, key=lambda x: x['ํ ์ธ์จ'], reverse=True)[:3] | |
| return cheapest_products | |
| finally: | |
| conn.close() | |