File size: 8,937 Bytes
d737845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### import"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: xmltodict in c:\\users\\user\\appdata\\local\\programs\\python\\python311\\lib\\site-packages (0.13.0)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "[notice] A new release of pip is available: 23.2.1 -> 24.0\n",
      "[notice] To update, run: python.exe -m pip install --upgrade pip\n"
     ]
    }
   ],
   "source": [
    "%pip install xmltodict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use request to download a xml file\n",
    "import requests\n",
    "import json\n",
    "import xmltodict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# url = 'http://tisvcloud.freeway.gov.tw/history/motc20/ETag.xml'\n",
    "# response = requests.get(url)\n",
    "# with open('ETag.xml', 'wb') as f:\n",
    "#     f.write(response.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Turn xml to json\n",
    "# filename = 'ETag'\n",
    "# with open(f'{filename}.xml', 'r', encoding='utf-8-sig') as f:\n",
    "#     data_dict = xmltodict.parse(f.read())\n",
    "#     data_json = json.dumps(data_dict, ensure_ascii=False)\n",
    "#     # dump to Etag.json with json\n",
    "#     json.dump(data_dict, open(f'{filename}.json', 'w'), ensure_ascii=False, indent=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "'pwd' ���O�����Υ~���R�O�B�i���檺�{���Χ妸�ɡC\n"
     ]
    }
   ],
   "source": [
    "!pwd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Read ETagPairLive_1615.xml.gz and decompress it\n",
    "import gzip\n",
    "import shutil\n",
    "import threading\n",
    "\n",
    "\n",
    "\n",
    "def crawl(url, filename):\n",
    "    try:\n",
    "        try:\n",
    "            response = requests.get(url)\n",
    "        except Exception as e:\n",
    "            print(\"Error\",e)\n",
    "        with open(f'{filename}.xml.gz', 'wb') as f:\n",
    "            f.write(response.content)\n",
    "        \n",
    "        # 解壓縮\n",
    "        with gzip.open(f'{filename}.xml.gz', 'rb') as f_in:\n",
    "            with open(f'{filename}.xml', 'wb') as f_out:\n",
    "                shutil.copyfileobj(f_in, f_out)\n",
    "\n",
    "        # xml to json\n",
    "        with open(f'{filename}.xml', 'r') as f:\n",
    "            data_dict = xmltodict.parse(f.read())\n",
    "            data_json = json.dumps(data_dict, ensure_ascii=False)\n",
    "            # dump to Etag.json with json\n",
    "            json.dump(data_dict, open(f'{filename}.json', 'w'), ensure_ascii=False, indent=2)\n",
    "    except Exception as e:\n",
    "        print(e)\n",
    "        print(f'{url} failed')\n",
    "    print(f'{url} done')\n",
    "\n",
    "threads = []\n",
    "day_list = ['202405%02d'%(x) for x in range(6, 13)]\n",
    "hour_list = ['%02d'%(i) for i in range(24)]\n",
    "five_minute_list = ['%02d'%(i) for i in range(0,60,5)]\n",
    "print(\"Lens = \", len(day_list) * len(hour_list) * len(five_minute_list))\n",
    "for day in day_list:\n",
    "    for hour in hour_list:\n",
    "        for minute in five_minute_list:\n",
    "            i = hour + minute\n",
    "            # filename = f'ETagPairLive_{str(i)}'\n",
    "            # url = f'https://tisvcloud.freeway.gov.tw/history/motc20/ETag/20240522/{filename}.xml.gz'\n",
    "            filename = f'./data/ETagPairLive_{day}_{str(i)}'\n",
    "            url = f'https://tisvcloud.freeway.gov.tw/history/motc20/ETag/{day}/ETagPairLive_{str(i)}.xml.gz'\n",
    "            t = threading.Thread(target=crawl, args=(url, filename))\n",
    "            threads.append(t)\n",
    "            t.start()\n",
    "\n",
    "# Wait for all threads to finish\n",
    "for t in threads:\n",
    "    t.join()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.font_manager as fm\n",
    "\n",
    "EtagPairId = '01F0339S-01F0376S'\n",
    "EtagStart = '01F0339S'\n",
    "EtagEnd = '01F0376S'\n",
    "EtagStartRoad = ['五股','高公局','林口(文化一路)']\n",
    "VehicleTypeDict = {\n",
    "    31: \"Car\",\n",
    "    32: \"Small Truck\",\n",
    "    41: \"Bus\", # (含計程車)\n",
    "    42: \"Heavy Truck\",\n",
    "    5: \"Trailer\"\n",
    "}\n",
    "\n",
    "time_series_31data = {}\n",
    "time_series_32data = {}\n",
    "time_series_41data = {}\n",
    "time_series_42data = {}\n",
    "time_series_5data = {}\n",
    "\n",
    "\n",
    "day_list = ['202405%02d'%(x) for x in range(6, 13)]\n",
    "hour_list = ['%02d'%(i) for i in range(24)]\n",
    "five_minute_list = ['%02d'%(i) for i in range(0,60,5)]\n",
    "for day in day_list:\n",
    "    for hour in hour_list:\n",
    "        for minute in five_minute_list:\n",
    "            i = hour + minute\n",
    "            filename = f'./data/ETagPairLive_{day}_{str(i)}'\n",
    "            try:\n",
    "                with open(f'{filename}.json', 'r') as f:\n",
    "                    data = json.load(f)\n",
    "                    EtagPairLive = data['ETagPairLiveList']['ETagPairLives']['ETagPairLive']\n",
    "                    for ETagPair in EtagPairLive:\n",
    "                        if ETagPair['ETagPairID'] == EtagPairId:\n",
    "                            # print(ETagPair['ETagPairID'])\n",
    "                            Flow = ETagPair['Flows']['Flow']\n",
    "                            for vehicle in Flow:\n",
    "                                # print(f\"VehicleType: {VehicleTypeDict[int(vehicle['VehicleType'])]}, VehicleNum: {vehicle['VehicleCount']}, Speed: {vehicle['SpaceMeanSpeed']}, Time: {vehicle['TravelTime']}\")\n",
    "                                if int(vehicle['VehicleType']) == 31:\n",
    "                                    time_series_31data[f'{day}_{i}'] = int(vehicle['VehicleCount'])\n",
    "                                elif int(vehicle['VehicleType']) == 32:\n",
    "                                    time_series_32data[f'{day}_{i}'] = int(vehicle['VehicleCount'])\n",
    "                                elif int(vehicle['VehicleType']) == 41:\n",
    "                                    time_series_41data[f'{day}_{i}'] = int(vehicle['VehicleCount'])\n",
    "                                elif int(vehicle['VehicleType']) == 42:\n",
    "                                    time_series_42data[f'{day}_{i}'] = int(vehicle['VehicleCount'])\n",
    "                                elif int(vehicle['VehicleType']) == 5:\n",
    "                                    time_series_5data[f'{day}_{i}'] = int(vehicle['VehicleCount'])\n",
    "            except:\n",
    "                pass\n",
    "\n",
    "step = 6\n",
    "plt.figure(figsize=(30,10))\n",
    "plt.plot(list(time_series_31data.keys())[::step], list(time_series_31data.values())[::step], label=VehicleTypeDict[31])\n",
    "plt.plot(list(time_series_32data.keys())[::step], list(time_series_32data.values())[::step], label=VehicleTypeDict[32])\n",
    "plt.plot(list(time_series_41data.keys())[::step], list(time_series_41data.values())[::step], label=VehicleTypeDict[41])\n",
    "plt.plot(list(time_series_42data.keys())[::step], list(time_series_42data.values())[::step], label=VehicleTypeDict[42])\n",
    "plt.plot(list(time_series_5data.keys())[::step], list(time_series_5data.values())[::step], label=VehicleTypeDict[5])\n",
    "plt.xlabel('Time')\n",
    "plt.xticks(fontsize=14)\n",
    "plt.xticks(rotation=60)\n",
    "plt.ylabel('VehicleCount')\n",
    "plt.title(f'{EtagStart} to {EtagEnd}')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}