윤영준 윤영준 2024-07-09
Hello Yona
@6bfd9fd72e1c447e13d578c271447314c838ecaa
 
README.md (added)
+++ README.md
@@ -0,0 +1,1 @@
+# Daegu-Jeju-DIP
 
action.py (added)
+++ action.py
@@ -0,0 +1,201 @@
+
+from flask_restx import Resource, Api, Namespace, fields,reqparse
+from fog_model.fog_predict import fog_classfication
+from fog_model.fog_model import darkchannel
+from flask import request,jsonify
+from flask import Flask, render_template, request
+from werkzeug.utils import secure_filename
+import os
+from haversine import haversine
+from database.database import DB
+import torch
+from PIL import Image
+from pothole_model.pothole import pothole
+from datetime import datetime
+import jwt
+
+
+paths = os.getcwd()
+
+Action = Namespace(
+    name="Action",
+    description="노드 분석을 위해 사용하는 api.",
+)
+
+def find_node(gps_address_y,gps_address_x):
+  db=DB()
+  nn_end = None
+  end_delta = float("inf")
+  value=0.0001
+  near_nodes=[]
+  while near_nodes==[]:
+    value=value*10
+    near_nodes=db.db_get_near_node(gps_address_y,gps_address_x,value)
+    
+  for n in near_nodes:
+    e_dist = haversine((gps_address_x,gps_address_y), n)
+    if e_dist < end_delta :
+      nn_end = n
+      end_delta = e_dist
+  return nn_end
+
+
+
+@Action.route('/image_summit')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def post(self):
+      if request.method == 'POST':
+         current_time = datetime.now()
+         timestamp = current_time.strftime("%Y%m%d%H%M%S")
+# 시간을 원하는 형식으로 포맷팅하기 (예: 년-월-일 시:분:초)
+         formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
+          # 포맷팅된 현재 시간 출력
+         token = request.headers.get('Authorization')
+         print(token)
+         #print(token)
+         if not token:
+             return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'})
+        
+         else:
+            # Decode the token to verify it
+            decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
+            print(decoded_token)
+            user_id = decoded_token['id']
+         print("현재 시간,저장요청:", formatted_time)
+         f = request.files['file']
+         save_path = f"images/{timestamp}/{user_id}"
+         os.makedirs(save_path, exist_ok=True)
+         new_filename = f"{save_path}/{user_id}_{timestamp}.jpg"
+         print(f)
+         f.save(new_filename)
+         print("저장완료", formatted_time)
+
+         return {
+                'save': 'done'  # str으로 반환하여 return
+            }, 200
+
+
+
+@Action.route('/image_anal')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def post(self):
+      if request.method == 'POST':
+         current_time = datetime.now()
+         formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
+         print("현재 시간:", formatted_time)
+
+
+         fc = fog_classfication()
+         dir = os.getcwd()
+         filename = request.json['filename']
+         file_type = request.json['file_type']
+         gps_address_x = float(request.json['gps_x'])
+         gps_address_y = float(request.json['gps_y'])
+         total_path = dir+ "\\"+ filename + file_type
+         model_fc= fc.predict(total_path)
+         
+         #model_yolo= torch.hub.load(paths +'/yolov5/', 'custom', path=paths+'/yolov5/best.pt', source='local')
+         #im = Image.open(total_path)
+         #results = model_yolo(im)
+         #li_detect=list(results.pandas().xyxy[0]['name'])
+         if model_fc == "normal":
+          #if 'vest' in li_detect and 'cone' in li_detect:
+            nn_end = find_node(gps_address_y,gps_address_x)
+            return {
+                'node': nn_end,  
+                'fog' : 'normal',
+                'construction' : 'construction'
+            }, 200
+            '''
+          #else:
+            return {
+                'node': None,  
+                'fog' : 'normal',
+                'construction' : 'normal'
+            }, 200
+            '''
+         else:
+           # if 'vest' in li_detect and 'cone' in li_detect:
+              nn_end = find_node(gps_address_y,gps_address_x)
+              db=DB()
+              current_time = datetime.now()
+              formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
+              db.db_add_report(filename,gps_address_x,gps_address_y)
+              print("현재 시간:", formatted_time)
+              return {
+                'node': nn_end,  
+                'fog' : 'fog',
+                'construction' : 'construction'
+            }, 200
+              
+              '''
+            #else:
+              nn_end = find_node(gps_address_y,gps_address_x)
+              return {
+                'node': nn_end,  
+                'fog' : 'fog',
+                'construction' : 'normal'
+              }, 200
+'''
+              
+@Action.route('/pothole_report')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def post(self):
+      if request.method == 'POST':
+         pc = pothole()
+         dir = os.getcwd()
+         report_id = request.json['report_id']
+         pothole_id = request.json['pothole_id']
+         pothole_x = float(request.json['pothole_x'])
+         pothole_y = float(request.json['pothole_y'])
+         pc.report(report_id,pothole_id,pothole_x,pothole_y)       
+         return {
+                'report': 'done'  # str으로 반환하여 return
+            }, 200
+
+@Action.route('/gps_update')
+class fileUpload(Resource):
+    def post(self):
+        db = DB()
+        data = request.get_json()
+        timestamp = data['timestamp']
+        trip_id = data['trip_id']
+        location_x = float(data['location_x'])
+        location_y = float(data['location_y'])
+        token = request.headers.get('Authorization')
+        print(token)
+        #print(token)
+        if not token:
+            return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'})
+        
+        else:
+            # Decode the token to verify it
+            decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
+            print(decoded_token)
+            user_id = decoded_token['id']
+        
+        # GPS 데이터베이스에 삽입
+        db.insert_gps_data(trip_id, location_x, location_y, user_id, timestamp)
+        return jsonify({'result': 'success'})
+            
+
+         
+@Action.route('/pothole_display')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def get(self):
+      if request.method == 'GET':
+         pc = pothole()
+         dir = os.getcwd()
+         #timestamp = request.json['timestamp']
+         value=pc.display()       
+         return {
+                'pothole': list(value)  # str으로 반환하여 return
+            }, 200
 
app.py (added)
+++ app.py
@@ -0,0 +1,32 @@
+from flask import Flask, request, abort, jsonify
+from flask_restx import Api
+from auth import Auth
+from trip import Trip
+from action import Action
+from flask_caching import Cache
+import json
+
+app = Flask(__name__)
+cache = Cache(app, config={'CACHE_TYPE': 'simple'})
+
+print("Api Start")
+api = Api(app,
+          version='0.1',
+          title="trafficagent",
+          description="API Server",
+          terms_url="/",
+          contact="dhlim@takensoft.co.kr",
+          license="MIT")
+
+print("Api Started")
+api.add_namespace(Trip, '/trip')
+print("Api Add Trip")
+
+api.add_namespace(Auth, '/auth')
+print("Api Add Auth")
+
+api.add_namespace(Action, '/action')
+
+if __name__ == "__main__":
+    app.run(debug=True, host='192.168.0.195', port=15857)
+    print("Flask Start")
 
auth.py (added)
+++ auth.py
@@ -0,0 +1,121 @@
+import hashlib
+from flask import request,jsonify,render_template,redirect,url_for
+from flask_restx import Resource, Api, Namespace, fields
+from database.database import DB
+import datetime
+import jwt
+
+
+
+
+
+users = {}
+
+Auth = Namespace(
+    name="Auth",
+    description="사용자 인증을 위한 API",
+)
+
+
+user_fields = Auth.model('User', {  # Model 객체 생성
+    'id': fields.String(description='a User Name', required=True, example="id")
+})
+
+
+user_fields_auth = Auth.inherit('User Auth', user_fields, {
+    'password': fields.String(description='Password', required=True)
+
+})
+
+user_fields_register = Auth.inherit('User reigster', user_fields, {
+    'password': fields.String(description='Password', required=True),'email': fields.String(description='email', required=True),'user_sex': fields.String(description='sex', required=True),'phone': fields.String(description='phone', required=True)
+
+})
+
+
+
+@Auth.route('/id')
+class AuthCheck(Resource):
+    @Auth.doc(responses={200: 'Success'})
+    @Auth.doc(responses={500: 'Register Failed'})
+    def post(self):
+        db=DB()
+        id = request.json['id']
+        value=db.db_check_id(id)
+        if value != None:
+            return {
+                "message": "중복 아이디가 있습니다"
+            }, 500
+        else:
+            return {
+                'message': '사용가능한 아이디입니다'  # str으로 반환하여 return
+            }, 200
+
+
+
+
+@Auth.route('/register')
+class AuthRegister(Resource):
+    @Auth.expect(user_fields_register)
+    @Auth.doc(responses={200: 'Success'})
+    @Auth.doc(responses={500: 'Register Failed'})
+    def post(self):
+        db=DB()
+        id_ = request.json['id']
+        password = request.json['password']
+        user_email = request.json['email']
+        sex = request.json['sex']
+        phone = request.json['phone']
+        pw_has = hashlib.sha256(password.encode('utf-8')).hexdigest()
+        db_check_duplicate = db.db_check_id(id_)
+        if db_check_duplicate != None:
+            return {
+                "message" : "Register Failed : duplicate ID"
+            }, 500
+        db_login_success_flag=db.db_login(id_,password)
+        if db_login_success_flag != None:
+            return {
+                "message": "Register Failed"
+            }, 500
+        else:
+            db.db_add_id(id,pw_has,user_email,sex,phone)
+            return {
+                'Authorization': id  # str으로 반환하여 return
+            }, 200
+
+@Auth.route('/login')
+class AuthLogin(Resource):
+    @Auth.expect(user_fields_auth)
+    @Auth.doc(responses={200: 'Success'})
+    @Auth.doc(responses={404: 'User Not Found'})
+    @Auth.doc(responses={500: 'Auth Failed'})
+    def post(self):
+        db=DB()
+        id = request.json['id']
+        password = request.json['password']
+        #CRITICAL ... WHY? WHY?
+        # ... hashing should be handled at client, not server... 
+        pw_hash = hashlib.sha256(password.encode('utf-8')).hexdigest()
+        result = db.db_login(id,pw_hash)
+        if result is not None:
+            payload = {
+                'id' : id,
+                'exp' : datetime.datetime.utcnow() + datetime.timedelta(days=14)
+            }
+            token = jwt.encode(payload, "secret", algorithm='HS256')
+            return jsonify({'result': 'success', 'token': token})
+        else:
+            return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})
+
+
+@Auth.route('/secession')
+class AuthSecession(Resource):
+    def post(self):
+         db=DB()
+         id = request.json['token']
+         payload = jwt.decode(id, "secret", algorithms=['HS256'])
+         db.db_delete_id(payload['id'])
+         return {'secession':'success'}
+
+
+
 
blocked_ips.json (added)
+++ blocked_ips.json
@@ -0,0 +1,1 @@
+["52.228.154.224", "118.235.81.10", "159.65.177.197", "85.204.85.178", "80.76.49.131", "172.245.131.82", "87.121.69.27", "178.128.175.240", "192.168.0.54", "146.70.199.147", "167.94.146.58", "94.156.64.121", "45.148.10.174", "165.229.169.32", "45.156.130.6", "185.59.223.68", "178.215.236.52", "209.141.32.195", "78.108.177.50", "27.0.238.68", "78.108.177.51", "27.0.238.70", "185.196.11.45", "51.159.103.12", "119.246.60.130", "151.235.201.120", "172.168.41.58", "45.88.91.41", "94.156.8.84", "172.212.61.226", "192.210.187.71", "87.236.176.109", "170.64.208.135", "103.252.136.86", "178.62.69.98", "141.98.11.15", "185.244.36.236", "134.122.117.248", "138.199.60.19", "206.168.34.180", "68.69.184.110"](파일 끝에 줄바꿈 문자 없음)
 
database/database.py (added)
+++ database/database.py
@@ -0,0 +1,215 @@
+import psycopg2 # driver 임포트
+import time
+from datetime import datetime, timedelta
+
+
+class DB():
+    def __init__(self):
+        self.conn=psycopg2.connect(
+            host='210.180.118.83',
+            dbname='TRAFFICAGNET',
+            user='takensoft',
+            password='tts96314728!@',
+            port='5432',
+            options=f'-c search_path=trafficagent'
+            ) # db에 접속
+        self.conn.autocommit=True
+        self.schema = 'trafficagent'
+    '''
+    def __init__(self):
+        self.conn=psycopg2.connect(
+            host='165.229.169.113',
+            dbname='traffic_agent',
+            user='takensoft',
+            password='ts44301236!@',
+            port='5432',
+            options="-c search_path=traffic_agent_v1") # db에 접속
+        self.conn.autocommit=True
+        '''
+    
+        
+    
+    def db_check_id(self,id):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute(f'''
+        SELECT user_id
+        FROM "{self.schema}".user_id
+        Where user_id = '{id}';
+        ''')
+        result=cur.fetchone()
+        cur.close()
+
+        return result
+
+    def db_login(self,id,pw):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute(f'''
+        SELECT user_id, user_pw, user_email, user_sex, user_phone, user_time_stamp
+        FROM "{self.schema}".user_id
+        Where user_id = '{id}' and user_pw='{pw}';
+        ''')
+        result=cur.fetchone()
+
+
+        cur.close()
+
+        return result
+
+    def db_add_id(self,user_id,user_pw,user_email,user_sex,user_phone) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        recievingtime=datetime.now()
+        d = recievingtime.isoformat(sep=' ', timespec='milliseconds')
+        # d=recievingtime.strftime("%Y-%m-%d %H:%M:%S.%f")
+        cur.execute(f'''
+        insert into "{self.schema}".user_id (user_id,user_pw,user_email,user_sex,user_phone,user_time_stamp)
+        values ('{user_id}','{user_pw}','{user_email}','{user_sex}','{user_phone}','{d}')
+        ''')
+        
+    def db_add_action(self,user_id,user_pw,user_email,user_sex,user_phone) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        recievingtime=datetime.now()
+        d = recievingtime.isoformat(sep=' ', timespec='milliseconds')
+        # d=recievingtime.strftime("%Y-%m-%d %H:%M:%S.%f")
+        cur.execute(f'''
+        insert into "{self.schema}".user_id (user_id,user_pw,user_email,user_sex,user_phone,user_time_stamp)
+        values ('{user_id}','{user_pw}','{user_email}','{user_sex}','{user_phone}','{d}')
+        ''')
+
+
+        cur.close()
+    def db_delete_id(self,user_id) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        cur.execute(f'''
+        delete
+        from "{self.schema}".user_id ui
+        where user_id  = '{user_id}'
+        ''')
+        cur.close()
+
+    def db_get_node(self):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute('''
+        select "index",source_x ,source_y,target_x,target_y," dist "
+        from "{self.schema}".node n 
+        where flcass != 'pedstrian'
+        ''')
+        result=cur.fetchall()
+
+        return result
+    
+    def db_get_dest(self,dest1):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute(f'''
+        select j.q,li.q ,li.location_cen_x_4623,li.location_cen_y_4623,li.location_exit_x_4623 ,li.location_exit_y_4623 
+        from "{self.schema}".jibun j, "{self.schema}".location_info li 
+        where j.build_num =li.build_code and (j.q='{dest1}' or li.q='{dest1}' or li.build_name_city like '{dest1}')
+        ''')
+        result=cur.fetchone()
+
+        return (float(result[4]),float(result[5]))
+    
+    def db_get_near_node(self,dest_x,dest_y,value):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute(f'''
+        select source_x, source_y 
+        from "{self.schema}".node n 
+        where {dest_x} > source_y  - {value} and {dest_x} <= source_y  + {value}
+        and {dest_y} > source_x  - {value} and {dest_y} <= source_x + {value}
+
+        ''')
+        result=cur.fetchall()
+        return result
+
+    def db_get_address(self,dest1):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute(f'''
+        select j.q,li.q ,li.location_cen_x_4623,li.location_cen_y_4623,li.location_exit_x_4623 ,li.location_exit_y_4623 
+        from "{self.schema}".jibun j, "{self.schema}".location_info li 
+        where j.build_num =li.build_code and (j.q='{dest1}' or li.q='{dest1}' or li.build_name_city like '{dest1}')
+        ''')
+        result=cur.fetchone()
+        print( (float(result[2]),float(result[3])))
+
+        return (float(result[2]),float(result[3]))
+    
+    def db_add_report(self,report_id,report_x,report_y) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        now=time.localtime()
+        d=time.strftime('%Y-%m-%d %X', now)
+        cur.execute(f'''
+        insert into "{self.schema}".report (report_id,report_x,report_y,timestamp)
+        values ('{report_id}','{report_x}','{report_y}','{d}')
+        ''')
+        
+    def db_get_near_point(self,dest_x,dest_y):
+        cur = self.conn.cursor() # 커서를 생성한다
+        now=datetime.now() 
+        d_plus=now +timedelta(hours=1)
+        d_plus=str("'"+d_plus.strftime('%Y-%m-%d %X')+"'")
+        d_minus=now -timedelta(hours=1)
+        d_minus=str("'"+d_minus.strftime('%Y-%m-%d %X')+"'")
+        cur.execute(f'''
+        select report_x, report_y
+        from "{self.schema}".report 
+        where {dest_y} > report_y  - 0.000498 and {dest_y} <= report_y  + 0.000498
+        and {dest_x} > report_x  - 0.000498 and {dest_x} <= report_x + 0.000498
+        and timestamp between {d_minus} and {d_plus};
+
+
+        ''')
+        result=cur.fetchall()
+        return result
+    
+    
+    def db_add_pothole(self,pothole_id,pothole_location_x,pothole_location_y) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        now=datetime.now() 
+        d=now.strftime('%Y-%m-%d %X')
+        cur.execute(f'''
+        insert into "{self.schema}".pothole (pothole_id,pothole_location_x,pothole_location_y,timestamp)
+        values ('{pothole_id}','{pothole_location_x}','{pothole_location_y}','{d}')
+        ''')
+        
+    def db_delete_pothole(self,dest_x,dest_y) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        now=datetime.now() 
+        d_plus=now +timedelta(hours=1)
+        d_plus=str("'"+d_plus.strftime('%Y-%m-%d %X')+"'")
+        d_minus=now -timedelta(hours=1)
+        d_minus=str("'"+d_minus.strftime('%Y-%m-%d %X')+"'")
+        cur.execute(f'''
+        delete from "{self.schema}".pothole 
+        where {dest_y} > pothole_location_y  - 0.000498 and {dest_y} <= pothole_location_y  + 0.000498
+        and {dest_x} > pothole_location_x  - 0.000498 and {dest_x} <= pothole_location_x + 0.000498
+        and timestamp between {d_minus} and {d_plus};
+        ''')
+        
+    def db_display_pothole(self) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        cur.execute(f'''
+        select report_x,report_y  from "{self.schema}".report 
+        ''')
+        result=cur.fetchall()
+        return result
+
+    def insert_gps_data(self, trip_id, location_x, location_y,user_id, timestamp):
+        cur = self.conn.cursor()
+        
+        print(trip_id, location_x, location_y, user_id)
+        trip_id = trip_id['current'] 
+        cur.execute(f'''
+        INSERT INTO "{self.schema}".gps_data (timestamp, trip_id, location_x, location_y,user_id)
+        VALUES (%s, %s, %s, %s,%s);
+        ''', (timestamp, trip_id, location_x, location_y,user_id))
+        
+        cur.close()
+        return True        
+
+
+    
 
gcity.py (added)
+++ gcity.py
@@ -0,0 +1,153 @@
+import networkx as nx
+import math
+from itertools import tee
+from numpy import Inf, Infinity, inf
+from database.database import DB
+import pandas as pd
+from haversine import haversine
+import time
+import pandas as pd
+import os
+
+paths= os.getcwd()
+
+def dist(a, b):
+    (x1, y1) = a
+    (x2, y2) = b
+    return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
+
+def swith_xy(tuples):
+    x,y=tuples
+    return (y,x)
+    
+def pairwise( iterable ):
+    """Returns an iterable access binary tuple
+    s -> (s0,s1), (s1,s2), (s2, s3), ..."""
+    a, b = tee( iterable )
+    next(b, None)
+    return zip(a, b)
+
+
+
+class path_finder():
+    def __init__(self):
+        start_time=time.time()
+        self.db=DB()
+        self.G=nx.read_gpickle(paths + '\\navigation_model\\OSM_gpickle.gpickle')
+        
+        print("done")
+        print(time.time()-start_time)
+
+
+    
+    def get_trip(self,dest1,dest2):
+
+        start_time=time.time()
+        dest1=swith_xy(self.db.db_get_dest(dest1))
+        dest2=swith_xy(self.db.db_get_dest(dest2))
+        value=0.0001
+
+        start_near_nodes=[]
+        while start_near_nodes == []:
+            value=value*10
+            start_near_nodes=self.db.db_get_near_node(dest1[1],dest1[0],value)
+        else: 
+            start_near_nodes=self.db.db_get_near_node(dest1[1],dest1[0],value)
+
+        nn_start = None
+        nn_end = None
+        start_delta = float("inf")
+        end_delta = float("inf")
+        
+
+
+        for n in start_near_nodes:
+            s_dist = haversine(dest1, n)
+            if s_dist < start_delta :
+                    nn_start = n
+                    start_delta = s_dist
+        value=0.0001
+        end_near_nodes=[]
+        while end_near_nodes==[]:
+            value=value*10
+            self.db.db_get_near_node(dest2[1],dest2[0],value)
+            end_near_nodes=self.db.db_get_near_node(dest2[1],dest2[0],value)
+
+        for n in end_near_nodes:
+            e_dist = haversine(dest2, n)
+            if e_dist < end_delta :
+                    nn_end = n
+                    end_delta = e_dist
+            
+        path = list(nx.astar_path(self.G,nn_start,nn_end,heuristic=dist,weight='length'))
+        return path
+    
+    def get_dest(self, dest1):
+        dest1=swith_xy(self.db.db_get_address(dest1))
+        return dest1
+
+db=DB()
+df = pd.read_csv('D:\\takensoft\\project2\\경산 길찾기\\경산시_체크.csv',encoding='euc-kr')
+li_start=[]
+li_dest1=[]
+for i in range(len(df)):
+    try:
+        print(i)
+        dest1=df['start'][i]
+        li_dest1.append(dest1)
+        dest1=swith_xy(db.db_get_dest(dest1))
+        value=0.0001
+        start_near_nodes=[]
+        while start_near_nodes == []:
+            value=value*10
+            start_near_nodes=db.db_get_near_node(dest1[1],dest1[0],value)
+        nn_start = None
+        start_delta = float("inf")
+        for n in start_near_nodes:
+            s_dist = haversine(dest1, n)
+            if s_dist < start_delta :
+                    nn_start = n
+                    start_delta = s_dist
+        li_start.append(nn_start)
+    except:
+        continue
+
+df_check=pd.DataFrame({'start':li_dest1,'시작지점':li_start})
+
+df_check.to_csv('test.csv',encoding='euc-kr')
+
+
+'''
+df=pd.read_csv('D:\\takensoft\\project2\\경산 길찾기\\경산시.csv',encoding='euc-kr')
+
+p=path_finder()
+li_path=[]
+for i in range(len(df)):
+    try:
+        if i%100 ==0:
+            print(i)
+            df2=pd.DataFrame(li_path)
+            df2.to_csv(f'D:\\takensoft\\project2\\경산 길찾기\\길찾기 결과{i}.csv',encoding='euc-kr')
+            li_path=[]
+        start=df['start'][i]
+        end=df['end'][i]
+        li_path.append(p.get_trip(start,end))
+    except:
+        continue
+li_start_x = []
+li_start_y = []
+li_end_x = []
+li_end_y = []
+
+db=DB()
+#df.to_csv('D:\\takensoft\\project2\\경산 길찾기\\길찾기 결과.csv',encoding='euc-kr')
+
+df=pd.read_csv('D:\\takensoft\\project2\\경산 길찾기\\경산시.csv',encoding='euc-kr')
+for i in range(len(df)):
+    li_start_x.append(db.db_get_dest(df['start'][i])[0])
+    li_start_y.append(db.db_get_dest(df['start'][i])[1])
+    li_end_x.append(db.db_get_dest(df['end'][i])[0])
+    li_end_y.append([db.db_get_dest(df['end'][i])[1]])
+df2 = pd.DataFrame({'start_point_x':li_start_x,'start_point_y':li_start_y,'end_point_x':li_end_x,'end_point_y':li_end_y})
+df2.to_csv('D:\\takensoft\\project2\\경산 길찾기\\출발지도착지좌표.csv',encoding='euc-kr')
+'''(파일 끝에 줄바꿈 문자 없음)
 
logger/logger.py (added)
+++ logger/logger.py
@@ -0,0 +1,13 @@
+from datetime import datetime
+import os
+
+if not os.path.exists("logs"):
+    os.makedirs("logs")
+    os.makedirs("logs/gunicorn")
+
+bind = "192.168.0.195:15857"
+workers = 2
+reload = True
+accesslog = f"./logs/gunicorn/access_{datetime.now().strftime('%Y-%m-%d_%H')}.log"
+errorlog = f"./logs/gunicorn/error_{datetime.now().strftime('%Y-%m-%d_%H')}.log"
+loglevel = "info"
 
requirements.txt (added)
+++ requirements.txt
@@ -0,0 +1,41 @@
+aniso8601==9.0.1
+attrs==23.2.0
+blinker==1.8.2
+cachelib==0.9.0
+click==8.1.7
+Flask==3.0.3
+Flask-Caching==2.3.0
+flask-restx==1.3.0
+haversine==2.8.1
+imageio==2.34.1
+importlib_resources==6.4.0
+itsdangerous==2.2.0
+Jinja2==3.1.4
+joblib==1.4.2
+jsonschema==4.22.0
+jsonschema-specifications==2023.12.1
+lazy_loader==0.4
+MarkupSafe==2.1.5
+networkx==3.3
+numpy==1.23.3
+opencv-python==4.10.0.82
+packaging==24.1
+pandas==2.2.2
+pillow==10.3.0
+psycopg2-binary==2.9.9
+PyJWT==2.8.0
+python-dateutil==2.9.0.post0
+pytz==2024.1
+referencing==0.35.1
+rpds-py==0.18.1
+scikit-image==0.23.2
+scikit-learn==1.5.0
+scipy==1.13.1
+six==1.16.0
+threadpoolctl==3.5.0
+tifffile==2024.5.22
+torch==1.12.1
+typing_extensions==4.12.2
+tzdata==2024.1
+Werkzeug==3.0.3
+
 
trip.py (added)
+++ trip.py
@@ -0,0 +1,78 @@
+from flask import request
+from flask_restx import Resource, Api, Namespace, fields
+from navigation_model.model_trip import path_finder
+import time
+import numpy as np
+import networkx
+
+todos = {}
+count = 1
+
+not_in_list=[]
+
+
+#trip = path_finder()
+
+
+
+Trip = Namespace(
+    name="trip",
+    description="경로 노드를 받기위한 사용하는 API.",
+)
+
+trip_fields = Trip.model('Trip', {  # Model 객체 생성
+    'path_start': fields.String(description='a Todo', required=True),'path_end' : fields.String(description='a Todo', required=True)
+})
+
+
+
+@Trip.route('/trip')
+class TripPost(Resource):
+    @Trip.expect(trip_fields)
+    @Trip.response(201, 'Success', trip_fields)
+    def post(self):
+        """경로를 받습니다"""
+        start_time=time.time()
+        start = request.json['path_start']
+        end = request.json['path_end']
+        
+        return {
+            'nodes' : trip.get_trip(start,end),
+            'start_point' : trip.get_dest(start),
+            'end_point' : trip.get_dest(end)
+            
+            
+        }, 201
+@Trip.route('/trip2')
+class TripPost(Resource):
+    @Trip.expect(trip_fields)
+    @Trip.response(201, 'Success', trip_fields)
+    def post(self):
+        """경로를 받습니다"""
+        start_time=time.time()
+        start_x = request.json['dest1_x']
+        start_y = request.json['dest1_y']
+        end = request.json['path_end']
+        return {
+            'nodes' : trip.get_trip_2(start_x,start_y,end,not_in_list),
+            'start_point' : (start_x,start_y),
+            'end_point' : trip.get_dest(end)
+            
+            
+        }, 201
+
+
+@Trip.route('/remove')
+class removenodePost(Resource):
+    def post(self):
+        """경로를 받습니다"""
+        gps_x = request.json['gps_x']
+        gps_y = request.json['gps_y']
+        trip.G.remove_node((float(gps_x),float(gps_y)))
+        not_in_list.append((float(gps_x),float(gps_y)))
+        
+        return {
+            "done" : "done"
+        }, 201
+
+
Add a comment
List