-
Notifications
You must be signed in to change notification settings - Fork 15
/
covidthailand.py
3419 lines (3025 loc) · 167 KB
/
covidthailand.py
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf8
import datetime
import dateutil
import difflib
from io import StringIO
from itertools import islice, compress, cycle
import json
import os
import pathlib
import pickle
import re
from typing import Sequence, Union, List, Callable
import urllib.parse
from bs4 import BeautifulSoup
import camelot
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib.ticker import FuncFormatter
from matplotlib.pyplot import cycler
import matplotlib.cm
import numpy as np
import pandas as pd
from pptx import Presentation
from pytwitterscraper import TwitterScraper
import requests
from requests.adapters import HTTPAdapter, Retry
from tika import parser
from webdav3.client import Client
CHECK_NEWER = bool(os.environ.get("CHECK_NEWER", False))
requests.adapters.DEFAULT_RETRIES = 5 # for other tools that use requests internally
s = requests.Session()
RETRY = Retry(
total=10, backoff_factor=1
) # should make it more reliable as ddc.moph.go.th often fails
s.mount("http://", HTTPAdapter(max_retries=RETRY))
s.mount("https://", HTTPAdapter(max_retries=RETRY))
#################
# String helpers
#################
def remove_prefix(text: str, prefix: str) -> str:
"""Removes the prefix of a string"""
if text.startswith(prefix):
return text[len(prefix):]
else:
return text
def remove_suffix(text: str, suffix: str) -> str:
"""Removes the suffix of a string"""
if text.endswith(suffix):
return text[:-len(suffix)]
else:
return text
###############
# Date helpers
###############
def today() -> datetime.datetime:
"""Return today's date and time"""
return datetime.datetime.today()
THAI_ABBR_MONTHS = [
"ม.ค.",
"ก.พ.",
"มี.ค.",
"เม.ย.",
"พ.ค.",
"มิ.ย.",
"ก.ค.",
"ส.ค.",
"ก.ย.",
"ต.ค.",
"พ.ย.",
"ธ.ค.",
]
THAI_FULL_MONTHS = [
"มกราคม",
"กุมภาพันธ์",
"มีนาคม",
"เมษายน",
"พฤษภาคม",
"มิถุนายน",
"กรกฎาคม",
"สิงหาคม",
"กันยายน",
"ตุลาคม",
"พฤศจิกายน",
"ธันวาคม",
]
def file2date(file):
"return date of either for '10-02-21' or '100264'"
file = os.path.basename(file)
file, *_ = file.rsplit(".", 1)
if m := re.search(r"\d{4}-\d{2}-\d{2}", file):
return d(m.group(0))
# date = file.rsplit(".pdf", 1)[0]
# if "-" in file:
# date = file.rsplit("-", 1).pop()
# else:
# date = file.rsplit("_", 1).pop()
if m := re.search(r"\d{6}", file):
# thai date in briefing filenames
date = m.group(0)
return datetime.datetime(
day=int(date[0:2]), month=int(date[2:4]), year=int(date[4:6]) - 43 + 2000
)
return None
def find_dates(content):
# 7 - 13/11/2563
dates = re.findall(r"([0-9]+)/([0-9]+)/([0-9]+)", content)
dates = set(
[
datetime.datetime(day=int(d[0]), month=int(d[1]), year=int(d[2]) - 543)
for d in dates
]
)
return sorted([d for d in dates])
def to_switching_date(dstr):
"turning str 2021-01-02 into date but where m and d need to be switched"
if not dstr:
return None
date = d(dstr).date()
if date.day < 13 and date.month < 13:
date = datetime.date(date.year, date.day, date.month)
return date
def previous_date(end, day):
"return a date before {end} by {day} days"
start = end
while start.day != int(day):
start = start - datetime.timedelta(days=1)
return start
def find_thai_date(content):
"find thai date like '17 เม.ย. 2563' "
m3 = re.search(r"([0-9]+) *([^ ]+) *(25[0-9][0-9])", content)
d2, month, year = m3.groups()
month = (
THAI_ABBR_MONTHS.index(month) + 1
if month in THAI_ABBR_MONTHS
else THAI_FULL_MONTHS.index(month) + 1
if month in THAI_FULL_MONTHS
else None
)
date = datetime.datetime(year=int(year) - 543, month=month, day=int(d2))
return date
def find_date_range(content):
"Parse thai date ranges line '11-17 เม.ย. 2563' or '04/04/2563 12/06/2563'"
m1 = re.search(
r"([0-9]+)/([0-9]+)/([0-9]+) [-–] ([0-9]+)/([0-9]+)/([0-9]+)", content
)
m2 = re.search(r"([0-9]+) *[-–] *([0-9]+)/([0-9]+)/(25[0-9][0-9])", content)
m3 = re.search(r"([0-9]+) *[-–] *([0-9]+) *([^ ]+) *(25[0-9][0-9])", content)
if m1:
d1, m1, y1, d2, m2, y2 = m1.groups()
start = datetime.datetime(day=int(d1), month=int(m1), year=int(y1) - 543)
end = datetime.datetime(day=int(d2), month=int(m2), year=int(y2) - 543)
return start, end
elif m2:
d1, d2, month, year = m2.groups()
end = datetime.datetime(year=int(year) - 543, month=int(month), day=int(d2))
start = previous_date(end, d1)
return start, end
elif m3:
d1, d2, month, year = m3.groups()
month = (
THAI_ABBR_MONTHS.index(month) + 1
if month in THAI_ABBR_MONTHS
else THAI_FULL_MONTHS.index(month) + 1
if month in THAI_FULL_MONTHS
else None
)
end = datetime.datetime(year=int(year) - 543, month=month, day=int(d2))
start = previous_date(end, d1)
return start, end
else:
return None, None
def daterange(start_date, end_date, offset=0):
"return a range of dates from start_date until before end_date. Offset extends range by offset days"
for n in range(int((end_date - start_date).days) + offset):
yield start_date + datetime.timedelta(n)
def spread_date_range(start, end, row, columns):
"take some values and spread it over a period of dates in proportion to data already there"
r = list(daterange(start, end, offset=1))
stats = [float(p) / len(r) for p in row]
results = pd.DataFrame(
[
[
date,
]
+ stats
for date in r
],
columns=columns,
).set_index("Date")
return results
####################
# Extraction helpers
#####################
def parse_file(filename, html=False, paged=True):
pages_txt = []
# Read PDF file
data = parser.from_file(filename, xmlContent=True)
xhtml_data = BeautifulSoup(data["content"], features="lxml")
if html and not paged:
return xhtml_data
pages = xhtml_data.find_all("div", attrs={"class": ["page", "slide-content"]})
if not pages:
if not paged:
return repr(xhtml_data)
else:
return [repr(xhtml_data)]
# TODO: slides are divided by slide-content and slide-master-content rather than being contained
for i, content in enumerate(pages):
# Parse PDF data using TIKA (xml/html)
# It's faster and safer to create a new buffer than truncating it
# https://stackoverflow.com/questions/4330812/how-do-i-clear-a-stringio-object
_buffer = StringIO()
_buffer.write(str(content))
parsed_content = parser.from_buffer(_buffer.getvalue())
if parsed_content["content"] is None:
continue
# Add pages
text = parsed_content["content"].strip()
if html:
pages_txt.append(repr(content))
else:
pages_txt.append(text)
if paged:
return pages_txt
else:
return '\n\n\n'.join(pages_txt)
NUM_RE = re.compile(r"\d+(?:\,\d+)*(?:\.\d+)?")
INT_RE = re.compile(r"\d+(?:\,\d+)*")
def get_next_numbers(content, *matches, debug=False, before=False, remove=0, ints=True, until=None):
if len(matches) == 0:
matches = [""]
for match in matches:
if type(match) == str:
match = re.compile(f"({match})")
ahead, *behind = match.split(content, 1) if match else ("", "", content)
if not behind:
continue
matched, *behind = behind
behind = "".join(behind)
found = ahead if before else behind
if until is not None and until in found:
found, rest = found.split(until, 1) # TODO: how to put it back togeather if behind=True?
rest = until+rest
else:
rest = ""
numbers = (INT_RE if ints else NUM_RE).findall(found)
numbers = [n.replace(",", "") for n in numbers]
numbers = [int(n) if ints else float(n) for n in numbers if n]
numbers = numbers if not before else list(reversed(numbers))
if remove:
behind = (INT_RE if ints else NUM_RE).sub("", found, remove)
return numbers, matched + " " + rest + behind
if debug and matches:
print("Couldn't find '{}'".format(match))
print(content)
return [], content
def get_next_number(content, *matches, default=None, remove=False, before=False, until=None):
num, rest = get_next_numbers(content, *matches, remove=1 if remove else 0, before=before, until=until)
return num[0] if num else default, rest
def slide2text(slide):
text = ""
if slide.shapes.title:
text += slide.shapes.title.text
for shape in slide.shapes:
if shape.has_text_frame:
# for p in shape.text_frame:
text += "\n" + shape.text
return text
def slide2chartdata(slide):
for shape in slide.shapes:
if not shape.has_chart:
continue
chart = shape.chart
if chart is None:
continue
title = chart.chart_title.text_frame.text if chart.has_title else ""
start, end = find_date_range(title)
if start is None:
continue
series = dict([(s.name, s.values) for s in chart.series])
yield chart, title, start, end, series
####################
# Download helpers
####################
def is_remote_newer(file, remote_date, check=True):
if not os.path.exists(file):
print(f"Missing: {file}")
return True
elif os.stat(file).st_size == 0:
return True
elif not check:
return False
elif remote_date is None:
return True # TODO: should we always keep cached?
if type(remote_date) == str:
remote_date = dateutil.parser.parse(remote_date).astimezone()
fdate = datetime.datetime.fromtimestamp(os.path.getmtime(file)).astimezone()
if remote_date > fdate:
timestamp = fdate.strftime("%Y%m%d-%H%M%S")
os.rename(file, f"{file}.{timestamp}")
return True
return False
def web_links(*index_urls, ext=".pdf", dir="html", match=None):
def is_ext(a):
return len(a.get("href").rsplit(ext)) == 2 if ext else True
def is_match(a):
return a.get("href") and is_ext(a) and (match.search(a.get_text(strip=True)) if match else True)
for index_url in index_urls:
for file, index in web_files(index_url, dir=dir, check=True):
soup = parse_file(file, html=True, paged=False)
links = (urllib.parse.urljoin(index_url, a.get('href')) for a in soup.find_all('a') if is_match(a))
for l in links:
yield l
def web_files(*urls, dir=os.getcwd(), check=CHECK_NEWER):
"if check is None, then always download"
for url in urls:
modified = s.head(url).headers.get("last-modified") if check else None
file = url.rsplit("/", 1)[-1]
file = os.path.join(dir, file)
os.makedirs(os.path.dirname(file), exist_ok=True)
if is_remote_newer(file, modified, check):
r = s.get(url)
if r.status_code == 200:
print(f"Download: {file}", end="")
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "wb") as f:
for chunk in r.iter_content(chunk_size=512 * 1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
print(".", end="")
print("")
elif os.path.exists(file):
print(f"Error downloading: {file}: using cache")
else:
print(f"Error downloading: {file}: skipping")
continue
with open(file, "rb") as f:
content = f.read()
yield file, content
def dav_files(url="http://nextcloud.dmsc.moph.go.th/public.php/webdav", username="wbioWZAQfManokc", password="null",
ext=".pdf .pptx", dir="testing_moph"):
options = {
"webdav_hostname": url,
"webdav_login": username,
"webdav_password": password,
}
client = Client(options)
client.session.mount("http://", HTTPAdapter(max_retries=RETRY))
client.session.mount("https://", HTTPAdapter(max_retries=RETRY))
# important we get them sorted newest files first as we only fill in NaN from each additional file
files = sorted(
client.list(get_info=True),
key=lambda info: dateutil.parser.parse(info["modified"]),
reverse=True,
)
for info in files:
file = info["path"].split("/")[-1]
if not any([ext == file[-len(ext):] for ext in ext.split()]):
continue
target = os.path.join(dir, file)
os.makedirs(os.path.dirname(target), exist_ok=True)
if is_remote_newer(target, info["modified"]):
client.download_file(file, target)
yield target
##########################################
# download and parse thailand covid data
##########################################
d = dateutil.parser.parse
def situation_cases_cum(parsed_pdf, date):
_, rest = get_next_numbers(parsed_pdf, "The Disease Situation in Thailand", debug=True)
cases, rest = get_next_numbers(
rest,
"Total number of confirmed cases",
"Characteristics of Infection in Confirmed cases",
"Confirmed cases",
debug=False
)
if not cases:
return pd.DataFrame()
cases, *_ = cases
if date < d("2020-04-09"):
return pd.DataFrame([(date, cases)], columns=["Date", "Cases Cum"]).set_index("Date")
outside_quarantine, _ = get_next_numbers(
rest,
"Cases found outside (?:the )?(?:state )?quarantine (?:facilities|centers)",
debug=False
)
if outside_quarantine:
outside_quarantine, *_ = outside_quarantine
# 2647.0 # 2021-02-15
# if date > d("2021-01-25"):
# # thai graphic says imported is 2396 instead of en 4195 on 2021-01-26
# outside_quarantine = outside_quarantine - (4195 - 2396)
quarantine, _ = get_next_number(
rest,
"Cases found in (?:the )?(?:state )?quarantine (?:facilities|centers)",
"Staying in [^ ]* quarantine",
default=0, until="●")
quarantine = 1903 if quarantine == 19003 else quarantine # "2021-02-05"
# TODO: work out date when it flips back again.
if date == d("2021-05-17"):
imported = quarantine = outside_quarantine
outside_quarantine = 0
elif date < d("2020-12-28") or (date > d("2021-01-25") and outside_quarantine > quarantine):
imported = outside_quarantine # It's mislabeled (new daily is correct however)
imported = 2647 if imported == 609 else imported # "2021-02-17")
imported = None if imported == 610 else imported # 2021-02-20 - 2021-03-01
if imported is not None:
outside_quarantine = imported - quarantine
else:
outside_quarantine = None
else:
imported = outside_quarantine + quarantine
else:
quarantine, _ = get_next_numbers(
rest,
"(?i)d.?e.?signated quarantine",
debug=False)
quarantine, *_ = quarantine if quarantine else [None]
quarantine = 562 if quarantine == 5562 else quarantine # "2021-09-19"
imported, _ = get_next_number(
rest,
"(?i)Imported Case(?:s)?",
"(?i)Cases were imported from overseas")
if imported and quarantine:
outside_quarantine = imported - quarantine
else:
outside_quarantine = None #TODO: can we get imported from total - quarantine - local?
if quarantine:
active, _ = get_next_number(
rest,
"(?i)Cases found from active case finding",
"(?i)Cases were (?:infected )?migrant workers",
)
prison, _ = get_next_number(rest, "Cases found in Prisons", default=0)
if active is not None:
active += prison
# TODO: cum local really means all local ie walkins+active testing
local, _ = get_next_number(rest, "(?i)(?:Local )?Transmission")
# TODO: 2021-01-25. Local 6629.0 -> 12250.0, quarantine 597.0 -> 2396.0 active 4684.0->5532.0
if imported is None:
pass
elif cases-imported == active:
walkin = local
local = cases-imported
active = local - walkin
elif active is None:
pass
elif local + active == cases-imported:
# switched to different definition?
walkin = local
local = walkin + active
elif date <= d("2021-01-25") or d("2021-02-16") <= date <= d("2021-03-01"):
walkin = local
local = walkin + active
else:
local, active = None, None
#assert cases == (local+imported) # Too many mistakes
return pd.DataFrame(
[(date, cases, local, imported, quarantine, outside_quarantine, active)],
columns=["Date", "Cases Cum", "Cases Local Transmission Cum", "Cases Imported Cum", "Cases In Quarantine Cum", "Cases Outside Quarantine Cum", "Cases Proactive Cum"]
).set_index("Date")
def situation_cases_new(parsed_pdf, date):
if date < d("2020-11-02"):
return pd.DataFrame()
_, rest = get_next_numbers(
parsed_pdf,
"The Disease Situation in Thailand",
"(?i)Type of case Total number Rate of Increase",
debug=False)
cases, rest = get_next_numbers(
rest,
"(?i)number of new case(?:s)?",
debug=False
)
if not cases or date < d("2020-05-09"):
return pd.DataFrame()
cases, *_ = cases
local, _ = get_next_numbers(rest, "(?i)(?:Local )?Transmission", debug=False)
local, *_ = local if local else [None]
quarantine, _ = get_next_numbers(
rest,
"Cases found (?:positive from |in )(?:the )?(?:state )?quarantine",
#"Staying in [^ ]* quarantine",
debug=False)
quarantine, *_ = quarantine
quarantine = {d("2021-01-27"): 11}.get(date, quarantine) # corrections from thai doc
outside_quarantine, _ = get_next_numbers(
rest,
"(?i)Cases found (?:positive )?outside (?:the )?(?:state )?quarantine",
debug=False
)
outside_quarantine, *_ = outside_quarantine if outside_quarantine else [None]
if outside_quarantine is not None:
imported = quarantine + outside_quarantine
active, _ = get_next_numbers(
rest,
"(?i)active case",
debug=True
)
active, *_ = active if active else [None]
if date <= d("2020-12-24"): # starts getting cum values
active = None
# local really means walkins. so need add it up
if active:
local = local + active
else:
imported, active = None, None
cases = {d("2021-03-31"): 42}.get(date, cases)
#if date not in [d("2020-12-26")]:
# assert cases == (local+imported) # except 2020-12-26 - they didn't include 30 proactive
return pd.DataFrame(
[(date, cases, local, imported, quarantine, outside_quarantine, active)],
columns=["Date", "Cases", "Cases Local Transmission", "Cases Imported", "Cases In Quarantine", "Cases Outside Quarantine", "Cases Proactive"]
).set_index("Date")
re_walkin_priv = re.compile("(?i)cases (in|at) private hospitals")
def situation_pui(parsed_pdf, date):
numbers, _ = get_next_numbers(
parsed_pdf, "Total +number of laboratory tests",
until="Sought medical services on their own at hospitals",
debug=False
)
if numbers:
if len(numbers) == 7:
tests_total, pui, active_finding, asq, not_pui, pui2, pui_port, *rest = numbers
elif len(numbers) == 6:
tests_total, pui, asq, not_pui, pui2, pui_port, *rest = numbers
active_finding = None
else:
raise Exception(numbers)
pui = {309371: 313813}.get(pui, pui) # 2020-07-01
#TODO: find 1529045 below and see which is correct 20201-04-26
pui2 = pui if pui2 in [96989, 433807, 3891136, 385860, 326073, 1529045] else pui2
assert pui == pui2
else:
numbers, _ = get_next_numbers(
parsed_pdf, "Total number of people who met the criteria of patients", debug=False,
)
if date > dateutil.parser.parse("2020-01-30") and not numbers:
raise Exception(f"Problem parsing {date}")
elif not numbers:
return pd.DataFrame()
tests_total, active_finding, asq, not_pui = [None] * 4
pui, pui_airport, pui_seaport, pui_hospital, *rest = numbers
# pui_port = pui_airport + pui_seaport
if pui in [1103858, 3891136]: # mistypes? # 433807?
pui = None
elif tests_total in [783679, 849874, 936458]:
tests_total = None
elif None in (tests_total, pui, asq, not_pui) and date > d("2020-06-30"):
raise Exception(f"Missing data at {date}")
# walkin public vs private
numbers, rest = get_next_numbers(parsed_pdf, "Sought medical services on their own at hospitals")
if not numbers:
pui_walkin_private, pui_walkin_public, pui_walkin = [None]*3
elif re_walkin_priv.search(rest):
pui_walkin_private, pui_walkin_public, pui_walkin, *_ = numbers
pui_walkin_public = {8628765: 862876}.get(pui_walkin_public, pui_walkin_public)
#assert pui_walkin == pui_walkin_private + pui_walkin_public
else:
pui_walkin, *_ = numbers
pui_walkin_private, pui_walkin_public = None, None
pui_walkin = {853189: 85191}.get(pui_walkin, pui_walkin) # by taking away other numbers
assert pui_walkin is None or pui is None or (pui_walkin <= pui and 5000000 > pui_walkin > 0)
assert pui_walkin_public is None or (5000000 > pui_walkin_public > 10000)
row = (tests_total, pui, active_finding, asq, not_pui, pui_walkin, pui_walkin_private, pui_walkin_public)
return pd.DataFrame(
[(date, )+row],
columns=[
"Date",
"Tested Cum",
"Tested PUI Cum",
"Tested Proactive Cum",
"Tested Quarantine Cum",
"Tested Not PUI Cum",
"Tested PUI Walkin Cum",
"Tested PUI Walkin Private Cum",
"Tested PUI Walkin Public Cum",
]
).set_index("Date")
def get_en_situation():
results = pd.DataFrame(columns=["Date"]).set_index("Date")
url = "https://ddc.moph.go.th/viralpneumonia/eng/situation.php"
for file, _ in web_files(*web_links(url, ext=".pdf", dir="situation_en"), dir="situation_en"):
parsed_pdf = parse_file(file, html=False, paged=False).replace("\u200b", "")
if "situation" not in os.path.basename(file):
continue
date = file2date(file)
if date <= dateutil.parser.parse("2020-01-30"):
continue # TODO: can manually put in numbers before this
pui = situation_pui(parsed_pdf, date)
cases = situation_cases_cum(parsed_pdf, date)
new_cases = situation_cases_new(parsed_pdf, date)
row = pui.combine_first(cases).combine_first(new_cases)
results = results.combine_first(row)
# cums = [c for c in results.columns if ' Cum' in c]
# if len(results) > 1 and (results.iloc[0][cums] > results.iloc[1][cums]).any():
# print((results.iloc[0][cums] > results.iloc[1][cums]))
# print(results.iloc[0:2])
# raise Exception("Cumulative data didn't increase")
# row = results.iloc[0].to_dict()
print(date.date(), file, row.to_string(header=False, index=False))
# "p{Tested PUI Cum:.0f}\tc{Cases Cum:.0f}({Cases:.0f})\t"
# "l{Cases Local Transmission Cum:.0f}({Cases Local Transmission:.0f})\t"
# "a{Cases Proactive Cum:.0f}({Cases Proactive:.0f})\t"
# "i{Cases Imported Cum:.0f}({Cases Imported:.0f})\t"
# "q{Cases In Quarantine Cum:.0f}({Cases In Quarantine:.0f})\t"
# "".format(**row)
# )
# Missing data. filled in from th infographic
missing = [
(d("2020-12-19"), 2476, 0, 0),
(d("2020-12-20"), 3011, 516, 516),
(d("2020-12-21"), 3385, 876, 360),
(d("2020-12-22"), 3798, 1273, 397),
(d("2020-12-23"), 3837, 1273, 0),
(d("2020-12-24"), 3895, 1273, 0),
(d("2020-12-25"), 3976, 1308, 35),
]
missing = pd.DataFrame(
missing,
columns=["Date", "Cases Local Transmission Cum", "Cases Proactive Cum", "Cases Proactive"]
).set_index("Date")
results = missing[["Cases Local Transmission Cum", "Cases Proactive Cum", ]].combine_first(results)
return results
def get_situation_today():
_, page = next(web_files("https://ddc.moph.go.th/viralpneumonia/index.php", dir="situation_th", check=True))
text = BeautifulSoup(page, 'html.parser').get_text()
numbers, rest = get_next_numbers(text, "ผู้ป่วยเข้าเกณฑ์เฝ้าระวัง")
pui_cum, pui = numbers[:2]
numbers, rest = get_next_numbers(text, "กักกันในพื้นที่ที่รัฐกำหนด")
imported_cum, imported = numbers[:2]
numbers, rest = get_next_numbers(text, "ผู้ป่วยยืนยัน")
cases_cum, cases = numbers[:2]
numbers, rest = get_next_numbers(text, "สถานการณ์ในประเทศไทย")
date = find_thai_date(rest).date()
row = [cases_cum, cases, pui_cum, pui, imported_cum, imported]
return pd.DataFrame(
[[date, ]+row],
columns=["Date", "Cases Cum", "Cases", "Tested PUI Cum", "Tested PUI", "Cases Imported Cum", "Cases Imported"]
).set_index("Date")
def check_cum(df, results):
if results.empty:
return True
next_day = results.loc[results.index[0]][[c for c in results.columns if " Cum" in c]]
last = df.loc[df.index[-1]][[c for c in df.columns if " Cum" in c]]
if (next_day.fillna(0) >= last.fillna(0)).all():
return True
else:
raise Exception(str(next_day - last))
def situation_pui_th(parsed_pdf, date, results):
tests_total, active_finding, asq, not_pui = [None] * 4
numbers, content = get_next_numbers(
parsed_pdf,
r"ด่านโรคติดต่อระหว่างประเทศ",
r"ด่านโรคติดต่อระหวา่งประเทศ", # 'situation-no346-141263n.pdf'
r"นวนการตรวจทาง\S+องปฏิบัติการ",
"ด่านควบคุมโรคติดต่อระหว่างประเทศ",
)
# cases = None
if len(numbers) > 6:
(
screened_port,
screened_cw,
tests_total,
pui,
active_finding,
asq,
not_pui,
*rest,
) = numbers
if tests_total < 30000:
tests_total, pui, active_finding, asq, not_pui, *rest = numbers
if pui == 4534137:
pui = 453413 # situation-no273-021063n.pdf
else:
numbers, content = get_next_numbers(
parsed_pdf,
# "ผู้ป่วยที่มีอาการเข้าได้ตามนิยาม",
"ตาราง 2 ผลดำ",
"ตาราง 1", # situation-no172-230663.pdf #'situation-no83-260363_1.pdf'
)
if len(numbers) > 0:
pui, *rest = numbers
if date > dateutil.parser.parse("2020-03-26") and not numbers:
raise Exception(f"Problem parsing {date}")
elif not numbers:
return
if tests_total == 167515: # situation-no447-250364.pdf
tests_total = 1675125
if date in [d("2020-12-23")]: # 1024567
tests_total, not_pui = 997567, 329900
if (
tests_total is not None
and tests_total > 2000000 < 30000
or pui > 1500000 < 100000
):
raise Exception(f"Bad data in {date}")
pui = {d("2020-02-12"): 799, d("2020-02-13"): 804}.get(date, pui) # Guess
walkinsre = "(?:ษาที่โรงพยาบาลด้วยตนเอง|โรงพยาบาลด้วยตนเอง|ารับการรักษาท่ีโรงพยาบาลด|โรงพยาบาลดวยตนเอง)"
_, line = get_next_numbers(parsed_pdf, walkinsre)
pui_walkin_private, rest = get_next_number(line, f"(?s){walkinsre}.*?โรงพยาบาลเอกชน", remove=True)
pui_walkin_public, rest = get_next_number(rest, f"(?s){walkinsre}.*?โรงพยาบาลรัฐ", remove=True)
unknown, rest = get_next_number(rest, f"(?s){walkinsre}.*?(?:งการสอบสวน|ารสอบสวน)", remove=True)
#rest = re.sub("(?s)(?:งการสอบสวน|ารสอบสวน).*?(?:อ่ืนๆ|อื่นๆ|อืน่ๆ|ผู้ป่วยยืนยันสะสม|88)?", "", rest,1)
pui_walkin, rest = get_next_number(rest)
assert pui_walkin is not None
if date <= d("2020-03-10"):
pui_walkin_private, pui_walkin, pui_walkin_public = [None] * 3 # starts going up again
#pui_walkin_private = {d("2020-03-10"):2088}.get(date, pui_walkin_private)
assert pui_walkin is None or pui is None or (pui_walkin <= pui and pui_walkin > 0)
row = (tests_total, pui, active_finding, asq, not_pui, pui_walkin_private, pui_walkin_public, pui_walkin)
if None in row and date > d("2020-06-30"):
raise Exception(f"Missing data at {date}")
df = pd.DataFrame(
[(date,)+row],
columns=[
"Date",
"Tested Cum",
"Tested PUI Cum",
"Tested Proactive Cum",
"Tested Quarantine Cum",
"Tested Not PUI Cum",
"Tested PUI Walkin Private Cum",
"Tested PUI Walkin Public Cum",
"Tested PUI Walkin Cum"]
).set_index("Date")
assert check_cum(df, results)
return df
def get_thai_situation():
results = pd.DataFrame(columns=["Date"]).set_index("Date")
links = web_links(
"https://ddc.moph.go.th/viralpneumonia/situation.php",
"https://ddc.moph.go.th/viralpneumonia/situation_more.php",
ext=".pdf",
dir="situation_th"
)
for file, _ in web_files(*links, dir="situation_th"):
parsed_pdf = parse_file(file, html=False, paged=False)
if "situation" not in os.path.basename(file):
continue
if "Situation Total number of PUI" in parsed_pdf:
# english report mixed up? - situation-no171-220663.pdf
continue
date = file2date(file)
df = situation_pui_th(parsed_pdf, date, results)
if df is not None:
results = results.combine_first(df)
print(date.date(), file, df.to_string(header=False, index=False))
# file,
# "p{Tested PUI Cum:.0f}\t"
# "t{Tested Cum:.0f}\t"
# "{Tested Proactive Cum:.0f}\t"
# "{Tested Quarantine Cum:.0f}\t"
# "{Tested Not PUI Cum:.0f}\t"
# "".format(**results.iloc[0].to_dict()))
#print(results)
return results
def cum2daily(results):
cum = results[(c for c in results.columns if " Cum" in c)]
all_days = pd.date_range(cum.index.min(), cum.index.max(), name="Date")
cum = cum.reindex(all_days) # put in missing days with NaN
#cum = cum.interpolate(limit_area="inside") # missing dates need to be filled so we don't get jumps
cum = cum - cum.shift(+1) # we got cumilitive data
renames = dict((c, c.rstrip(' Cum')) for c in list(cum.columns) if 'Cum' in c)
cum = cum.rename(columns=renames)
return cum
def get_situation():
print("========Situation Reports==========")
today_situation = get_situation_today()
en_situation = get_en_situation()
th_situation = get_thai_situation()
situation = th_situation.combine_first(en_situation)
cum = cum2daily(situation)
situation = situation.combine_first(cum) # any direct non-cum are trusted more
# Only add in the live stats if they have been updated with new info
today = today_situation.index.max()
yesterday = today-datetime.timedelta(days=1)
stoday = today_situation.loc[today]
syesterday = situation.loc[str(yesterday)] if str(yesterday) in situation else None
if syesterday is None or (syesterday['Tested PUI Cum'] < stoday['Tested PUI Cum'] and syesterday['Tested PUI'] != stoday['Tested PUI']):
situation = situation.combine_first(today_situation)
export(situation, "situation_reports")
return situation
def get_cases():
print("========Covid19 Timeline==========")
file, text = next(web_files("https://covid19.th-stat.com/api/open/timeline?123", dir="json", check=True))
data = pd.DataFrame(json.loads(text)['Data'])
data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index("Date")
cases = data[["NewConfirmed", "NewDeaths", "NewRecovered", "Hospitalized"]]
cases = cases.rename(columns=dict(NewConfirmed="Cases", NewDeaths="Deaths", NewRecovered="Recovered"))
return cases
def get_tests_by_day():
print("========Tests by Day==========")
file = next(dav_files(ext="xlsx"))
tests = pd.read_excel(file, parse_dates=True, usecols=[0, 1, 2])
tests.dropna(how="any", inplace=True) # get rid of totals row
tests = tests.set_index("Date")
pos = tests.loc["Cannot specify date"].Pos
total = tests.loc["Cannot specify date"].Total
tests.drop("Cannot specify date", inplace=True)
# Need to redistribute the unknown values across known values
# Documentation tells us it was 11 labs and only before 3 April
unknown_end_date = datetime.datetime(day=3, month=4, year=2020)
all_pos = tests["Pos"][:unknown_end_date].sum()
all_total = tests["Total"][:unknown_end_date].sum()
for index, row in tests.iterrows():
if index > unknown_end_date:
continue
row.Pos = float(row.Pos) + row.Pos / all_pos * pos
row.Total = float(row.Total) + row.Total / all_total * total
# TODO: still doesn't redistribute all missing values due to rounding. about 200 left
#print(tests["Pos"].sum(), pos + all_pos)
#print(tests["Total"].sum(), total + all_total)
# fix datetime
tests.reset_index(drop=False, inplace=True)
tests["Date"] = pd.to_datetime(tests["Date"])
tests.set_index("Date", inplace=True)
tests.rename(columns=dict(Pos="Pos XLS", Total="Tests XLS"), inplace=True)
print(file, len(tests))
return tests
DISTRICT_RANGE_SIMPLE = [str(i) for i in range(1, 14)]
DISTRICT_RANGE = DISTRICT_RANGE_SIMPLE + ["Prison"]
DISTRICT_RANGE_UNKNOWN = [str(i) for i in range(1, 14)] + ["Prison", "Unknown"]
def get_tests_by_area():
pos_cols = [f"Pos Area {i}" for i in DISTRICT_RANGE_SIMPLE]
test_cols = [f"Tests Area {i}" for i in DISTRICT_RANGE_SIMPLE]
columns = ["Date"] + pos_cols + test_cols + ["Pos Area", "Tests Area"]
raw_cols = ["Start", "End", ] + pos_cols + test_cols
data = pd.DataFrame()
raw = pd.DataFrame()
for file in dav_files(ext=".pptx"):
prs = Presentation(file)
for chart in (
chart for slide in prs.slides for chart in slide2chartdata(slide)
):
chart, title, start, end, series = chart
if "เริ่มเปิดบริการ" not in title and any(
t in title for t in ["เขตสุขภาพ", "เขตสุขภำพ"]
):
# the graph for X period split by health area.
# Need both pptx and pdf as one pdf is missing
pos = list(series["จำนวนผลบวก"])
tests = list(series["จำนวนตรวจ"])
row = pos + tests + [sum(pos), sum(tests)]
results = spread_date_range(start, end, row, columns)
# print(results)
data = data.combine_first(results)
raw = raw.combine_first(pd.DataFrame(
[[start, end, ]+pos + tests],
columns=raw_cols
).set_index("Start"))
print(file)
# Also need pdf copies becaus of missing pptx
for file in dav_files(ext=".pdf"):
pages = parse_file(file, html=False, paged=True)
not_whole_year = [page for page in pages if "เริ่มเปิดบริการ" not in page]
by_area = [
page
for page in not_whole_year
if "เขตสุขภาพ" in page or "เขตสุขภำพ" in page
]
# Can't parse '35_21_12_2020_COVID19_(ถึง_18_ธันวาคม_2563)(powerpoint).pptx' because data is a graph
# no pdf available so data missing
# Also missing 14-20 Nov 2020 (no pptx or pdf)
for page in by_area:
start, end = find_date_range(page)
if start is None:
continue
if "349585" in page:
page = page.replace("349585", "349 585")
# if '16/10/2563' in page:
# print(page)
# First line can be like จดัท ำโดย เพญ็พชิชำ ถำวงศ ์กรมวิทยำศำสตณก์ำรแพทย์ วันที่ท ำรำยงำน 15/02/2564 เวลำ 09.30 น.
first, rest = page.split("\n", 1)
page = (
rest if "เพญ็พชิชำ" in first or "/" in first else page
) # get rid of first line that sometimes as date and time in it
numbers, content = get_next_numbers(page, "", debug=True) # "ภาคเอกชน",
# ภาครัฐ
# ภาคเอกชน
# จดัท ำโดย เพญ็พชิชำ ถำวงศ ์กรมวิทยำศำสตณก์ำรแพทย์
# print(numbers)
# TODO: should really find and parse X axis labels which contains 'เขต' and count
tests_start = 13 if "total" not in page else 14
pos = numbers[0:13]
tests = numbers[tests_start:tests_start + 13]
row = pos + tests + [sum(pos), sum(tests)]
results = spread_date_range(start, end, row, columns)
#print(results)