forked from djay/covidthailand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcovid_data.py
3337 lines (2984 loc) · 166 KB
/
covid_data.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
import datetime
import functools
import dateutil
from dateutil.parser import parse as d
from dateutil.relativedelta import relativedelta
from itertools import chain, islice
import json
import os
import re
import copy
import codecs
import shutil
import time
from bs4 import BeautifulSoup
import camelot
import numpy as np
import pandas as pd
import requests
from requests.exceptions import ConnectionError
from utils_pandas import add_data, check_cum, cum2daily, daily2cum, daterange, export, fuzzy_join, import_csv, \
spread_date_range, cut_ages
from utils_scraping import CHECK_NEWER, MAX_DAYS, USE_CACHE_DATA, any_in, dav_files, get_next_number, get_next_numbers, \
get_tweets_from, pairwise, parse_file, parse_numbers, pptx2chartdata, remove_suffix, replace_matcher, seperate, split, \
strip, toint, unique_values,\
web_files, web_links, all_in, NUM_OR_DASH, s
from utils_scraping_tableau import workbook_flatten, workbook_iterate, workbook_explore
from utils_thai import DISTRICT_RANGE, area_crosstab, file2date, find_date_range, \
find_thai_date, get_province, join_provinces, parse_gender, to_thaiyear, today, \
get_fuzzy_provinces, POS_COLS, TEST_COLS
##########################################
# Situation reports/PUI
##########################################
def situation_cases_cum(parsed_pdf, date):
prison = None
_, rest = get_next_numbers(parsed_pdf, "Disease Situation in Thailand", debug=False)
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, prison)],
columns=["Date", "Cases Cum", "Cases Local Transmission Cum", "Cases Imported Cum",
"Cases In Quarantine Cum", "Cases Outside Quarantine Cum", "Cases Proactive Cum", "Cases Area Prison 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")
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, active_finding, pui2, pui_port, *rest = numbers
not_pui = None
# TODO latest reports have not_pui in same place as active_finding
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, 2159780, 278178, 2774962] 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, active_finding) 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.search("(?i)cases (in|at) private hospitals", 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)
assert pui is None or pui > 0, f"Invalid pui situation_en {date}"
if not_pui is not None:
active_finding += not_pui
row = (tests_total, pui, active_finding, asq, 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 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
parsed_pdf = parsed_pdf.replace("DDC Thailand 1", "") # footer put in teh wrong place
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 situation_pui_th_death(dfsit, parsed_pdf, date, file):
if "40 – 59" not in parsed_pdf:
return dfsit
numbers, rest = get_next_numbers(parsed_pdf, "15 – 39", until="40 – 59", ints=False)
if len(numbers) == 3:
a1_w1, a1_w2, a1_w3 = numbers
a2_w1, a2_w2, a2_w3 = get_next_numbers(rest, "40 – 59", until=" 60 ", ints=False, return_rest=False)
a3_w1, a3_w2, a3_w3, *_ = get_next_numbers(rest, " 60 ", ints=False, return_rest=False)
else:
# Actually uses 20-39 here but we will assume no one 15-20 died before this changed
_, rest = get_next_numbers(parsed_pdf, "40 – 59", until=" 60 ", ints=False)
numbers = get_next_numbers(rest, "2 เดือน 1", " 60 ปีขึ้นไป", ints=False, return_rest=False)
a1_w1, a2_w1, a3_w1, a1_w2, a2_w2, a3_w2, a1_w3, a2_w3, a3_w3, *_ = numbers
# else:
# a3_w3, a2_w3, a1_w3, *_ = get_next_numbers(text,
# "วหรือภำวะเส่ียง",
# "หรือสูงอำยุ",
# "มีโรคประจ",
# "หรือภำวะเส่ียง",
# before=True,
# ints=False,
# return_rest=False)
assert 0 <= a3_w3 <= 25
assert 0 <= a2_w3 <= 25
assert 0 <= a1_w3 <= 25
# time to treatment
numbers = get_next_numbers(
parsed_pdf,
"ระยะเวลำเฉล่ียระหว่ำงวันเร่ิมป่วย",
"ระยะเวลำเฉล่ียระหว่ำงวันเร่ิม",
"ถึงวันได้รับรักษา",
ints=False,
return_rest=False)
if numbers:
w1_avg, w1_min, w1_max, w2_avg, w2_min, w2_max, w3_avg, w3_min, w3_max, *_ = numbers
else:
# 'situation_th/situation-no598-230864.pdf'
w3_avg, w3_min, w3_max = [np.nan] * 3
columns = [
"Date", "W3 CFR 15-39", "W3 CFR 40-59", "W3 CFR 60-", "W3 Time To Treatment Avg", "W3 Time To Treatment Min",
"W3 Time To Treatment Max"
]
df = pd.DataFrame([[date, a1_w3, a2_w3, a3_w3, w3_avg, w3_min, w3_max]], columns=columns).set_index("Date")
print(date.date(), "Death Ages", df.to_string(header=False, index=False))
return dfsit.combine_first(df)
def situation_pui_th(dfpui, parsed_pdf, date, file):
tests_total, active_finding, asq, not_pui = [None] * 4
numbers, content = get_next_numbers(
parsed_pdf,
r"ด่านโรคติดต่อระหว่างประเทศ",
r"ด่านโรคติดต่อระหวา่งประเทศ", # 'situation-no346-141263n.pdf'
r"นวนการตรวจทาง\S+องปฏิบัติการ",
"ด่านควบคุมโรคติดต่อระหว่างประเทศ",
until="(?:โรงพยาบาลด้วยตนเอง|ารับการรักษาท่ีโรงพยาบาลด|โรงพยาบาลเอกชน)"
)
# cases = None
if len(numbers) == 7: # numbers and numbers[2] < 30000:
tests_total, pui, active_finding, asq, not_pui, *rest = numbers
if pui == 4534137:
pui = 453413 # situation-no273-021063n.pdf
elif len(numbers) > 8:
_, _, tests_total, pui, active_finding, asq, not_pui, *rest = numbers
elif len(numbers) == 8:
# 2021 - removed not_pui
_, _, tests_total, pui, asq, active_finding, pui2, *rest = numbers
assert pui == pui2
not_pui = None
elif len(numbers) == 6: # > 2021-05-10
tests_total, pui, asq, active_finding, pui2, screened = numbers
assert pui == pui2
not_pui = None
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 finding PUI numbers for date {date}")
elif not numbers:
return dfpui
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)
if not_pui is not None:
active_finding += not_pui # later reports combined it anyway
row = (tests_total, pui, active_finding, asq, 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}")
assert pui is None or pui > 0, f"Invalid pui situation_th {date}"
cols = ["Tested Cum",
"Tested PUI Cum",
"Tested Proactive Cum",
"Tested Quarantine Cum",
"Tested PUI Walkin Private Cum",
"Tested PUI Walkin Public Cum",
"Tested PUI Walkin Cum"]
df = pd.DataFrame(
[(date,) + row],
columns=["Date"] + cols
).set_index("Date")
assert check_cum(df, dfpui, cols)
dfpui = dfpui.combine_first(df)
print(date.date(), file, df.to_string(header=False, index=False))
return dfpui
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)
results = situation_pui_th(results, parsed_pdf, date, file)
results = situation_pui_th_death(results, parsed_pdf, date, file)
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]
assert not any_in(row, None)
assert pui > 0
return pd.DataFrame(
[[date, ] + row],
columns=["Date", "Cases Cum", "Cases", "Tested PUI Cum", "Tested PUI", "Cases Imported Cum", "Cases Imported"]
).set_index("Date")
def get_situation():
print("========Situation Reports==========")
today_situation = get_situation_today()
th_situation = get_thai_situation()
en_situation = get_en_situation()
situation = import_csv("situation_reports", ["Date"],
not USE_CACHE_DATA).combine_first(th_situation).combine_first(en_situation)
cum = cum2daily(situation)
situation = situation.combine_first(cum) # any direct non-cum are trusted more
# TODO: Not sure but 5 days have 0 PUI. Take them out for now
# Date
# 2020-02-12 0.0
# 2020-02-14 0.0
# 2020-10-13 0.0
# 2020-12-29 0.0
# 2021-05-02 0.0
situation['Tested PUI'] = situation['Tested PUI'].replace(0, np.nan)
# 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:
situation = situation.combine_first(today_situation)
elif 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
#################################
# Cases Apis
#################################
def get_cases():
print("========Covid19 Timeline==========")
try:
file, text, url = next(
web_files("https://covid19.th-stat.com/json/covid19v2/getTimeline.json", dir="json", check=True))
except ConnectionError:
# I think we have all this data covered by other sources. It's a little unreliable.
return pd.DataFrame()
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"))
cases["Source Cases"] = url
return cases
@functools.lru_cache(maxsize=100, typed=False)
def get_case_details_csv():
if False:
return get_case_details_api()
url = "https://data.go.th/dataset/covid-19-daily"
file, text, _ = next(web_files(url, dir="json", check=True))
data = re.search(r"packageApp\.value\('meta',([^;]+)\);", text.decode("utf8")).group(1)
apis = json.loads(data)
links = [api['url'] for api in apis if "รายงานจำนวนผู้ติดเชื้อ COVID-19 ประจำวัน" in api['name']]
# get earlier one first
links = sorted([link for link in links if '.php' not in link and '.xlsx' not in link], reverse=True)
# 'https://data.go.th/dataset/8a956917-436d-4afd-a2d4-59e4dd8e906e/resource/be19a8ad-ab48-4081-b04a-8035b5b2b8d6/download/confirmed-cases.csv'
cases = pd.DataFrame()
for file, _, _ in web_files(*links, dir="json", check=True, strip_version=True, appending=True):
if file.endswith(".xlsx"):
continue
#cases = pd.read_excel(file)
elif file.endswith(".csv"):
confirmedcases = pd.read_csv(file)
if '�' in confirmedcases.loc[0]['risk']:
# bad encoding
with codecs.open(file, encoding="tis-620") as fp:
confirmedcases = pd.read_csv(fp)
first, last, ldate = confirmedcases["No."].iloc[0], confirmedcases["No."].iloc[-1], confirmedcases["announce_date"].iloc[-1]
print("Covid19daily:", f"rows={len(confirmedcases)}", f"{last-first}={last}-{first}", ldate, file)
cases = cases.combine_first(confirmedcases.set_index("No."))
else:
raise Exception(f"Unknown filetype for covid19daily {file}")
cases = cases.reset_index("No.")
cases['announce_date'] = pd.to_datetime(cases['announce_date'], dayfirst=True)
cases['Notified date'] = pd.to_datetime(cases['Notified date'], dayfirst=True, errors="coerce")
cases = cases.rename(columns=dict(announce_date="Date")).set_index("Date")
cases['age'] = pd.to_numeric(cases['age'], downcast="integer", errors="coerce")
#assert cases.index.max() <
return cases
def get_case_details_api():
rid = "67d43695-8626-45ad-9094-dabc374925ab"
chunk = 10000
url = f"https://data.go.th/api/3/action/datastore_search?resource_id={rid}&limit={chunk}&q=&offset="
records = []
cases = import_csv("covid-19", ["_id"], dir="json")
lastid = cases.last_valid_index() if cases.last_valid_index() else 0
data = None
while data is None or len(data) == chunk:
r = s.get(f"{url}{lastid}")
data = json.loads(r.content)['result']['records']
df = pd.DataFrame(data)
df['announce_date'] = pd.to_datetime(df['announce_date'], dayfirst=True)
df['Notified date'] = pd.to_datetime(df['Notified date'], dayfirst=True, errors="coerce")
df = df.rename(columns=dict(announce_date="Date"))
# df['age'] = pd.to_numeric(df['age'], downcast="integer", errors="coerce")
cases = cases.combine_first(df.set_index("_id"))
lastid += chunk - 1
export(cases, "covid-19", csv_only=True, dir="json")
cases = cases.set_index("Date")
print("Covid19daily: ", "covid-19", cases.last_valid_index())
# # they screwed up the date conversion. d and m switched sometimes
# # TODO: bit slow. is there way to do this in pandas?
# for record in records:
# record['announce_date'] = to_switching_date(record['announce_date'])
# record['Notified date'] = to_switching_date(record['Notified date'])
# cases = pd.DataFrame(records)
return cases
@functools.lru_cache(maxsize=100, typed=False)
def get_cases_by_demographics_api():
print("========Covid19Daily Demographics==========")
cases = get_case_details_csv().reset_index()
age_groups = cut_ages(cases, ages=[10, 20, 30, 40, 50, 60, 70], age_col="age", group_col="Age Group")
case_ages = pd.crosstab(age_groups['Date'], age_groups['Age Group'])
case_ages.columns = [f"Cases Age {a}" for a in case_ages.columns.tolist()]
#labels2 = ["Age 0-14", "Age 15-39", "Age 40-59", "Age 60-"]
#age_groups2 = pd.cut(cases['age'], bins=[0, 14, 39, 59, np.inf], right=True, labels=labels2)
age_groups2 = cut_ages(cases, ages=[15, 40, 60], age_col="age", group_col="Age Group")
case_ages2 = pd.crosstab(age_groups2['Date'], age_groups2['Age Group'])
case_ages2.columns = [f"Cases Age {a}" for a in case_ages2.columns.tolist()]
cases['risk'].value_counts()
risks = {}
risks['สถานบันเทิง'] = "Entertainment"
risks['อยู่ระหว่างการสอบสวน'] = "Investigating" # Under investication
risks['การค้นหาผู้ป่วยเชิงรุกและค้นหาผู้ติดเชื้อในชุมชน'] = "Proactive Search"
risks['State Quarantine'] = 'Imported'
risks['ไปสถานที่ชุมชน เช่น ตลาดนัด สถานที่ท่องเที่ยว'] = "Community"
risks['Cluster ผับ Thonglor'] = "Entertainment"
risks['ผู้ที่เดินทางมาจากต่างประเทศ และเข้า ASQ/ALQ'] = 'Imported'
risks['Cluster บางแค'] = "Community" # bangkhee
risks['Cluster ตลาดพรพัฒน์'] = "Community" # market
risks['Cluster ระยอง'] = "Entertainment" # Rayong
# work with forigners
risks['อาชีพเสี่ยง เช่น ทำงานในสถานที่แออัด หรือทำงานใกล้ชิดสัมผัสชาวต่างชาติ เป็นต้น'] = "Work"
risks['ศูนย์กักกัน ผู้ต้องกัก'] = "Prison" # detention
risks['คนไทยเดินทางกลับจากต่างประเทศ'] = "Imported"
risks['สนามมวย'] = "Entertainment" # Boxing
risks['ไปสถานที่แออัด เช่น งานแฟร์ คอนเสิร์ต'] = "Community" # fair/market
risks['คนต่างชาติเดินทางมาจากต่างประเทศ'] = "Imported"
risks['บุคลากรด้านการแพทย์และสาธารณสุข'] = "Work"
risks['ระบุไม่ได้'] = "Unknown"
risks['อื่นๆ'] = "Unknown"
risks['พิธีกรรมทางศาสนา'] = "Community" # Religous
risks['Cluster บ่อนพัทยา/ชลบุรี'] = "Entertainment" # gambling rayong
risks['ผู้ที่เดินทางมาจากต่างประเทศ และเข้า HQ/AHQ'] = "Imported"
risks['Cluster บ่อนไก่อ่างทอง'] = "Entertainment" # cockfighting
risks['Cluster จันทบุรี'] = "Entertainment" # Chanthaburi - gambing?
risks['Cluster โรงงาน Big Star'] = "Work" # Factory
r = {
27: 'Cluster ชลบุรี:Entertainment', # Chonburi - gambling
28: 'Cluster เครือคัสเซ่อร์พีคโฮลดิ้ง (CPG,CPH):Work',
29: 'ตรวจก่อนทำหัตถการ:Unknown', # 'Check before the procedure'
30: 'สัมผัสผู้เดินทางจากต่างประเทศ:Contact', # 'touch foreign travelers'
31: "Cluster Memory 90's กรุงเทพมหานคร:Entertainment",
32: 'สัมผัสผู้ป่วยยืนยัน:Contact',
33: 'ปอดอักเสบ (Pneumonia):Pneumonia',
34: 'Cluster New Jazz กรุงเทพมหานคร:Entertainment',
35: 'Cluster มหาสารคาม:Entertainment', # Cluster Mahasarakham
36: 'ผู้ที่เดินทางมาจากต่างประเทศ และเข้า OQ:Imported',
37: 'Cluster สมุทรปราการ (โรงงาน บริษัทเมทัล โปรดักส์):Work',
38: 'สัมผัสใกล้ชิดผู้ป่วยยันยันก่อนหน้า:Contact',
39: 'Cluster ตลาดบางพลี:Work',
40: 'Cluster บ่อนเทพารักษ์:Community', # Bangplee Market'
41: 'Cluster Icon siam:Community',
42: 'Cluster The Lounge Salaya:Entertainment',
43: 'Cluster ชลบุรี โรงเบียร์ 90:Entertainment',
44: 'Cluster โรงงาน standard can:Work',
45: 'Cluster ตราด :Community', # Trat?
46: 'Cluster สถานบันเทิงย่านทองหล่อ:Entertainment',
47: 'ไปยังพื้นที่ที่มีการระบาด:Community',
48: 'Cluster สมุทรสาคร:Work', # Samut Sakhon
49: 'สัมผัสใกล้ชิดกับผู้ป่วยยืนยันรายก่อนหน้านี้:Contact',
51: 'อยู่ระหว่างสอบสวน:Unknown',
20210510.1: 'Cluster คลองเตย:Community', # Cluster Klongtoey, 77
# Go to a community / crowded place, 17
20210510.2: 'ไปแหล่งชุมชน/สถานที่คนหนาแน่น:Community',
20210510.3: 'สัมผัสใกล้ชิดผู้ป่วยยืนยันก่อนหน้า:Contact',
# Cluster Chonburi Daikin Company, 3
20210510.4: 'Cluster ชลบุรี บริษัทไดกิ้น:Work',
20210510.5: 'ร้านอาหาร:Entertainment', # resturant
# touch the infected person confirm Under investigation, 5
20210510.6: 'สัมผัสผู้ติดเชื้อยืนยัน อยู่ระหว่างสอบสวน:Contact',
# touch the infected person confirm Under investigation, 5
20210510.7: 'สัมผัสผู้ป่วยยืนยัน อยู่ระหว่างสอบสวน:Contact',
# Travelers from high-risk areas Bangkok, 2
20210510.8: 'ผู้เดินทางมาจากพื้นที่เสี่ยง กรุงเทพมหานคร:Community',
# to / from Epidemic area, Bangkok Metropolis, 1
20210510.9: 'ไปยัง/มาจาก พื้นที่ระบาดกรุงเทพมหานครมหานคร:Community',
20210510.11: 'ระหว่างสอบสวน:Investigating',
# party pakchong https://www.bangkokpost.com/thailand/general/2103827/5-covid-clusters-in-nakhon-ratchasima
20210510.12: 'Cluster ปากช่อง:Entertainment',
20210512.1: 'Cluster คลองเตย:Community', # klongtoey cluster
20210512.2: 'อยู่ระหว่างสอบสวนโรค:Investigating',
20210512.3: 'อื่น ๆ:Unknown', # Other
# African gem merchants dining after ramandan
20210512.4: 'Cluster จันทบุรี (ชาวกินี ):Entertainment',
20210516.0: 'Cluster เรือนจำกลางคลองเปรม:Prison', # 894
20210516.1: 'Cluster ตลาดสี่มุมเมือง:Community', # 344 Four Corners Market
20210516.2: 'Cluster สมุทรปราการ GRP Hightech:Work', # 130
20210516.3: 'Cluster ตลาดนนทบุรี:Community', # Cluster Talat Nonthaburi, , 85
20210516.4: 'Cluster โรงงาน QPP ประจวบฯ:Work', # 69
# 41 Cluster Special Prison Thonburi,
20210516.5: 'Cluster เรือนจำพิเศษธนบุรี:Prison',
# 26 Cluster Chanthaburi (Guinea),
20210516.6: 'Cluster จันทบุรี (ชาวกินี):Entertainment',
# 20210516.7: 'Cluster บริษัทศรีสวัสดิ์,Work', #16
20210516.8: 'อื่น:Unknown', # 10
20210516.9: 'Cluster เรือนจำพิเศษมีนบุรี:Prison', # 5
20210516.11: 'Cluster จนท. สนามบินสุวรรณภูมิ:Work', # 4
20210516.12: 'สัมผัสผู้ป่วยที่ติดโควิด:Contact', # 4
20210531.0: 'Cluster เรือนจำพิเศษกรุงเทพ:Prison',
20210531.1: 'Cluster บริษัทศรีสวัสดิ์:Work',
20210531.2: "สัมผัสผู้ป่วยยืนยัน อยู่ระหว่างสอบสวน:Contact",
20210531.3: 'Cluster ตราด:Community',
20210531.4: 'ผู้ที่เดินทางมาจากต่างประเทศ และเข้า AOQ:Imported',
20210531.5: 'ผู้เดินทางมาจากพื้นที่เสี่ยง กรุงเทพมหานคร:Community',
20210531.6: 'Cluster กรุงเทพมหานคร. คลองเตย:Community',
20210622.0: 'อยู่ระหว่างการสอบสวน\n:Investigating',
20210622.1: 'Cluster ตราด:Community',
20210622.2: "สัมผัสผู้ป่วยยืนยัน \n อยู่ระหว่างสอบสวน:Contact",
20210622.3: "ผู้เดินทางมาจากพื้นที่เสี่ยง กรุงเทพมหานคร.:Community",
20210622.4: "อาศัย/เดินทางไปในพื้นที่ที่มีการระบาด:Community",
20210622.5: "อยุ่ระหว่างสอบสวน:Unknown",
20210622.6: "สัมผัสผู้ป่วยยืนยัน อยุ๋ระหว่างสอบสวน:Contact",
20210622.7: "สัมผัสผู้ติดเชื้อยืนยัน\nอยู่ระหว่างสอบสวน:Contact",
20210622.8: "ระหว่างการสอบสวนโรค:Investigating",
20210622.9: "ปอดอักเสบ Pneumonia:Pneumonia",
20210622.01: "Cluster ตลาดบางแค:Community",
20210622.11: "คนไทยเดินทางมาจากต่างประเทศ:Imported",
20210622.12: "คนไทยมาจากพื้นที่เสี่ยง:Community",
20210622.13: "cluster ชลบุรี\n(อยู่ระหว่างการสอบสวน):Investigating",
20210622.14: "Cluster โรงงาน Big Star:Work",
20210622.15: "Cluster สมุทรปราการ ตลาดเคหะบางพลี:Work",
20210622.16: "Cluster ระยอง วิริยะประกันภัย:Work",
20210622.17: "Cluster ตลาดบางแค/คลองขวาง:Work",
20210622.18: "เดินทางมาจากพื้นที่มีการระบาดของโรค:Community",
20210622.19: "Cluster งานมอเตอร์ โชว์:Community",
20210622.02: "ทัณฑสถาน/เรือนจำ:Prison",
20210622.21: "สถานที่ทำงาน:Work",
20210622.22: "รอประสาน:Unknown",
20210622.23: "ผู้ติดเชื้อในประเทศ:Contact",
20210622.24: "ค้นหาเชิงรุก:Proactive Search",
20210622.25: "Cluster ทัณฑสถานโรงพยาบาลราชทัณฑ์:Prison",
20210622.26: "2.สัมผัสผู้ติดเชื้อ:Contact",
20210622.27: "Cluster ระยอง:Community",
20210622.28: "ตรวจสุขภาพแรงงานต่างด้าว:Work",
20210622.29: "สัมผัสในสถานพยาบาล:Work", # contact in hospital
20210622.03: "ไปเที่ยวสถานบันเทิงในอุบลที่พบการระบาดของโรค Ubar:Entertainment",
20210622.31: "ไปสถานที่เสี่ยง เช่น ตลาด สถานที่ชุมชน:Community",
20210622.32: "Cluster ทัณฑสถานหญิงกลาง:Prison",
20210622.33: "ACF สนามกีฬาไทย-ญี่ปุ่น:Entertainment",
20210622.34: "ACF สีลม:Entertainment",
20210622.35: "ACF รองเมือง:Entertainment",
20210622.36: "ACF สนามกีฬาธูปะเตมีย์:Entertainment",
20210622.37: "Cluster ห้างแสงทอง (สายล่าง):Community",
20210622.38: "Cluster ทันฑสถานบำบัดพิเศษกลาง:Community",
20210714.01: "Sandbox:Imported",
20210731.01: "Samui plus:Imported",
20210731.02: "ACF เคหะหลักสี่:Work",
20210731.03: "เดินทางมาจากพื้นที่เสี่ยงที่มีการระบาดของโรค:Community",
20210806.01: "ท้ายบ้าน:Unknown",
20210806.02: "อื่นๆ:Unknown", # Other
}
for v in r.values():
key, cat = v.split(":")
risks[key] = cat
risks = pd.DataFrame(risks.items(), columns=[
"risk", "risk_group"]).set_index("risk")
cases_risks, unmatched = fuzzy_join(cases, risks, on="risk", return_unmatched=True)
# dump mappings to file so can be inspected
matched = cases_risks[["risk", "risk_group"]]
export(matched.value_counts().to_frame("count"), "risk_groups", csv_only=True)
export(unmatched, "risk_groups_unmatched", csv_only=True)
case_risks_daily = pd.crosstab(cases_risks['Date'], cases_risks["risk_group"])
case_risks_daily.columns = [f"Risk: {x}" for x in case_risks_daily.columns]
cases_risks['Province'] = cases_risks['province_of_onset']
risks_prov = join_provinces(cases_risks, 'Province')
risks_prov = risks_prov.value_counts(['Date', "Province", "risk_group"]).to_frame("Cases")
risks_prov = risks_prov.reset_index()
risks_prov = pd.crosstab(index=[risks_prov['Date'], risks_prov['Province']],
columns=risks_prov["risk_group"],
values=risks_prov['Cases'],
aggfunc="sum")
risks_prov.columns = [f"Cases Risk: {c}" for c in risks_prov.columns]
return case_risks_daily.combine_first(case_ages).combine_first(case_ages2), risks_prov
########################
# Dashboards
########################
def moph_dashboard():
def skip_valid(df, idx_value, allow_na={}):
if type(idx_value) == tuple:
date, prov = idx_value
idx_value = (str(date.date()) if date else None, prov)
else:
date = idx_value
idx_value = str(date.date()) if date else None
# Assume index of df is in the same order as params
if df.empty:
return False
def is_valid(column, date, idx_value):
limits = allow_na.get(column, None)
maxdate = today()
mins = []
if type(limits) in [tuple, list]:
mindate, maxdate, *mins= limits
elif limits is None:
mindate = d("1975-1-1")
else:
mindate = limits
if not(date is None or mindate <= date <= maxdate):
return True
try:
val = df.loc[idx_value][column]
except KeyError:
return False
if pd.isna(val):
return False
if mins:
return mins[0] <= val
else:
return True
# allow certain fields null if before set date
nulls = [c for c in df.columns if not is_valid(c, date, idx_value) ]
if not nulls:
return True
else:
print(date, "MOPH Dashboard", f"Retry Missing data at {idx_value} for {nulls}. Retry")
return False
def getDailyStats(df):
# remove crap from bad pivot
df = df.drop(columns=[c for c in df.columns if "Vac Given" in c and not any_in(c, "Cum",)])
# somehow we got some dodgy rows. should be no neg cases 2021
df = df.drop(df[df['Cases'] == 0.0].index)
# Fix spelling mistake
if 'Postitive Rate Dash' in df.columns:
df = df.drop(columns=['Postitive Rate Dash'])
allow_na = {
"ATK": d("2021-07-31"),
"Cases Area Prison": d("2021-05-12"),
"Positive Rate Dash": (d("2021-07-01"), today() - relativedelta(days=5)),
"Tests": today(), # its no longer there
'Hospitalized Field HICI': d("2021-08-08"),
'Hospitalized Field Hospitel': d("2021-08-08"),
'Hospitalized Field Other': d("2021-08-08"),
'Vac Given 1 Cum': (d("2021-08-01"), today() - relativedelta(days=4)),
'Vac Given 2 Cum': (d("2021-08-01"), today() - relativedelta(days=4)),
"Vac Given 3 Cum": (d("2021-08-01"), today() - relativedelta(days=4)),
'Hospitalized Field': (d('2021-04-20'), today(), 100),
'Hospitalized Respirator': (d("2021-03-25"), today(), 1), # patchy before this
'Hospitalized Severe': (d("2021-04-01"), today(), 10), # try and fix bad values
'Hospitalized Hospital': (d("2021-01-27"), today(), 1),
'Recovered': (d('2021-01-01'), today(), 1),
'Cases Walkin': (d('2021-01-01'), today(), 1),
}
url = "https://public.tableau.com/views/SATCOVIDDashboard/1-dash-tiles"
# new day starts with new info comes in
dates = reversed(pd.date_range("2021-01-24", today() - relativedelta(hours=7)).to_pydatetime())
for get_wb, date in workbook_iterate(url, param_date=dates):
date = next(iter(date))
if skip_valid(df, date, allow_na):
continue
if (wb := get_wb()) is None:
continue
row = workbook_flatten(
wb,
date,
D_New="Cases",
D_Walkin="Cases Walkin",
D_Proact="Cases Proactive",
D_NonThai="Cases Imported",
D_Prison="Cases Area Prison",
D_Hospital="Hospitalized Hospital",
D_Severe="Hospitalized Severe",
D_SevereTube="Hospitalized Respirator",
D_Medic="Hospitalized",
D_Recov="Recovered",
D_Death="Deaths",
D_ATK="ATK",
D_Lab2={
"AGG(% ติดเฉลี่ย)-value": "Positive Rate Dash",
"DAY(txn_date)-value": "Date",
},
D_Lab={
"AGG(% ติดเฉลี่ย)-alias": "Positive Rate Dash",
"ATTR(txn_date)-alias": "Date",
},
D_NewTL={
"SUM(case_new)-value": "Cases",
"DAY(txn_date)-value": "Date"
},
D_DeathTL={
"SUM(death_new)-value": "Deaths",
"DAY(txn_date)-value": "Date"
},
D_Vac_Stack={
"DAY(txn_date)-value": "Date",
"vaccine_plan_group-alias": {
"1": "1 Cum",
"2": "2 Cum",
"3": "3 Cum",
},
"SUM(vaccine_total_acm)-value": "Vac Given",
},
D_HospitalField="Hospitalized Field",
D_Hospitel="Hospitalized Field Hospitel",
D_HICI="Hospitalized Field HICI",
D_HFieldOth="Hospitalized Field Other",
D_RecovL={
"DAY(txn_date)-value": "Date",
"SUM(recovered_new)-value": "Recovered"
}
)
if row.empty:
break
assert date >= row.index.max() # might be something broken with setParam for date
row["Source Cases"] = "https://ddc.moph.go.th/covid19-dashboard/index.php?dashboard=main"
df = row.combine_first(df) # prefer any updated info that might come in. Only applies to backdated series though
print(date, "MOPH Dashboard", row.loc[row.last_valid_index():].to_string(index=False, header=False))
# We get negative valus for field hosoutal before april
assert df[df['Recovered'] == 0.0].empty
df.loc[:"2021-03-31", 'Hospitalized Field'] = np.nan
return df
def getTimelines(df):
# Get deaths by prov, date. and other stats - timeline
#
# ['< 10 ปี', '10-19 ปี', '20-29 ปี', '30-39 ปี', '40-49 ปี', '50-59 ปี', '60-69 ปี', '>= 70 ปี', 'ไม่ระบุ']
# D4_TREND
# cases = AGG(stat_count)-alias
# severe = AGG(ผู้ติดเชื้อรายใหม่เชิงรุก)-alias,
# deaths = AGG(ผู้เสียชีวิต)-alias (and AGG(ผู้เสียชีวิต (รวมทุกกลุ่มผู้ป่วย))-value all patient groups)
# cum cases = AGG(stat_accum)-alias
# date = DAY(date)-alias, DAY(date)-value
url = "https://ddc.moph.go.th/covid19-dashboard/index.php?dashboard=select-trend-line"
url = "https://dvis3.ddc.moph.go.th/t/sat-covid/views/SATCOVIDDashboard/4-dash-trend-w"
url = "https://dvis3.ddc.moph.go.th/t/sat-covid/views/SATCOVIDDashboard/4-dash-trend?:isGuestRedirectFromVizportal=y&:embed=y"
def range2eng(range):
return range.replace(" ปี", "").replace('ไม่ระบุ', "Unknown").replace(">= 70", "70+").replace("< 10", "0-9")
for get_wb, idx_value in workbook_iterate(url, D4_CHART="age_range"):
age_group = next(iter(idx_value))
age_group = range2eng(age_group)
skip = not pd.isna(df[f"Cases Age {age_group}"].get(str(today().date())))
if skip or (wb := get_wb()) is None:
continue
row = workbook_flatten(
wb,
None,
D4_TREND={
"DAY(date)-value": "Date",
"AGG(ผู้เสียชีวิต (รวมทุกกลุ่มผู้ป่วย))-value": "Deaths",
"AGG(stat_count)-alias": "Cases",
"AGG(ผู้ติดเชื้อรายใหม่เชิงรุก)-alias": "Hospitalized Severe",
},
)
if row.empty:
continue
row['Age'] = age_group
row = row.pivot(values=["Deaths", "Cases", "Hospitalized Severe"], columns="Age")
row.columns = [f"{n} Age {v}" for n, v in row.columns]
df = row.combine_first(df)
print(row.last_valid_index(), "MOPH Ages", range2eng(age_group),
row.loc[row.last_valid_index():].to_string(index=False, header=False))
df = df.loc[:, ~df.columns.duplicated()] # remove duplicate columns
return df
def get_trends_prov(df):
url = "https://dvis3.ddc.moph.go.th/t/sat-covid/views/SATCOVIDDashboard/4-dash-trend"