<jupyter_start><jupyter_text><jupyter_code>!pip install -Uqq fastai  # upgrade fastai on colab
from fastai.vision.all import *
from fastai.vision.widgets import *
import os, shutil

from PIL import Image
import requests
from io import BytesIO
from fastai.vision.widgets import *
from google.colab import drive
drive.mount('/content/drive')

%cd /content/drive/MyDrive/Uni/PDS/FWF

path = Path(r'/content/drive/MyDrive/Uni/PDS/FWF')
data_path = Path(r'/content/drive/MyDrive/Uni/PDS/FWF/data')
data_path.ls()
#load Masterdata
df_countries = pd.read_csv('/content/drive/MyDrive/Uni/PDS/FWF/countries.CSV')


dict_countrynames = df_countries.set_index('Code').to_dict()['Country']
list_countrycodes= df_countries['Code'].tolist()

def getPreText(confidence):
  #return the right preffix text based on the confidence
  pretext = ""
  if confidence >= 0.9:
    pretext = "This is the flag of "
  elif confidence >= 0.8:
    pretext = "I am pretty sure, that this is the flag of "
  elif confidence >= 0.7:
    pretext = "This should be the flag of "
  elif confidence >= 0.6:
    pretext = "This might be the flag of "
  elif confidence < 0.4:
    pretext = "I have to guess - eventually the flag of "
  return pretext

#######################################################################################

def getConfidencePercentage(confidence):
  #return right suffix
  c_percentage = round(confidence * 100,2)
  return c_percentage

#######################################################################################

def on_click_classify(change):
  #get image
  img = PILImage.create(btn_upload.data[-1])
  out_pl.clear_output()
  with out_pl:display(img.to_thumb(256,256))

  #make prediction and retrieve information
  country_id = learn_inf.predict(img)[0]
  country_tensor_index = learn_inf.predict(img)[1].item()
  confidence = learn_inf.predict(img)[2].numpy()[country_tensor_index]

  example_pl.clear_output()
  with example_pl:display(get_example_img(country_id).to_thumb(256,256),)

  #read full country name 
  country_name = dict_countrynames[country_id]

  #get fitting strings
  if confidence > 0:
    pretext= getPreText(confidence)
  else:
    pretext= "No prediction possible"
  

  #return the Name of the predicted country
  lbl_pred.value = pretext + country_name
  
  #update confidence bar
  bar_confidence.value = getConfidencePercentage(confidence)
  bar_confidence_score.value = "{} %".format(getConfidencePercentage(confidence))

  #change to the right accordion tab
  accordion.selected_index = 1

#######################################################################################
def on_click_show(change):
  #get image
  lbl_upload2.value = "You uploaded the following image: "
  img = PILImage.create(btn_upload.data[-1])
  out_pl.clear_output()
  with out_pl:display(img.to_thumb(256,256))
#######################################################################################

def search_images_ddg(key,max_n=1):
    """Search for 'key' with DuckDuckGo and return a unique urls of 'max_n' images
    (Adopted from https://github.com/deepanprabhu/duckduckgo-images-api and 
    https://github.com/fastai/fastbook/blob/master/utils.py)
    """
    url        = 'https://duckduckgo.com/'
    params     = {'q':key}
    res        = requests.post(url,data=params)
    searchObj  = re.search(r'vqd=([\d-]+)\&',res.text)
    if not searchObj: print('Token Parsing Failed !'); return
    requestUrl = url + 'i.js'
    headers    = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0',
                 'referer': 'https://duckduckgo.com/'}
    params     = (('l','us-en'),('o','json'),('q',key),('vqd',searchObj.group(1)),('f',',,,'),('p','1'),('v7exp','a'))
    urls       = []
    while True:
        try:
            res  = requests.get(requestUrl,headers=headers,params=params)
            data = json.loads(res.text)
            for obj in data['results']:
                urls.append(obj['image'])
                max_n = max_n - 1
                if max_n < 1: return L(set(urls))     # dedupe
            if 'next' not in data: return L(set(urls))
            requestUrl = url + data['next']
        except:
            pass

#######################################################################################

def get_example_img(country_id):
  country_name = dict_countrynames[country_id]
  results = search_images_ddg(f'flag {country_name} wikipedia')
  response = requests.get(results[0])
  img = Image.open(BytesIO(response.content))
  return img<jupyter_output><empty_output><jupyter_text><jupyter_code>#load learner
learn_inf = load_learner(path/'export.pkl')


#create Labels
lbl_upload1 = widgets.Label('Upload the flag you want to learn about')
lbl_upload2 = widgets.Label()
lbl_pred = widgets.Label()
lbl_empty = widgets.Label(" ")
lbl_result1 = VBox([widgets.Label('The image you uploaded: ')])
lbl_result2 = VBox([lbl_empty, widgets.Label('The flag should look like this: ')])


#create upload button
btn_upload = widgets.FileUpload()
btn_upload

#create Button for Classify
btn_run = widgets.Button(description='Classify')
btn_run.on_click(on_click_classify)

btn_show = widgets.Button(description='Show Upload')
btn_show.on_click(on_click_show)

#output upload
out_pl = widgets.Output()
out_pl.clear_output()



#output example image
example_pl = widgets.Output()
example_pl.clear_output()

#confidence bar
bar_confidence = widgets.IntProgress(
    value=0,
    min=0,
    max=100,
    step=1,
    description='Confidence: ',
    bar_style='success', # 'success', 'info', 'warning', 'danger' or ''
    orientation='horizontal'
)

bar_confidence_score =  widgets.Label()

bar_confidence_full = HBox([bar_confidence,bar_confidence_score])

#collect widgets
upload_widgets = VBox([lbl_upload1,HBox([btn_upload,btn_show,btn_run]),lbl_upload2,out_pl])
result_widgets = VBox([lbl_result1,out_pl,lbl_empty, lbl_pred,bar_confidence_full,lbl_result2, example_pl])

#create accordion
accordion = widgets.Accordion(children=[upload_widgets, result_widgets])
accordion.set_title(0, 'Upload')
accordion.set_title(1, 'Result')
accordion<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1844430419690754, 'fraction_numerical': 0.013411170716314294, 'mean_word_length': 4.0229793977813, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 14, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '289831', 'license': 'MIT', 'n_tokens_mistral': 2206, 'n_tokens_neox': 2035, 'n_words': 410, 'path': 'fws_app.ipynb', 'repo_name': 'pds2021/a5-nicoelbert', 'size': '6338'}