dhlim / rds star
dhlim 2023-08-16
main
@54572a7b36f22e6cc5a59e747a0f11b1f56551b6
 
main_server/85CF_HD_20211018_039146.jpg (Binary) (added)
+++ main_server/85CF_HD_20211018_039146.jpg
Binary file is not shown
 
main_server/README.MD (added)
+++ main_server/README.MD
@@ -0,0 +1,0 @@
 
main_server/__pycache__/action.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/action.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/action.cpython-311.pyc (Binary) (added)
+++ main_server/__pycache__/action.cpython-311.pyc
Binary file is not shown
 
main_server/__pycache__/app.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/app.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/auth.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/auth.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/auth.cpython-311.pyc (Binary) (added)
+++ main_server/__pycache__/auth.cpython-311.pyc
Binary file is not shown
 
main_server/__pycache__/config.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/config.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/fog - 복사본.pkl (Binary) (added)
+++ main_server/__pycache__/fog - 복사본.pkl
Binary file is not shown
 
main_server/__pycache__/model_trip.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/model_trip.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/predict - 복사본.py (added)
+++ main_server/__pycache__/predict - 복사본.py
@@ -0,0 +1,30 @@
+import pickle
+from sklearn.metrics import *
+from model import darkchannel, sobel
+import pandas as pd
+import joblib
+import numpy as np
+
+
+#이미지 주소
+
+def predict(X_test):
+    svclassifier_from_pickle = joblib.load('fog.pkl')
+    
+    Y_pred = svclassifier_from_pickle.predict(X_test)
+    if Y_pred == 0:
+        print("fog")
+    else:
+        print("normal")
+    
+    #print("정확도 : ", accuracy_score(Y_test,Y_pred))
+    #print(confusion_matrix(Y_test,Y_pred))
+    #print(classification_report(Y_test,Y_pred))
+
+img = "C:/Users/lim/Desktop/data/85CF_HD_20211018_038932.jpg"
+
+alpha_map,result=darkchannel(img)
+edge = sobel(img)
+value=np.array([[result,edge]])
+predict(value)
+
 
main_server/__pycache__/todo.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/todo.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/trip.cpython-310.pyc (Binary) (added)
+++ main_server/__pycache__/trip.cpython-310.pyc
Binary file is not shown
 
main_server/__pycache__/trip.cpython-311.pyc (Binary) (added)
+++ main_server/__pycache__/trip.cpython-311.pyc
Binary file is not shown
 
main_server/action.py (added)
+++ main_server/action.py
@@ -0,0 +1,67 @@
+from flask_restx import Resource, Api, Namespace, fields
+from flask import request
+from flask import Flask, render_template, request
+from werkzeug.utils import secure_filename
+import os
+from database.database import DB
+from PIL import Image
+from datetime import datetime, timedelta
+
+paths = os.getcwd()
+
+Action = Namespace(
+    name="Action",
+    description="노드 분석을 위해 사용하는 api.",
+)
+
+
[email protected]('/image_summit')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def post(self):
+      if request.method == 'POST':
+         f = request.files['file']
+         f.save(secure_filename(f.filename))
+         return {
+                'save': 'done'  # str으로 반환하여 return
+            }, 200
+
+
+
[email protected]('/image_anal')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def post(self):
+      if request.method == 'POST':
+         db=DB()
+         dir = os.getcwd()
+         filename = request.json['filename']
+         file_type = request.json['file_type']
+         lat = float(request.json['gps_x'])
+         lon = float(request.json['gps_y'])
+         user_id = 'test'
+         action_success = True
+         action_id = 'test'
+         db.db_add_action(action_id,lat,lon,user_id,action_success)
+         return {
+                'node': (lat,lon),  
+                'rain' : 'rain',
+            }, 200
+
+              
[email protected]('/action_display')
+class fileUpload(Resource):
+    @Action.doc(responses={200: 'Success'})
+    @Action.doc(responses={500: 'Register Failed'})
+    def post(self):
+      if request.method == 'GET':
+        db = DB()
+        now=datetime.now() 
+        d=now.strftime('%Y-%m-%d %X')
+        value=db.db_display_action(d)     
+        return {
+              'report': list(value)  
+          }, 200
+         
 
main_server/app.py (added)
+++ main_server/app.py
@@ -0,0 +1,30 @@
+from flask import Flask
+from flask_restx import Api
+from auth import Auth
+from action import Action
+
+
+
+
+app = Flask(__name__)
+
+
+print("Api Start")
+api = Api(    app,
+    version='0.1',
+    title="trafficagent",
+    description="API Server",
+    terms_url="/",
+    contact="[email protected]",
+    license="MIT")
+
+
+
+api.add_namespace(Auth, '/auth')
+print("Api Add Auth")
+
+api.add_namespace(Action, '/action')
+
+if __name__ == "__main__":
+    app.run(debug=False, host='0.0.0.0', port=8080)
+    print("Flask Start")(파일 끝에 줄바꿈 문자 없음)
 
main_server/auth.py (added)
+++ main_server/auth.py
@@ -0,0 +1,114 @@
+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)
+
+})
+
+
+
[email protected]('/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
+
+
+
+
[email protected]('/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['user_sex']
+        phone = request.json['phone']
+        pw_has = hashlib.sha256(password.encode('utf-8')).hexdigest()
+        value=db.db_login(id,password)
+        if value != None:
+            return {
+                "message": "Register Failed"
+            }, 500
+        else:
+            db.db_add_id(id,pw_has,user_email,sex,phone)
+            return {
+                'Authorization': id  # str으로 반환하여 return
+            }, 200
+
[email protected]('/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']
+        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(seconds=70)
+            }
+            token = jwt.encode(payload, "secret", algorithm='HS256')
+            return jsonify({'result': 'success', 'token': token})
+        else:
+            return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})
+
+
[email protected]('/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'}
+
+
+
 
main_server/database/__pycache__/database.cpython-310.pyc (Binary) (added)
+++ main_server/database/__pycache__/database.cpython-310.pyc
Binary file is not shown
 
main_server/database/__pycache__/database.cpython-311.pyc (Binary) (added)
+++ main_server/database/__pycache__/database.cpython-311.pyc
Binary file is not shown
 
main_server/database/database.py (added)
+++ main_server/database/database.py
@@ -0,0 +1,93 @@
+import psycopg2 # driver 임포트
+import time
+from datetime import datetime, timedelta
+
+
+class DB():
+    def __init__(self):
+        self.conn=psycopg2.connect(
+            host='localhost',
+            dbname='postgres',
+            user='postgres',
+            password='ts4430!@',
+            port='5432'
+            ) # db에 접속
+        self.conn.autocommit=True
+
+    def db_check_id(self,id):
+        cur = self.conn.cursor() # 커서를 생성한다
+
+        cur.execute(f'''
+        SELECT user_id
+        FROM rds.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 rds.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() # 커서를 생성한다
+        now=time.localtime()
+        d=time.strftime('%Y-%m-%d %X', now)
+        cur.execute(f'''
+        insert into rds.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 rds.user_id ui
+        where user_id  = '{user_id}'
+        ''')
+        cur.close()
+    
+
+    
+    def db_add_action(self,action_id,lat,lon,user_id,action_success) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        now=datetime.now() 
+        d=now.strftime('%Y-%m-%d %X')
+        cur.execute(f'''
+        insert into rds.action (action_id,lat,lon,action_time_stamp,user_id,action_success)
+        values ('{action_id}','{lat}','{lon}','{d}','{user_id}','{action_success}')
+        ''')
+        
+        
+    def db_display_action(self,timestamp) :
+        cur = self.conn.cursor() # 커서를 생성한다
+        now=timestamp
+        d_plus=now +timedelta(hours=2)
+        d_plus=str("'"+d_plus.strftime('%Y-%m-%d %X')+"'")
+        d_minus=now -timedelta(hours=2)
+        d_minus=str("'"+d_minus.strftime('%Y-%m-%d %X')+"'")
+        cur.execute(f'''
+        select * from rds.pothole 
+        where timestamp between {d_minus} and {d_plus};
+        ''')
+        result=cur.fetchall()
+        return result
+    
+
+        
+
+    (파일 끝에 줄바꿈 문자 없음)
 
main_server/fog_1.jpg (Binary) (added)
+++ main_server/fog_1.jpg
Binary file is not shown
 
main_server/mrousavy1404057804125804675.jpg (Binary) (added)
+++ main_server/mrousavy1404057804125804675.jpg
Binary file is not shown
 
main_server/mrousavy1609405171016471384.jpg (Binary) (added)
+++ main_server/mrousavy1609405171016471384.jpg
Binary file is not shown
 
main_server/mrousavy6478677259507416977.jpg (Binary) (added)
+++ main_server/mrousavy6478677259507416977.jpg
Binary file is not shown
 
main_server/mrousavy9178771130024154858.jpg (Binary) (added)
+++ main_server/mrousavy9178771130024154858.jpg
Binary file is not shown
 
main_server/requirements.txt (added)
+++ main_server/requirements.txt
@@ -0,0 +1,113 @@
+absl-py==1.3.0
+aniso8601==9.0.1
+asttokens @ file:///home/conda/feedstock_root/build_artifacts/asttokens_1660605382950/work
+astunparse==1.6.3
+attrs==22.1.0
+backcall @ file:///home/conda/feedstock_root/build_artifacts/backcall_1592338393461/work
+backports.functools-lru-cache @ file:///home/conda/feedstock_root/build_artifacts/backports.functools_lru_cache_1618230623929/work
+cachetools==5.2.0
+certifi==2022.9.24
+charset-normalizer==2.1.1
+click==8.1.3
+colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1655412516417/work
+contourpy==1.0.6
+cycler==0.11.0
+debugpy @ file:///D:/bld/debugpy_1660619096890/work
+decorator @ file:///home/conda/feedstock_root/build_artifacts/decorator_1641555617451/work
+dgl==0.9.1
+entrypoints @ file:///home/conda/feedstock_root/build_artifacts/entrypoints_1643888246732/work
+executing @ file:///home/conda/feedstock_root/build_artifacts/executing_1664126393503/work
+Flask==2.1.3
+flask-restx==0.5.1
+flatbuffers==22.9.24
+fonttools==4.38.0
+gast==0.4.0
+geojson==2.5.0
+google-auth==2.13.0
+google-auth-oauthlib==0.4.6
+google-pasta==0.2.0
+grpcio==1.50.0
+h5py==3.7.0
+haversine==2.7.0
+idna==3.4
+imageio==2.22.2
+ipykernel @ file:///D:/bld/ipykernel_1664214869204/work
+ipython @ file:///D:/bld/ipython_1662481701382/work
+itsdangerous==2.1.2
+jedi @ file:///home/conda/feedstock_root/build_artifacts/jedi_1659959867326/work
+Jinja2==3.1.2
+joblib==1.2.0
+jsonschema==4.16.0
+jupyter_client @ file:///home/conda/feedstock_root/build_artifacts/jupyter_client_1661522530937/work
+jupyter_core @ file:///D:/bld/jupyter_core_1658332495289/work
+keras==2.10.0
+Keras-Preprocessing==1.1.2
+kiwisolver==1.4.4
+libclang==14.0.6
+Markdown==3.4.1
+MarkupSafe==2.1.1
+matplotlib==3.6.0
+matplotlib-inline @ file:///home/conda/feedstock_root/build_artifacts/matplotlib-inline_1660814786464/work
+nest-asyncio @ file:///home/conda/feedstock_root/build_artifacts/nest-asyncio_1664684991461/work
+networkx==2.8.7
+numpy==1.23.3
+oauthlib==3.2.2
+opencv-python==4.6.0.66
+opt-einsum==3.3.0
+packaging @ file:///home/conda/feedstock_root/build_artifacts/packaging_1637239678211/work
+pandas==1.5.0
+parso @ file:///home/conda/feedstock_root/build_artifacts/parso_1638334955874/work
+pickleshare @ file:///home/conda/feedstock_root/build_artifacts/pickleshare_1602536217715/work
+Pillow==9.2.0
+platformdirs==2.5.2
+prompt-toolkit @ file:///home/conda/feedstock_root/build_artifacts/prompt-toolkit_1662384672173/work
+protobuf==3.19.6
+psutil @ file:///C:/Windows/Temp/abs_b2c2fd7f-9fd5-4756-95ea-8aed74d0039flsd9qufz/croots/recipe/psutil_1656431277748/work
+psycopg2==2.9.4
+pure-eval @ file:///home/conda/feedstock_root/build_artifacts/pure_eval_1642875951954/work
+pyasn1==0.4.8
+pyasn1-modules==0.2.8
+Pygments @ file:///home/conda/feedstock_root/build_artifacts/pygments_1660666458521/work
+PyJWT==2.6.0
+pyopencl==2022.2.4
+pyparsing @ file:///home/conda/feedstock_root/build_artifacts/pyparsing_1652235407899/work
+pyrsistent==0.18.1
+pyshp==2.3.1
+python-dateutil @ file:///home/conda/feedstock_root/build_artifacts/python-dateutil_1626286286081/work
+pytools==2022.1.12
+pytz==2022.4
+PyWavelets==1.4.1
+pywin32==303
+PyYAML==6.0
+pyzmq @ file:///C:/ci/pyzmq_1657616000714/work
+requests==2.28.1
+requests-oauthlib==1.3.1
+rsa==4.9
+scikit-image==0.19.3
+scikit-learn==1.1.2
+scipy==1.9.2
+seaborn==0.12.1
+six @ file:///home/conda/feedstock_root/build_artifacts/six_1620240208055/work
+sklearn==0.0
+stack-data @ file:///home/conda/feedstock_root/build_artifacts/stack_data_1664126450622/work
+tensorboard==2.10.1
+tensorboard-data-server==0.6.1
+tensorboard-plugin-wit==1.8.1
+tensorflow==2.10.0
+tensorflow-estimator==2.10.0
+tensorflow-io-gcs-filesystem==0.27.0
+termcolor==2.0.1
+threadpoolctl==3.1.0
+tifffile==2022.10.10
+torch==1.12.1+cu116
+torchaudio==0.12.1+cu116
+torchvision==0.13.1+cu116
+tornado @ file:///D:/bld/tornado_1656937966227/work
+tqdm==4.64.1
+traitlets @ file:///home/conda/feedstock_root/build_artifacts/traitlets_1663005918942/work
+typing_extensions==4.4.0
+urllib3==1.26.12
+wcwidth @ file:///home/conda/feedstock_root/build_artifacts/wcwidth_1600965781394/work
+Werkzeug==2.1.2
+wincertstore==0.2
+wrapt==1.14.1
 
main_server/subfuction/generate.py (added)
+++ main_server/subfuction/generate.py
@@ -0,0 +1,57 @@
+from haversine import haversine
+import networkx as nx
+import geojson
+
+
+
+with open("D:/takensoft/project2/data/기타 가공/데이터/osm.geojson",encoding='utf-8') as f:
+    gj = geojson.load(f)
+
+
+def swith_xy(tuples):
+    x,y=tuples
+    return (y,x)
+
+G = nx.Graph ()
+
+total_data_num= gj['features']
+for j in range(len(total_data_num)):
+    features = gj['features'][j]
+    lines=features['geometry']['coordinates'][0]
+    print(j)
+
+    for i in range(len(lines)-1):
+        G.add_edge(swith_xy(lines[i]),swith_xy(lines[i+1]),flcass=features['properties']['fclass'],oneway=features['properties']['oneway'])
+
+sg = (G.subgraph(c) for c in nx.connected_components(G)) #가져올 수 없는 패키지가 있는 경우
+sg = list(sg)[0]
+
+for n0, n1 in G.edges ():
+    dist = haversine(n0, n1,unit='m')
+    G.edges [n0,n1][" dist "] = dist
+
+df=nx.to_pandas_edgelist(G)
+
+li_source=list(df['source'])
+li_source_x= []
+li_source_y=[]
+
+for i in li_source:
+    li_source_x.append(str(i[0]))
+    li_source_y.append(str(i[1]))
+df['source_x']=li_source_x
+df['source_y']=li_source_y
+
+li_target=list(df['target'])
+li_target_x= []
+li_target_y=[]
+
+for i in li_target:
+    li_target_x.append(str(i[0]))
+    li_target_y.append(str(i[1]))
+df['target_x']=li_target_x
+df['target_y']=li_target_y
+df=df.drop(['source','target'],axis=1)
+df=df.reset_index()
+df.to_csv('node.csv',encoding='euc-kr')
+
 
main_server/subfuction/save_pickle.py (added)
+++ main_server/subfuction/save_pickle.py
@@ -0,0 +1,35 @@
+import torch
+import numpy as np
+import networkx as nx
+from database.database import DB
+import pandas as pd
+
+import networkx as nx
+import math
+from itertools import tee
+import shapefile
+import os
+
+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)
+
+def swith_xy(tuples):
+    x,y=tuples
+    return (y,x)
+    
+
+
+
+
+db=DB()
+df=pd.DataFrame(db.db_get_node())
+df.columns=['index','source_x','source_y','target_x','target_y','distance']
+G=nx.Graph()
+for j in range(len(df)):
+    G.add_edge((df['source_x'][j],df['source_y'][j]),(df['target_x'][j],df['target_y'][j]),length=df['distance'][j])
+nx.write_gpickle(G,'OSM_gpickle.gpickle')
+
Add a comment
List