def collect_data(self): #read file parking lot information with open("臺北市停車場資訊.json", "r") as f: # read file and convert to dict parking_lot_info_content = json.loads(f.read()) # parking lot info parking_lot_Updatetime = parking_lot_info_content["data"]["UPDATETIME"] parking_lot_data = parking_lot_info_content["data"]["park"] # get data and save to sql for data in parking_lot_data: para = [] #轉換停車場twd97 座標成gs84 經緯度 tw97x = float(data["tw97x"]) tw97y = float(data["tw97y"]) gs84 = twd97.towgs84(tw97x, tw97y) #put data into para for sql para.append(data["id"]) #id para.append(data["area"]) #area para.append(data["name"]) #name para.append(1) #room para.append(data["summary"]) #summary para.append(data["tel"]) #tel para.append(gs84[0]) #latitude para.append(gs84[1]) #longitude para.append(data["payex"]) #payex para.append(data["totalcar"]) #totalcar para.append(data["totalmotor"]) #totalmotor para.append(data["totalbus"]) #totalbus para.append(parking_lot_Updatetime) #update_time para = tuple(para) #save into sql sql = "replace into taipei (id, area, name, room, summary, tel, latitude, longitude, payex, totalcar, totalmotor, totalbus, update_time) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" mysql.update(sql, para) #read file, parking live data with open("剩餘停車位數.json", "r") as f: # read file and convert to dict parking_live_content = json.loads(f.read()) #parking live data parking_live_time = parking_live_content["data"]["UPDATETIME"] parking_live_data = parking_live_content["data"]["park"] #get data and save to sql for data in parking_live_data: para = [] # put data into para for sql para.append(data["id"]) # id para.append(data["availablecar"]) #availablecar para.append(data["availablemotor"]) # availablemotor para.append(data["availablebus"]) # availablebus para.append(parking_live_time) # update_time # save into sql sql = "replace into taipei_live (id, availablecar, availablemotor, availablebus, update_time) values (%s,%s,%s,%s,%s)" mysql.update(sql, para)
def update(self, instance, validated_data): instance.ws84_x = validated_data.get('ws84_x', instance.ws84_x) instance.ws84_y = validated_data.get('ws84_y', instance.ws84_y) instance.address = validated_data.get('address', instance.address) instance.note = validated_data.get('note', instance.note) bucket_lat, bucket_lng = twd97.towgs84(float(instance.ws84_x), float(instance.ws84_y)) instance.lng = bucket_lng instance.lat = bucket_lat instance.point = 'POINT(%f %f)' % (float( instance.ws84_x), float(instance.ws84_y)) instance.save() return instance
def create(self, validated_data): bucket_id = validated_data.get('id') ws84_x = validated_data.get('ws84_x') ws84_y = validated_data.get('ws84_y') address = validated_data.get('address') note = validated_data.get('note') bucket_lat, bucket_lng = twd97.towgs84(float(ws84_x), float(ws84_y)) return Bucket.objects.create(id=bucket_id, ws84_x=ws84_x, ws84_y=ws84_y, address=address, note=note, lng=float(bucket_lng), lat=float(bucket_lat), point='POINT(%f %f)' % (ws84_x, ws84_y))
def find_parking_lot_by_coordinate(self, location, within_meters): x, y = location for park in self._jsParkingInfo['data']['park']: if 'Entrancecoord' in park: for entrance in park['Entrancecoord']['EntrancecoordInfo']: entrance_x, entrance_y = float(entrance['Xcod']), float(entrance['Ycod']) if vincenty((x, y), (entrance_x, entrance_y)).meters < within_meters: yield park break elif 'tw97x' in park and 'tw97y' in park: entrance_x, entrance_y = twd97.towgs84(float(park['tw97x']), float(park['tw97y'])) if vincenty((x, y), (entrance_x, entrance_y)).meters < within_meters: yield park else: logger.warning('No location info for ' + park['name'])
def twd97tokml(txtname): loadedData = np.loadtxt(txtname, dtype=np.str) kml = simplekml.Kml() data = [] for i in range(len(loadedData)): QQ = loadedData[i].split(',') data.append(QQ) for i in range(len(data)): name = data[i][0] N = float(data[i][1]) E = float(data[i][2]) lat, lon = twd97.towgs84(N, E) kml.newpoint(name=name, coords=[(lon, lat)]) kml.save(txtname[:-4] + ".kml")
bucket_x = ws['B' + str(row)].value bucket_y = ws['C' + str(row)].value if bucket_x == None or bucket_y == None: continue try: bucket_x = float(bucket_x) bucket_y = float(bucket_y) except: continue bucket_address = ws['D' + str(row)].value if isinstance( ws['D' + str(row)].value, str) == True else '無' bucket_note = ws['E' + str(row)].value if isinstance( ws['E' + str(row)].value, str) == True else '無' bucket_lat, bucket_lng = twd97.towgs84(bucket_x, bucket_y) bucket_dict[bucket_id] = { 'bucket_lat': bucket_lat if isinstance(bucket_lat, float) == True else NO_DATA, 'bucket_lng': bucket_lng if isinstance(bucket_lng, float) == True else NO_DATA, # 'bucket_address': bucket_address, # 'bucket_note': bucket_note } Bucket( id=bucket_id, ws84_x=bucket_x, ws84_y=bucket_y, address=bucket_address,
db = client['cloud-final'] collection = db['parkingInfo'] link = "http://data.ntpc.gov.tw/api/v1/rest/datastore/382000000A-000225-002" req = requests.get(link) data = json.loads(req.text) df_park = pd.read_csv("park_data.csv", encoding='utf-8') col_name = df_park.columns latitude = [] longitude = [] TWD97Y = df_park["TW97Y"].values TWD97X = df_park["TW97X"].values for i in range(len(TWD97X)): lat, long = twd97.towgs84(TWD97X[i], TWD97Y[i]) latitude.append(lat) longitude.append(long) df_park["latitude"] = latitude df_park["longitude"] = longitude for index, row in df_park.iterrows(): data = { "park_id": row[col_name[0]], "park_area": row['AREA'], "park_name": row['NAME'], "park_summary": row['SUMMARY'], "park_address": row['ADDRESS'], "park_payex": row['PAYEX'], "park_servicetime": row['SERVICETIME'],
def getComment(street, address, use, brand, layer, terAreaClass=""): def getCookie(): options = Options() # options.add_argument("--headless") options.add_argument("--no-sandbox") options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") driver = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=options) driver.get("http://luz.tcd.gov.tw/web/") sleep(2) cookie = driver.get_cookies()[0] sleep(0.5) driver.quit() with open(r"../ap/legalityData/cookies.txt", 'w') as f: f.write(cookie['name'] + "=" + cookie['value']) return cookie['name'] + "=" + cookie['value'] def taipei(areaClass, area=150, floorList=[1], use="餐廳或飲食店"): print("台北判斷") if "特" in areaClass: print(areaClass, "需人工判斷該區為什麼區!-{}".format(address)) return "請人工查詢下方網頁<br/>(用門牌號碼>選區、路、巷弄號搜索,確認該區右方括弧內叫做什麼)<br/><a href='https://www.zone.gov.taipei/new_showmapMain.aspx?noshow=0' target='_blank'>台北市土地分區查詢</a><br/>請輸入該區右方括弧內名稱於特別欄位,並再次送出:" elif "商" in areaClass: if use != "餐廳或飲食店" and area >= 300: judgment = "初評通過,但須檢討停車代金,請開發組進行品牌配對" else: judgment = "初評通過,請開發組進行品牌配對" elif "住" in areaClass: if "住一" in areaClass or "住1" in areaClass or "第一種住" in areaClass or "第1種住" in areaClass: judgment = "初評不通過" elif area < 150 and len([i for i in floorList if i in [1, -1]]) > 0: judgment = "初評通過,請開發組進行品牌配對(面臨道路寬需8公尺以上)" elif areaClass in [ "三之一", "三之二", "四之一", "3-1", "3-2", "4-1", "3之1", "3之2", "4之1" ] and area < 500 and len([i for i in floorList if i in [2, 1, -1] ]) > 0: judgment = "初評通過,請開發組進行品牌配對(面臨道路寬需12公尺以上)" elif areaClass in [ "三之一", "三之二", "四之一", "3-1", "3-2", "4-1", "3之1", "3之2", "4之1" ] and len([i for i in floorList if i in [2, 1, -1]]) > 0: judgment = "初評通過,請開發組進行品牌配對(面臨道路寬需12公尺以上,使用面積大於規定500㎡>需判斷是否可分戶使用)" elif len([i for i in floorList if i in [1, -1]]) > 0: judgment = "初評通過,請開發組進行品牌配對(面臨道路寬需8公尺以上,使用面積大於規定150㎡>需判斷是否可分戶使用)" else: judgment = "初評不通過" elif "工" in areaClass: if len([i for i in floorList if i in [2, 1, -1]]) > 0 and area < 300: judgment = "初評通過,請開發組進行品牌配對(同棟建築餐飲業+飲食業使用面積需在500㎡以下)" elif len([i for i in floorList if i in [2, 1, -1] ]) > 0 and area < 500: judgment = "初評通過,請開發組進行品牌配對(同棟建築餐飲業+飲食業使用面積需在500㎡以下,使用面積大於規定300㎡>需判斷是否可分戶使用)" else: judgment = "初評不通過 (工業區-同棟建築餐飲業+飲食業使用面積需在500㎡以下)" else: judgment = "初評通過,請開發組進行品牌配對(須請建築師判斷)" return judgment def taichung(areaClass, area=150, floorList=[1], use="餐廳或飲食店"): print("台中判斷") if "商" in areaClass: if use != '餐廳或飲食店' and area >= 300: judgment = "初評通過,但須檢討停車代金,請開發組進行品牌配對" else: judgment = "初評通過,請開發組進行品牌配對" elif "住" in areaClass: if "B種" in areaClass: judgment = "初評不通過" elif area < 500: judgment = "初評通過,請開發組進行品牌配對" elif area >= 500: judgment = "初評通過,請開發組進行品牌配對(使用面積大於規定500㎡,需判斷是否可分戶使用)" else: judgment = "初評通過,請開發組進行品牌配對(須請建築師判斷)" return judgment def Kaohsiung(areaClass, area=150, floorList=[1], use="餐廳或飲食店"): print("高雄判斷") if "商" in areaClass: if use != '餐廳或飲食店' and area >= 300: judgment = "初評通過,但須檢討停車代金,請開發組進行品牌配對" else: judgment = "初評通過,請開發組進行品牌配對" elif "住" in areaClass: if area < 300: if len([i for i in floorList if i in [1, -1]]) > 0: judgment = "初評通過,請開發組進行品牌配對" elif 2 in floorList: judgment = "路寬十五公尺以上初評通過,請開發組進行品牌配對" elif len([i for i in floorList if i in [2, 1, -1]]) > 0: judgment = "初評通過,請開發組進行品牌配對(使用面積大於規定300㎡,需判斷是否可分戶使用)" else: judgment = "初評不通過" else: judgment = "初評通過,請開發組進行品牌配對(須請建築師判斷)" return judgment def otherCity(areaClass, area, floorList=[1], use="餐廳或飲食店"): print("其他縣市判斷") if "商" in areaClass: if use != '餐廳或飲食店' and area >= 300: judgment = "初評通過,但須檢討停車代金,請開發組進行品牌配對" else: judgment = "初評通過,請開發組進行品牌配對" elif "住" in areaClass: if area < 300: judgment = "初評通過,請開發組進行品牌配對" elif area >= 300: judgment = "初評通過,請開發組進行品牌配對(使用面積大於規定300㎡,需判斷是否可分戶使用)" else: judgment = "初評通過,請開發組進行品牌配對(須請建築師判斷)" return judgment # len([i for i in floorList if i in [2,1,-1]])>0: def getDienMin(): dienMinDict = read_excel(r"../ap/legalityData/dienMin.xlsx") dienMinDict = dienMinDict.to_dict() smallestDict = { i: [j for j in dienMinDict[i].values() if type(j) == str] for i in dienMinDict } smallestDict = {j: i for i in smallestDict for j in smallestDict[i]} return smallestDict #######################################################################################go dienList = { "2": "原燒", "3": "王品", "4": "聚", "5": "藝奇", "6": "夏慕尼", "7": "西堤", "8": "陶板屋", "10": "品田", "12": "石二鍋", "13": "舒果", "15": "hot7", "151": "禾樂", "16": "ita", "17": "莆田", "18": "酷必", "19": "麻佬大", "20": "乍牛", "22": "沐越", "23": "青花驕", "24": "享鴨", "25": "丰和日麗" } smallestDict = getDienMin() # dienType = input("是否為街邊店\n選項\n\t1:是\n\t2:否\n\t:") street = "1" dienType = street if dienType == "1": dienType = '街邊' elif dienType == "2": dienType = '商場' if dienType == '商場': address = input("請輸入商場名稱、位置\n(例:中原家樂福-桃園市中壢區中華路二段501號):") use = input("是否由商場辦理合法性?\n選項\n\t1:是\n\t2:否\n\t:") elif dienType == '街邊': # address = input("請輸入地址(須包含[市|縣]及[區|市|鎮|鄉]):") address = address ############################# # nF = int(input("共承租幾層?")) nF = len(layer) # layerData = {} # for i in range(1, nF + 1): # nLayer = int(input("請輸入第{}筆承租樓層\n選項\n\t 1:一樓\n\t 2:二樓\n\t-1:地下一樓\n\t-2:地下二樓 (以此類推)\n\t:".format(i))) # nArea = float(input("請輸入使用面積(平方公尺)")) # layerData[nLayer] = nArea # area = round(sum([layerData[i] for i in layerData]), 3) # floorList = [i for i in layerData] # print("總面積共{}平方公尺".format(area)) # ############################# # # area=float(input("請輸入使用面積(平方公尺):")) # # floor=int(input("請輸入樓層\n選項\n\t 1:一樓\n\t 2:二樓\n\t-1:地下一樓\n\t-2:地下二樓\n\t:")) # use = input("用途\n選項\n\t1:餐廳或飲食店\n\t2:其他-非餐飲\n\t:") # if use == "1": # use = '餐廳或飲食店' # elif use == "2": # use = '其他-非餐飲' # # brand = input("""品牌\n選項 # 2: '原燒', # 3: '王品', # 4: '聚', # 5: '藝奇', # 6: '夏慕尼', # 7: 'TASTy', # 8: '陶板屋', # 10: '品田牧場', # 12: '石二鍋', # 13: '舒果', # 15: 'hot 7', # 151:'禾樂', # 16: 'ita義塔', # 17: '莆田', # 18: 'CooK BEEF!', # 19: '麻佬大', # 20: '乍牛', # 22: '沐越', # 23: '青花驕', # 24: '享鴨', # 25: '丰和日麗'\n\t:""") # brand = dienList[brand] # smallest = smallestDict[brand] # ########################## # bigadd = "" # smalladd = "" try: bigadd = findall("(..[市|縣])(\w\w?\w?[區|市|鎮|鄉])", address)[0][0] smalladd = findall("(..[市|縣])(\w\w?\w?[區|市|鎮|鄉])", address)[0][1] except: pass try: road = address.split(smalladd)[-1].split("、")[0] except: road = address.split("、")[0] print("沒有市或區的地址,可能會不準確") headersStr = """Accept: */* Accept-Encoding: gzip, deflate Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7 Connection: keep-alive Content-Length: 114 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Cookie: ASP.NET_SessionId=zyh3tb3y1zfoxairu3hr0mth Host: luz.tcd.gov.tw Origin: http://luz.tcd.gov.tw Referer: http://luz.tcd.gov.tw/WEB/ User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 X-Requested-With: XMLHttpRequest""" headerDict = { i.split(": ")[0].strip(): i.split(": ")[1].strip() for i in headersStr.split("\n") } with open(r"../ap/legalityData/cookies.txt", 'r') as f: cookieStr = f.read() headerDict['Cookie'] = cookieStr dataDict = {} dataDict["VAL1"] = road if bigadd != "": dataDict["COUNTY"] = bigadd dataDict["TOWN"] = smalladd try: findXYUrl = "http://luz.tcd.gov.tw/WEB/ws_data.ashx?CMD=GETADDRESS" res = post(findXYUrl, data=dataDict, headers=headerDict) locationData = loads(res.text) print(locationData) except: getCookie() with open(r"../ap/legalityData/cookies.txt", 'r') as f: cookieStr = f.read() headerDict['Cookie'] = cookieStr res = post(findXYUrl, data=dataDict, headers=headerDict) locationData = loads(res.text) # return "資料讀取中,請等30秒後再來" lat, lng = towgs84(locationData['AddressList'][0]['X'], locationData['AddressList'][0]['Y']) print(lat, lng) else: lat, lng = google(address).latlng print(lat, lng) P4326 = Proj(init='epsg:4326') P3857 = Proj(init='epsg:3857') x, y = transform(P4326, P3857, lng, lat) print(x, y) queryHeadersStr = """Accept: */* Accept-Encoding: gzip, deflate Accept-Language: zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7 Connection: keep-alive Content-Length: 69 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Cookie: ASP.NET_SessionId=zyh3tb3y1zfoxairu3hr0mth Host: luz.tcd.gov.tw Origin: http://luz.tcd.gov.tw Referer: http://luz.tcd.gov.tw/WEB/ User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 X-Requested-With: XMLHttpRequest""" queryHeaderDict = { i.split(": ")[0].strip(): i.split(": ")[1].strip() for i in queryHeadersStr.split("\n") } queryHeaderDict['Cookie'] = cookieStr queryData = {} queryData["X"], queryData["Y"] = x, y # queryData["X"],queryData["Y"]=13495533.107782178,2870575.0923182988 queryData["LAYERS"] = "5,3,6" queryData['LANDLAYERS'] = "" queryUrl = "http://luz.tcd.gov.tw/WEB/ws_identify.ashx" res = post(queryUrl, data=queryData, headers=queryHeaderDict) info = loads(res.text) print(info) # areaClass = info['5']['features'][0]['attributes']['使用分區'] # print(areaClass) ############################################################################################################# # nF = int(input("共承租幾層?") # layerData = {} # for i in range(1, nF + 1): # # nLayer = int(input("請輸入第{}筆承租樓層\n選項\n\t 1:一樓\n\t 2:二樓\n\t-1:地下一樓\n\t-2:地下二樓 (以此類推)\n\t:".format(i))) # # nArea = float(input("請輸入使用面積(平方公尺)")) # layerData[nLayer] = nArea layerData = layer area = round(sum([layerData[i] for i in layerData]), 3) floorList = [i for i in layerData] print("總面積共{}平方公尺".format(area)) ############################# # area=float(input("請輸入使用面積(平方公尺):")) # floor=int(input("請輸入樓層\n選項\n\t 1:一樓\n\t 2:二樓\n\t-1:地下一樓\n\t-2:地下二樓\n\t:")) # use = input("用途\n選項\n\t1:餐廳或飲食店\n\t2:其他-非餐飲\n\t:" use = use if use == "1": use = '餐廳或飲食店' elif use == "2": use = '其他-非餐飲' # brand = input("""品牌\n選項 # 2: '原燒', # 3: '王品', # 4: '聚', # 5: '藝奇', # 6: '夏慕尼', # 7: 'TASTy', # 8: '陶板屋', # 10: '品田牧場', # 12: '石二鍋', # 13: '舒果', # 15: 'hot 7', # 151:'禾樂', # 16: 'ita義塔', # 17: '莆田', # 18: 'CooK BEEF!', # 19: '麻佬大', # 20: '乍牛', # 22: '沐越', # 23: '青花驕', # 24: '享鴨', # 25: '丰和日麗'\n\t:""") brand = brand brand = dienList[brand] smallest = smallestDict[brand] ########################## # bigadd = "" # smalladd = "" ############################################################################################################## if dienType == '商場': if use == "1": use = "商場會辦理合法性" judgment = "初評通過" else: use = "但須由我方自行辦理合法業務" judgment = "初評通過(須請建築師判斷)" print("本評估新點({})為商場店,{}。<br\><br\>\t本案判斷:{}".format( address, use, judgment)) # address=input("請輸入商場名稱、位置\n(例:中原家樂福-桃園市中壢區中華路二段501號):") # use=input("是否為商場辦理合法性?\n選項\n\t1:是\n\t2:否\n\t:") else: if terAreaClass != "": areaClass = terAreaClass print(bigadd) if smallest > area: judgment = "初評不通過,未達'{}'最小合法面積限制{}m2".format(brand, smallest) elif bigadd == "台北市" or bigadd == "臺北市": if "特" in areaClass: judgment = taipei(areaClass, area, floorList, use) else: judgment = taipei(areaClass, area, floorList, use) elif bigadd == "台中市" or bigadd == "臺中市": judgment = taichung(areaClass, area, floorList, use) elif bigadd == "高雄市": judgment = Kaohsiung(areaClass, area, floorList, use) else: judgment = otherCity(areaClass, area, floorList, use) layer_area = "、".join([ "{}F:{}㎡".format(i, layerData[i]) if i > 0 else "B{}:{}㎡".format(-i, layerData[i]) for i in layerData ]) if nF == 1: return "本評估新點({})的使用分區為 {},<br/>(建物面積:{},用途:{})。<br/><br\>\t本案判斷:{}-{}".format( address, areaClass, layer_area, use, brand, judgment) else: return "本評估新點({})的使用分區為 {},<br/>(建物面積:{}-共{}㎡,用途:{})。<br/><br/>\t本案判斷:{}-{}".format( address, areaClass, layer_area, area, use, brand, judgment)
def seed_ntpc(): logger.debug("Seed NTPC sample data") data_file = os.path.join(os.getcwd(), "seed", "NTCLighting.csv") if not os.path.isfile(data_file): logger.debug(f"CSV file not existed: {data_file}") return clean_data() # add basic data cust = sdCustomer(name=__cust_name, display_name=__cust_display, comment=__cust_comment) user = sdUser(cust=cust, name="admin", display_name="Admin (NTPC)", comment="NTPC Administrator", password="******") model_led = sdDeviceModel(name=__model_led[0], display_name=__model_led[1]) model_ctrl = sdDeviceModel(name=__model_ctrl[0], display_name=__model_ctrl[1]) db.session.add(cust) db.session.add(user) db.session.add(model_led) db.session.add(model_ctrl) db.session.commit() # add devices device_groups = {} with open(data_file, encoding='utf-8', newline='') as csv_file: rows = csv.reader(csv_file) index = 0 row_count = 0 for row in rows: index += 1 if index == 1: # ignore header continue # convert twd97 to wgs84 try: twd_x, twd_y = float(row[4]), float(row[5]) (wgs_y, wgs_x) = twd97.towgs84(twd_x, twd_y) except Exception: logger.debug(f"twd or wgs error: {row}") continue # check if coordination out of range if wgs_x < 120 or wgs_x > 122 or wgs_y < 24 or wgs_y > 26: logger.debug( f"wgs_x or wgs_y out of range: 120 <= x < 122 or 24 <= x < 26" ) continue # add device row_count = row_count + 1 # get or new device group group_name = row[0] device_group = device_groups.get(group_name) if not device_group: device_group = sdDeviceGroup(cust=cust, name=group_name, display_name=f"新北市{group_name}") device_groups[group_name] = device_group # new device device = sdDevice( cust=cust, name=f"{row_count}", display_name=f"{row[0]}_{row_count}", comment=f"New no is {row[1]}, Old no is {row[2]}", address=f"新北市{row[3]}", device_group=device_group, wgs_x=wgs_x, wgs_y=wgs_y) # assign controller and led device.controller = sdController(model=model_ctrl, cust=cust, serial_no=str(uuid.uuid4())) device.led = sdLed(model=model_led, cust=cust, serial_no=str(uuid.uuid4())) # add objects db.session.add(device) if (row_count % 10000) == 0: db.session.commit() logger.debug(f"Commit {row_count}") db.session.commit() logger.debug(f"Total device committed {row_count}")