-
Notifications
You must be signed in to change notification settings - Fork 0
/
common_utils.py
1522 lines (1169 loc) · 41.6 KB
/
common_utils.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
def create_dir(dir,v = 1):
"""Creates a directory without throwing an error if directory already exists.
dir : The directory to be created.
v : Verbosity"""
if not os.path.exists(dir):
os.makedirs(dir)
if v:
print("Created Directory : ", dir)
return 1
else:
if v:
print("Directory already existed : ", dir)
return 0
!pip install kaggle
import os
def get_size(path = os.getcwd()):
print("Calculating Size: ",path)
total_size = 0
#if path is directory--
if os.path.isdir(path):
print("Path type : Directory/Folder")
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
#if path is a file---
elif os.path.isfile(path):
print("Path type : File")
total_size=os.path.getsize(path)
else:
print("Path Type : Special File (Socket, FIFO, Device File)" )
total_size=0
bytesize=total_size
print(bytesize, 'bytes')
print(bytesize/(1024), 'kilobytes')
print(bytesize/(1024*1024), 'megabytes')
print(bytesize/(1024*1024*1024), 'gegabytes')
return total_size
x=get_size("/content/examples")
import os
os.makedirs("/content/.kaggle/")
import json
token = {"username":"farhanhaikhan","key":"f2c0df223af325f0d811a0f18b0c02ca"}
with open('/content/.kaggle/kaggle.json', 'a+') as file:
json.dump(token, file)
import shutil
os.makedirs("/.kaggle/")
src="/content/.kaggle/kaggle.json"
des="/.kaggle/kaggle.json"
shutil.copy(src,des)
os.makedirs("/root/.kaggle/")
!cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json
!kaggle config set -n path -v /content
#https://towardsdatascience.com/setting-up-kaggle-in-google-colab-ebb281b61463
!kaggle competitions download -c digit-recognizer
!kaggle datasets download -d tawsifurrahman/covid19-radiography-database
!unzip -q covid19-radiography-database.zip -d /content/dataset
src="/content/Dataset.zip"
des="/content/DATA/"
get_ipython().system('unzip -q {} -d {}'.format(src,des))
import os
def create_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
print("Created Directory : ", dir)
return dir
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
def zipper(dir_path,zip_path):
zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
zipdir(dir_path, zipf)
zipf.close()
zipper('/content/MAIN/Train',"Zipped_Data.zip")
MAIN="/content/DATA"
SLAVE="/content/final-dataset/"
create_dir(MAIN)
#we want directories such as
#DATA-> Train , Val-> Covid, Normal ,Viral_Pneumonia
TRAIN_PATH = "/content/DATA/Train"
VAL_PATH = "/content/DATA/Val"
create_dir(TRAIN_PATH)
create_dir(VAL_PATH)
from sklearn.model_selection import train_test_split
import random
def distribute(SRC_PATH="/content/final-dataset",TRAIN_PATH="/content/DATA/Train",VAL_PATH="/content/DATA/Val",current_class="abc",
max_val=0,split_frac=0.8):
SRC_CLASS_PATH=os.path.join(SRC_PATH,current_class)
TRAIN_CLASS_PATH=os.path.join(TRAIN_PATH,current_class)
VAL_CLASS_PATH=os.path.join(VAL_PATH,current_class)
ITEMS=os.listdir(SRC_CLASS_PATH)
if (max_val!=0):
try:
ITEMS=random.choices(ITEMS,k=max_val)
except:
ITEMS = random.sample(ITEMS, max_val)
print("Length of ",current_class," trimmed to ",len(ITEMS))
print("Length of ",current_class," ",len(ITEMS))
random.seed(43) #make this expt reproducable
x=ITEMS
y=range(len(x))
xTrain, xTest, yTrain, yTest = train_test_split(x, y, test_size = 0.2, random_state = 43)
TRAIN_IMGS=xTrain
VAL_IMGS=xTest
print("Train : Val Lists ",len(TRAIN_IMGS)," : ",len(VAL_IMGS))
for each_img in TRAIN_IMGS:
src=os.path.join(SRC_CLASS_PATH,each_img)
des=os.path.join(TRAIN_CLASS_PATH,each_img)
shutil.copy(src,des)
for each_img in VAL_IMGS:
src=os.path.join(SRC_CLASS_PATH,each_img)
des=os.path.join(VAL_CLASS_PATH,each_img)
shutil.copy(src,des)
category_classes=["COVID-19","NORMAL","Viral Pneumonia"]
for each_class in category_classes:
create_dir(os.path.join(TRAIN_PATH,each_class))
create_dir(os.path.join(VAL_PATH,each_class))
distribute(current_class=each_class,max_val=375)
#75/375 is 20%
#trim all datasets to 300:75 ratio
#other augmentation techniques : CVD_DATASET
#to delete some data
#shutil.rmtree("/content/DATA")
#COVID ZIPPER
from google.colab import drive
drive.mount('/content/drive')
import shutil
import os
def create_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
print("Created Directory : ", dir)
return dir
src="/content/drive/My Drive/NEW_DATA/FINAL_AUG_DATA"
des="/content/MAIN"
shutil.copytree(src,des)
def zipper(dir_path,zip_path):
zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
zipdir(dir_path, zipf)
zipf.close()
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
def zipper(dir_path,zip_path):
zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
zipdir(dir_path, zipf)
zipf.close()
zipper('/content/MAIN/Train',"'Zipped_Dataset_Train.zip'")
zipf = zipfile.ZipFile('Zipped_Dataset_Train.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('/content/MAIN/Train', zipf)
zipf.close()
zipf = zipfile.ZipFile('Zipped_Dataset_Val.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('/content/MAIN/Val', zipf)
zipf.close()
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
RES="/content/drive/My Drive/NEW_DATA/"
zip_file=find('*Zipped_Dataset_Val.zip', '/content/')
print(zip_file[0])
src=zip_file[0]
des=os.path.join(RES,"Zipped_Dataset_Val.zip")
shutil.copy(src,des)
zip_file2=find('*Zipped_Dataset_Train.zip', '/content/')
print(zip_file2[0])
src=zip_file2[0]
des=os.path.join(RES,"Zipped_Dataset_Train.zip")
shutil.copy(src,des)
def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
dir="/content/drive/My Drive/NEW_DATA/FINAL_AUG_DATA"
bytesize=get_size(dir)
print(bytesize, 'bytes')
print(bytesize/(1024*1024), 'megabytes')
print(bytesize/(1024*1024*1024), 'gegabytes')
#download the dataset
#main_runner
#https://towardsdatascience.com/setting-up-kaggle-in-google-colab-ebb281b61463
#setting up kaggle in your colab
import os
os.makedirs("/content/.kaggle/")
import json
token = {"username":"farhanhaikhan","key":"f2c0df223af325f0d811a0f18b0c02ca"}
with open('/content/.kaggle/kaggle.json', 'a+') as file:
json.dump(token, file)
import shutil
os.makedirs("/.kaggle/")
src="/content/.kaggle/kaggle.json"
des="/.kaggle/kaggle.json"
shutil.copy(src,des)
os.makedirs("/root/.kaggle/")
!cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json
!kaggle config set -n path -v /content
#https://towardsdatascience.com/setting-up-kaggle-in-google-colab-ebb281b61463
!pip install kaggle
!kaggle datasets download -d tawsifurrahman/covid19-radiography-database
!unzip -q covid19-radiography-database.zip -d /content/dataset
from PIL import Image
directory="/content/dataset/COVID-19 Radiography Database/COVID-19/"
output="/content/dataset_compressed/COVID-19 Radiography Database/COVID-19/"
os.makedirs(output)
list_files=os.listdir(directory)
for each in list_files:
full_path=os.path.join(directory,each)
foo = Image.open(full_path)
x,y=foo.size
x=round(x*0.8)
y=round(y*0.8)
foo = foo.resize((x,y),Image.ANTIALIAS)
foo.save(os.path.join(output,each),optimize=True,quality=95)
"""
The normal chest X-ray (left panel) depicts clear lungs without any areas of abnormal opacification in the image. Bacterial pneumonia (middle) typically exhibits a focal lobar consolidation, in this case in the right upper lobe (white arrows), whereas viral pneumonia (right) manifests with a more diffuse ‘‘interstitial’’ pattern in both lungs.
"""
#auc roc curve
#intersection
#https://github.com/ieee8023/covid-chestxray-dataset
#https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia
#merge all notebooks in a directory!
import os, fnmatch
import io
import sys
import nbformat
from nbformat import v4 as nbf
#from IPython import nbformat #is deprecated
#finds files in a directory corresponding to a regex query
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
#code to print a list vertically :)
def print_list(lst):
for i in lst:
print(i)
#function to merge multiple notebooks into one file
def merge_notebooks(filenames,output="output_finale.ipynb",start=True,end=True):
merged = nbf.new_notebook()
count=0
for fname in filenames:
count+=1
with io.open(fname, 'r', encoding='utf-8') as f:
print("Reading Notebook",count," : ",fname)
nb = nbformat.read(f, as_version=4)
if start:
start_text = """## Start of notebook """+str(os.path.basename(fname))
start_cells = [nbformat.v4.new_markdown_cell(start_text)]
merged.cells.extend(start_cells)
merged.cells.extend(nb.cells)
print("Appending to Output Notebook",count," : ",fname)
if end:
end_text = """## End of notebook """+str(os.path.basename(fname))
end_cells = [nbformat.v4.new_markdown_cell(end_text)]
merged.cells.extend(end_cells)
if not hasattr(merged.metadata, 'name'):
merged.metadata.name = ''
merged.metadata.name += "_merged"
print("Merging to Output Notebook : ",output)
with io.open(output, 'w', encoding='utf-8') as f:
nbformat.write(merged, f)
#print("Merged to Output Notebook : ",os.path.join(os.getcwd(),output))
print("Merged to Output Notebook : ",output)
#print(nbformat.writes(merged))
#nbformat.writes(merged)
#sorted_list=sorted([notebook_files], key=str.lower)
#sort by basename
notebook_files=find('*.ipynb', '/content/')
notebook_files.sort(key=lambda x: os.path.basename(x))
print(len(notebook_files),"Notebook Files Found :")
print_list(notebook_files)
merge_notebooks(filenames=notebook_files,output="merged_output_notebook.ipynb")
#answer on stackoverflow 4 line indent code
filename="/content/db_code.txt"
with open(filename) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.rstrip() for x in content]
for e in content:
print(str(" ")+e)
#finds files in a directory corresponding to a regex query
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
zip_file=find('*covid19-radiography-database.zip', '/content/')
print(zip_file)
#scrape a table from a webpage
import requests
import pandas as pd
url = "http://www.inwea.org/wind-energy-in-india/wind-power-potential/"
html = requests.get(url).content
df_list = pd.read_html(html)
print(len(df_list))
df1,df2 = df_list
#Estimation of installable wind power potential at 80 m level,Estimation of installable wind power potential at 100 m level
df1.to_csv('small_data.csv')
df2.to_csv('big_data.csv')
df.to_csv('50-80.csv', index = False, header=True)
import os, fnmatch
import sqlite3
import pandas as pd
#creates a directory without throwing an error
def create_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
print("Created Directory : ", dir)
else:
print("Directory already existed : ", dir)
return dir
#finds files in a directory corresponding to a regex query
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
#convert sqlite databases(.db,.sqlite) to pandas dataframe(excel with each table as a different sheet or individual csv sheets)
def save_db(dbpath=None,excel_path=None,csv_path=None,extension="*.sqlite",csvs=True,excels=True):
if (excels==False and csvs==False):
print("Atleast one of the parameters need to be true: csvs or excels")
return -1
#little code to find files by extension
if dbpath==None:
files=find(extension,os.getcwd())
if len(files)>1:
print("Multiple files found! Selecting the first one found!")
print("To locate your file, set dbpath=<yourpath>")
dbpath = find(extension,os.getcwd())[0] if dbpath==None else dbpath
print("Reading database file from location :",dbpath)
#path handling
external_folder,base_name=os.path.split(os.path.abspath(dbpath))
file_name=os.path.splitext(base_name)[0] #firstname without .
exten=os.path.splitext(base_name)[-1] #.file_extension
internal_folder="Saved_Dataframes_"+file_name
main_path=os.path.join(external_folder,internal_folder)
create_dir(main_path)
excel_path=os.path.join(main_path,"Excel_Multiple_Sheets.xlsx") if excel_path==None else excel_path
csv_path=main_path if csv_path==None else csv_path
db = sqlite3.connect(dbpath)
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
print(len(tables),"Tables found :")
if excels==True:
#for writing to excel(xlsx) we will be needing this!
try:
import XlsxWriter
except ModuleNotFoundError:
!pip install XlsxWriter
if (excels==True and csvs==True):
writer = pd.ExcelWriter(excel_path, engine='xlsxwriter')
i=0
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
i+=1
print("Parsing Excel Sheet ",i," : ",table_name)
table.to_excel(writer, sheet_name=table_name, index=False)
print("Parsing CSV File ",i," : ",table_name)
table.to_csv(os.path.join(csv_path,table_name + '.csv'), index_label='index')
writer.save()
elif excels==True:
writer = pd.ExcelWriter(excel_path, engine='xlsxwriter')
i=0
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
i+=1
print("Parsing Excel Sheet ",i," : ",table_name)
table.to_excel(writer, sheet_name=table_name, index=False)
writer.save()
elif csvs==True:
i=0
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
i+=1
print("Parsing CSV File ",i," : ",table_name)
table.to_csv(os.path.join(csv_path,table_name + '.csv'), index_label='index')
cursor.close()
db.close()
return 0
save_db();
#mount the drive where we have the downloaded trained weights
from google.colab import drive
drive.mount('/content/drive',force_remount=True)
from google.colab import drive
drive.mount('/gdrive')
#common utility functions used everywhere
from IPython.display import FileLink
FileLink(r'/kaggle/input/lung-segmentation-unet/best_model.h5')
#creates a directory without throwing an error
def create_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
print("Created Directory : ", dir)
else:
print("Directory already existed : ", dir)
return dir
#counts the number of files in a directory
def count_no(dir):
lst=os.listdir(dir)
return len(lst)
def ListDiff(li1, li2):
return (list(set(li1) - set(li2)))
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
zipf = zipfile.ZipFile('Zipped_Dataset.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('/content/FINAL_AUG_DATA', zipf)
zipf.close()
get_ipython().system('unzip -q {} -d /content/kaggle_dir'.format(zip_file[0]))
print("Done Unzipping!")
#main_runner
#https://towardsdatascience.com/setting-up-kaggle-in-google-colab-ebb281b61463
#setting up kaggle in your colab
import os
os.makedirs("/content/.kaggle/")
import json
token = {"username":"farhanhaikhan","key":"f2c0df223af325f0d811a0f18b0c02ca"}
with open('/content/.kaggle/kaggle.json', 'a+') as file:
json.dump(token, file)
import shutil
os.makedirs("/.kaggle/")
src="/content/.kaggle/kaggle.json"
des="/.kaggle/kaggle.json"
shutil.copy(src,des)
os.makedirs("/root/.kaggle/")
!cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json
!kaggle config set -n path -v{/content}
#############################
#download google drive file to kaggle_dir
#turn on the internet first
import gdown
url = 'https://drive.google.com/uc?id=1UP_Gv9D0nqTHaK7haudwPqjshW_XYEFz'
output = 'dataset.zip'
gdown.download(url, output, quiet=False)
####################
def print_dict(new_dict):
#print ("Dictionary is : ")
#print("keys: values")
for i in new_dict:
print(i, " :", new_dict[i])
############################
!unzip -q /kaggle/working/dataset.zip -d /kaggle/working/data_aug
#############################
import shutil
shutil.rmtree("/kaggle/working/data_aug")
##############################
import shutil
src=""
des=""
shutil.copy(src,des)
###########################
import os
"""def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
dir="/content/drive/My Drive/NEW_DATA/FINAL_AUG_DATA"
bytesize=get_size(dir)
print(bytesize, 'bytes')
print(bytesize/(1024*1024), 'megabytes')
print(bytesize/(1024*1024*1024), 'gegabytes')"""
##########################################################################
#listing directories
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
##############################################################################
os.path.getsize("best_model_todate")/(1024*1024) #megabytes
########################################################################
"""if os.path.isdir(path):
print("\nIt is a directory")
elif os.path.isfile(path):
print("\nIt is a normal file")
else:
print("It is a special file (socket, FIFO, device file)" )"""
#https://www.w3resource.com/python-exercises/python-basic-exercise-85.php
import os
def get_size(path = os.getcwd()):
print("Calculating Size: ",path)
total_size = 0
#if path is directory--
if os.path.isdir(path):
print("Path type : Directory/Folder")
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
#if path is a file---
elif os.path.isfile(path):
print("Path type : File")
total_size=os.path.getsize(path)
else:
print("Path Type : Special File (Socket, FIFO, Device File)" )
total_size=0
bytesize=total_size
print(bytesize, 'bytes')
print(bytesize/(1024), 'kilobytes')
print(bytesize/(1024*1024), 'megabytes')
print(bytesize/(1024*1024*1024), 'gegabytes')
return total_size
x=get_size("/content/examples")
# -*- coding: utf-8 -*-
"""BeautifulSoup1.0.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1r3tWW0YZBHIGSwJYOkKXN3MolgT0LryS
#Getting the query from the search
"""
from bs4 import BeautifulSoup
import re
import requests
import random
req_name="snakes"
#request name that triggers everything in the following code
#reques name is the only expected input by the user
#function that returns google search results based upon a query
#here we want pinterest photo links only
def google_search_results(req_name):
#https://hackernoon.com/how-to-scrape-google-with-python-bo7d2tal
#https://github.com/getlinksc/scrape_google/blob/master/search.py
# desktop user-agent
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0"
# mobile user-agent
MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36"
query = req_name
#https://www.google.com/search?q=tigers+photos+pinterest
query = query.replace(' ', '+')
URL = f"https://google.com/search?q={query}"
#print(URL)
headers = {"user-agent": USER_AGENT}
resp = requests.get(URL, headers=headers)
if resp.status_code == 200:
soup = BeautifulSoup(resp.content, "html.parser")
results = []
for g in soup.find_all('div', class_='r'):
anchors = g.find_all('a')
if anchors:
link = anchors[0]['href']
title = g.find('h3').text
item = {
"title": title,
"link": link
}
results.append(item)
return results
#code to print a list vertically :)
def print_list(lst):
for i in lst:
print(i)
#extracts the urls from the search query
def extract_urls(search_res):
urls=[]
for site in search_res:
urls.append(site["link"])
return urls
#filters out the pinterest urls from the list of urls
#most probably not required as google searches keywords efficiently
def filter_pin_urls(urls):
filtered_links=[]
for url in urls:
if(re.search("pinterest",url)):
filtered_links.append(url)
return filtered_links
#get links from google for pinterest pics
def get_img_url(req_name):
search_res=google_search_results(req_name+" photos pinterest")
#print_list(search_res)
query_urls=extract_urls(search_res)
filtered_urls=filter_pin_urls(query_urls)
#print_list(filtered_urls)
#print(len(filtered_urls))
req_url=random.choice(filtered_urls)
#print(req_url)
return (req_url)
req_url=get_img_url(req_name)
print(req_url)
def get_all_hyperlinks(data):
links=[]
for link in data.findAll('a', attrs={'href': re.compile("^http://")}):
#links.append()
print (link.get('href'))
"""#IMAGE DOWNLOAD PART"""
import urllib.request
#handles getting all image webpage data as string
def get_data(url):
html_page=urllib.request.urlopen(url)
soup = BeautifulSoup(html_page)
data=str(soup)
return data
#find all image urls ending with jpg
def find_all_image_urls(s):
#pinterest concentration
#syntax
#{"url":"https://i.pinimg.com/474x/2a/16/b0/2a16b0c151a32a58d735bb46f589f6f6.jpg"
#lst = re.findall('"url":"http\S+jpg"', s)
#lst = re.findall('"url":"http[^,]+jpg"', s)
lst = re.findall('http[^,]+jpg', s)
#todo ending with other extensions png etc
return lst
#filter that searches for the word originals in the set of urls for pinterest specefically this is important
def filtered_urls(lst):
new_lst=[]
for i in lst:
if(re.search("originals",i)):
new_lst.append(i)
return new_lst
string_data=get_data(req_url)
#print(string_data)
image_urls=find_all_image_urls(string_data)
unique_urls=set(image_urls)
orig_urls=filtered_urls(unique_urls)
print_list(orig_urls)
#.*\.ccf$
#todo add other file formats
# \S matches any non-whitespace character
# ^ Match the start of the string
# $ Match the end of the string
"""The matching pattern could be:
^([^,]+),
That means
^ starts with
[^,] anything but a comma
+ repeated one or more times (use * (means zero or more) if the first field can be empty)
([^,]+) remember that part
, followed by a comma"""
#handles downloading all images on the list of images
import os
#name of the directory in which images will be saved
def dir_name(req_name):
directory="/content"+"/"+req_name+"/"
if not os.path.isdir(directory):
os.makedirs(directory)
return directory
#downloads the images from list of urls to given output directory
def download_images(urls,dir):
#wget -P /var/cache/foobar/ [...]
#wget --directory-prefix=/var/cache/foobar/ [...]\
for url in urls:
os.system('wget -P %s %s' %(dir,url))
dir=dir_name(req_name)
print(dir)
download_images(orig_urls,dir)
#downloads all the images from the given request name .
#Not recommended to use as will take up lots of internet and storage space
def download_all_imgs(query):
search_res=google_search_results(query+" photos pinterest")
#print_list(search_res)
query_urls=extract_urls(search_res)
filtered_links=filter_pin_urls(query_urls)
for each_url in filtered_links:
string_data=get_data(each_url)
#print(string_data)
image_urls=find_all_image_urls(string_data)
unique_urls=set(image_urls)
orig_urls=filtered_urls(unique_urls)
#print_list(orig_urls)
download_images(orig_urls,dir)
#download_all_imgs("linkin_park")
#download_all_imgs(req_name)
import os
# Get the list of all files and directories
# in the root directory
path = dir
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# print the list
print_list(dir_list)
print("No of downloaded images :",len(dir_list))
#code to copy downloaded content to your personal drive
#mount drive before running this piece of code
import shutil
src_dir=dir
des_dir="/content/drive/My Drive/Linkin_Park"
#shutil.copytree(src_dir,des_dir)
#todo perhaps for other websites than pinterest, use filter good quality pics
from PIL import Image
#im = Image.open("texture.jpg")
#print (im.size)
#The size is given as a 2-tuple (width, height)
#getting image resolutions in python
#delete/filterout low resolution images
"""#GET TEXT PART"""
#!git clone https://github.com/hunkim/word-rnn-tensorflow.git
#https://medium.com/deep-writing/how-to-write-with-artificial-intelligence-45747ed073c
#checkout deep writing later
def filter_wiki_urls(urls):
filtered_links=[]
for url in urls:
if(re.search("wikipedia",url)):
filtered_links.append(url)
return filtered_links
def filter_urls_with_keyword(urls,word):
#if word is found in the list of urls then only return url
filtered_links=[]
for url in urls:
if(re.search(word,url)):
filtered_links.append(url)
return filtered_links
#a text url generator using req_name as input
def get_txt_url(req_name):
search_res=google_search_results(req_name+" wikipedia")
#print_list(search_res)
query_urls=extract_urls(search_res)
filtered_urls=filter_wiki_urls(query_urls)
#print_list(filtered_urls)
#print(len(filtered_urls))
#req_url=random.choice(filtered_urls)
req_url=filtered_urls[0] #the first url
#print(req_url)
return (req_url)
# specify which URL/web page we are going to be scraping
# sampler text_url = "https://en.wikipedia.org/wiki/Tiger"
text_url=get_txt_url(req_name)
# open the url using urllib.request and put the HTML into the page variable
page = urllib.request.urlopen(text_url)
# parse the HTML from our URL into the BeautifulSoup parse tree format
soup = BeautifulSoup(page)
#print(soup)
#https://www.thepythoncode.com/article/access-wikipedia-python