Esempio n. 1
0
def allcountrydata(request):
    cov = covid.Covid()
    actives = cov.get_total_active_cases()
    confirmed = cov.get_total_confirmed_cases()
    recovered = cov.get_total_recovered()
    deaths = cov.get_total_deaths()
    countries = cov.list_countries()
    cname = []
    cactive = []
    cconfirmed = []
    crecovered = []
    cdeaths = []
    index = 0
    for c in countries:
        t = c['name']
        data = cov.get_status_by_country_name(t)
        cname.append(data['country'])
        cactive.append(data['active'])
        cdeaths.append(data['deaths'])
        crecovered.append(data['recovered'])
        cconfirmed.append(data['confirmed'])
        index += 1
        if (index == 50):
            break
    mylist = zip(cname, cactive, cdeaths, crecovered, cconfirmed)
    return render(
        request, 'updates.html', {
            'active': actives,
            'confirmed': confirmed,
            'recovered': recovered,
            'deaths': deaths,
            'mylist': mylist
        })
Esempio n. 2
0
def coronaDetails(request):
    cov = covid.Covid()
    name = request.POST['countryname']
    print(name)
    actives = cov.get_total_active_cases()
    confirmed = cov.get_total_confirmed_cases()
    recovered = cov.get_total_recovered()
    deaths = cov.get_total_deaths()

    virusdata = cov.get_status_by_country_name(name)
    active = virusdata['active']
    recover = virusdata['recovered']
    deaths = virusdata['deaths']
    label = ["Active", "Recovered", "Deaths"]
    data = [active, recover, deaths]
    return render(
        request, 'updates.html', {
            'label': label,
            'data': data,
            'name': name,
            'active': actives,
            'confirmed': confirmed,
            'recovered': recovered,
            'deaths': deaths
        })
Esempio n. 3
0
def verileri_getir(
):  #Entry'e girilien ülkenin verilerini getirmesini sağlayan fonksiyon.
    data = covid.Covid()
    ulke_adi = ulke_girisi.get()  #Ülke adının kullanıcıdan alınması
    status = data.get_status_by_country_name(
        ulke_adi
    )  #Covid kütüphanesinin "get_status_by_country_name" methodu ile ülkenin verilerinin alınması
    aktif_vaka = status['active']  #Aktif vaka sayısı
    aktif_vaka_girisi.insert(0,
                             aktif_vaka)  #Aktif Vaka'nın entry'e bastırıyoruz.
    vefat_vaka = status['deaths']  #Vefat eden kişi sayısı
    olum_sayi_girisi.insert(
        0, vefat_vaka)  #Vefat Eden Kişi sayısı'nın entry'e bastırıyoruz.
    toplam_vaka = status['confirmed']  #Toplam Vaka Sayısı
    toplam_vaka_girisi.insert(
        0, toplam_vaka)  #Toplam Vaka Sayısını entry'e bastırıyoruz.
    iyilesen_vaka = status['recovered']  #İyileşen Vaka Sayısı
    iyilesen_vaka_girisi.insert(
        0, iyilesen_vaka)  #İyileşen Vaka Sayısı'nı entry'e bastırıyoruz.

    veri = {
        key: status[key]
        for key in status.keys()
        & {"confirmed", "active", "deaths", "recovered"}
    }
    veri_keys = list(veri.keys())
    veri_values = list(veri.values())
    plt.title(ulke_adi)  #Grafiğin başlığını belirliyoruz.
    plt.bar(range(len(veri)), veri_values,
            tick_label=veri_keys)  #Grafiğin çubuklarını ayarlıyoruz.
    plt.plot(range(len(veri)))
    plt.show()  #Grafiği ekrana veriyoruz.
def run():
    # creating Instances
    cov = covid.Covid()

    # generating data
    country_name = input_value.get()
    virus_data = cov.get_status_by_country_name(country_name)

    # active People
    active = virus_data['active']

    # recover people
    recover = virus_data['recovered']

    # death people
    deaths = virus_data['deaths']

    # ploting the pie plot
    plt.pie([active, recover, deaths], labels=['Active', 'recovered', 'Deaths'], colors=['b', 'g', 'r'],
            explode=(0, 0, 0.2), startangle=180, autopct='%1.1f%%', shadow=True)

    # display the plot
    plt.title(country_name)
    plt.legend()
    plt.show()
Esempio n. 5
0
def check():
    data = covid.Covid()
    global a
    a = data.get_status_by_country_name(txt.get())
    out=("Country: "+str(a["country"])+"\n"+"Confirmed: "+str(a["confirmed"])+"\n"+\
         "Active: "+str(a["active"])+"\n"+"Deaths: "+str(a["deaths"])+"\n"+"Recovered: "+ str(a["recovered"]))

    Label(tk, height=20, width=20, text=out, font="Times").pack(pady=8)
Esempio n. 6
0
def show_countries():
    screen = Toplevel()
    screen.title("Countries List")
    screen.geometry("800x500+100+100")
    scrollbar = Scrollbar(screen, orient=VERTICAL)
    scrollbar.pack(side=RIGHT, fill=Y)
    text = Text(screen, yscrollcommand=scrollbar.set)
    text.pack(fill=BOTH, expand=YES)

    data = covid.Covid()
    country_name = e1.get()
    text.insert(END, data.list_countries())
Esempio n. 7
0
    def show_data(self):
        
            
        data = covid.Covid()
        countryname = self.button1.get()
        print(countryname)
        
        status = data.get_status_by_country_name(countryname)
        active = status['active']
        self.button2.insert(0,active)
        death = status['deaths']
        self.button3.insert(0, death)
        confirm = status['confirmed']
        self.button4.insert(0, confirm)
        recover = status['recovered']
        self.button5.insert(0, recover)
        print(status)
            # intialise data of lists.
        data = {'id': status['id'],
                    'Country': status['country'],
                    'Confirmed': status['confirmed'],
                    'Active': status['active'],
                    'Deaths': status['deaths'],
                    'Recovered': status['recovered'],
                    'Latitude': status['latitude'],
                    'Longitude': status['longitude'],
                    'Last_Updated': status['last_update']
                    }

            # Create DataFrame
        df = pd.DataFrame(data, index=[0])

            # Print the output.
        print(df)
        cadr = {

                key:status[key]
                for key in status.keys() & {"confirmed","active","deaths","recovered"}
            }
        n = list(cadr.keys())
        v = list(cadr.values())
        plt.title("Country")
        plt.bar(range(len(cadr)),v,tick_label=n,label=('active'))
        plt.xlabel('x-labels')
        plt.ylabel('data')

        plt.plot(range(len(cadr)))


        plt.show()
Esempio n. 8
0
def getoption(request):
    cov = covid.Covid()
    o = {}
    o.update(csrf(request))
    # print(cov.get_data())
    actives = cov.get_total_active_cases()
    confirmed = cov.get_total_confirmed_cases()
    recovered = cov.get_total_recovered()
    deaths = cov.get_total_deaths()
    return render(
        request, 'updates.html', {
            'o': o,
            'active': actives,
            'confirmed': confirmed,
            'recovered': recovered,
            'deaths': deaths
        })
Esempio n. 9
0
def getname(request):
    cov = covid.Covid()
    c = {}
    c.update(csrf(request))
    actives = cov.get_total_active_cases()
    confirmed = cov.get_total_confirmed_cases()
    recovered = cov.get_total_recovered()
    deaths = cov.get_total_deaths()
    countries = cov.list_countries()
    return render(
        request, 'updates.html', {
            'c': c,
            'active': actives,
            'confirmed': confirmed,
            'recovered': recovered,
            'deaths': deaths,
            'countries': countries
        })
Esempio n. 10
0
def show_data():
    try:
        data = covid.Covid()
        country_name = e1.get()
        #x=data.list_countries()
        status = data.get_status_by_country_name(country_name)
        active = status['active']
        e2.insert(0, active)
        death = status['deaths']
        e3.insert(0, death)
        confirmed = status['confirmed']
        e4.insert(0, confirmed)
        recovered = status['recovered']
        e5.insert(0, recovered)

        data = {
            'id': str(status['id']),
            'Country': str(status['country']),
            'Confirmed': str(status['confirmed']),
            'Active': str(status['active']),
            'Deaths': str(status['deaths']),
            'Recovered': str(status['recovered']),
            'Latitude': str(status['latitude']),
            'Longitude': str(status['longitude']),
            'Last_updated': str(status['last_update']),
        }
        df = pd.DataFrame(data, index=[0])
        print(df)
        cadr = {
            key: status[key]
            for key in {'confirmed', 'active', 'deaths', 'recovered'}
        }
        n = list(cadr.keys())
        v = list(cadr.values())
        plt.title("Country")
        plt.bar(range(len(cadr)), v, tick_label=n, label=('active'))
        plt.xlabel('x-labels')
        plt.ylabel('data')
        plt.plot(range(len(cadr)))
        y = plt.show()
    except Exception as es:
        messagebox.showerror("Error", f"Error due to {str(es)}")
Esempio n. 11
0
import covid
import matplotlib.pyplot as plt
#CREATING INSTANCE
cov = covid.Covid()
#GENERATING DATA
name = input('enter the country name ')
virusdata = cov.get_status_by_country_name(name)
#ACTIVE
active = virusdata['active']
#RECOVERED
recover = virusdata['recovered']
#DEATHS
deaths = virusdata['deaths']
#PLOTTING THE PIE PLOT
plt.pie([active,recover,deaths],labels=['active','recovered','deaths'],colors = ['b','g','r'],explode=(0,0,0.2),startangle = 180,autopct = '%1.1f%%',shadow=True)
#DISPLAYING THE PLOT
plt.title(name)
plt.legend()
plt.show()
Esempio n. 12
0
def listen():

    

    cov = covid.Covid()

    # GetInfo получает информацию о количестве заболевших,
    # Выздоровевших и умерших по данной стране,
    # Пользуясь данными университета хопкинса 
    # через covid api

    def GetInfo(country='/total'):
        list_countries = [i['name'] for i in list(cov.list_countries())]
        if country == '/total':
            message = """
Всего подтвержденных случаев: %s
Выздоровевших: %s
Число смертей: %s
    """ % (cov.get_total_confirmed_cases(), cov.get_total_recovered(), cov.get_total_deaths())
            return message
        elif country in  list_countries:
            print("country info")
            status = cov.get_status_by_country_name(country)
            message = """
Всего подтвержденных случаев: %s
Выздоровевших: %s
Число смертей: %s
            """ % (status['confirmed'], status['recovered'], status['deaths'])
        else:
            message = 'empty'
        print("GetInfo")
        return message

    hello_msg = """
Привет! Я могу сообщать тебе последние новости о коронавирусе.
Пока я умею немного, но мы над этим работаем.
Чтобы посмотреть общую статистику: /total
Чтобы посмотреть статистику по России: /Russia
Также ты можешь посмотреть информацию по любой стране,
просто написав ее название (пока что только на английском).
А еще мы можем подсказать, как скоротать время: /whattodo
Ссылка на официальные ресурсы: /resources
Новости можно посмотреть здесь: /news
Посмотреть симптомы коронавируса: /symptoms
Получить оригинальные стикеры: /stickers
Удачи!"""

    
    def message_cb(bot, event):
        
        msg = event.text 
        if msg == '/start':
            s = set()
            bot.send_text(chat_id=event.from_chat, text=hello_msg)
            if os.path.exists("IDs.pckl"):
                with open("IDs.pckl", "rb") as f:
                    s = pickle.load(f)
            s.add(event.from_chat)
            with open("IDs1.pckl", "wb") as f:
                pickle.dump(s, file=f)
            os.rename("IDs1.pckl", "IDs.pckl")

        elif msg == '/Russia':
            bot.send_text(chat_id=event.from_chat, text=GetInfo('Russia'))
            send_graph("Russia", event.from_chat)

        elif msg == '/news':
            inf = """
Последние новости о коронавирусе можно посмотреть на этих сайтах:
https://стопкоронавирус.рф
https://www.rbc.ru/society/04/05/2020/5e2fe9459a79479d102bada6#
https://www.bbc.com/russian/news-52528528
"""
            bot.send_text(chat_id=event.from_chat, text=inf)

        elif msg == '/resources':
            inf = """
Информациб по миру мы берем отсюда: https://coronavirus.jhu.edu/map.html
Последнюю статистику по России можно посмотреть здесь: https://стопкоронавирус.рф
"""
            bot.send_text(chat_id=event.from_chat, text=inf)

        elif '/q' in msg:

            print('quiz started')
        
            Data_1 = pd.read_excel('Questions 2.xlsx')

            Que = Data_1['Questions']
            ans1 = Data_1['Ans_1']
            ans2 = Data_1['Ans_2']
            ans3 = Data_1['Ans_3']
            for i in range(len(Data_1.iloc[1])):
                for j in range(len(Data_1['Ans_1'])):
                    Data_1.iloc[j,i] = str(Data_1.iloc[j,i])


            for i in range(len(Que)):
                k = i-1

                if '/qz%d'%k in event.text:
                    bot.send_text(chat_id=event.from_chat, text = '%s\n/qz%d1 %s \n/qz%d2 %s \n /qz%d3 %s'%(Que[i], i, ans1[i], i, ans2[i], i, ans3[i]))
                    id_user.append(event.from_chat)
                    que_user.append(Que[i])
                    ans_user.append(event.text)

                elif '/qz%d'%(len(Que) - 1) in event.text:
                    bot.send_text(chat_id=event.from_chat, text = 'Вы молодец!')
                    id_user.append(event.from_chat)
                    que_user.append(Que[i])
                    ans_user.append(event.text)
                    break


                elif event.text == '/quiz' and i == 0:
                    bot.send_text(chat_id=event.from_chat, text = '%s\n/qz%d1 %s \n/qz%d2 %s \n /qz%d3 %s'%(Que[0], 0, ans1[0], 0, ans2[0], 0, ans3[0]))
                    
                    id_user.append(event.from_chat)
                    que_user.append(Que[i])
                    ans_user.append(event.text)
            print(id_user)
            print(que_user)
            print(ans_user)


        elif msg == '/symptoms':

            with open('./simptomy_kv.png', "rb") as file:
                bot.send_file(chat_id=event.from_chat, file=file)


        elif msg == "/whattodo":
            inf = """
Во время самоизоляции очень важно найти занятие по душе,
и у нас есть несколько вариантов чтоб вам помочь:)
Вы можете посмотреть подборку семейных фильмов и сериалов: /familyfilms
И фильмов для тех, кто остался наедине с собой: /alonefilms
Ну а если помимо свободного времени у вас
есть научное любопытство, вы можете посмотреть 
подборку интересных опытов по физике: /experiments
Кстати, лайфхак: вы всегда можете поиграть в настолки,
даже если вы далеко от друзей, многие популярные игры 
имеют онлайн версии, например, монополия. Проверяли, затягивает:))
"""
            bot.send_text(chat_id=event.from_chat, text=inf)

        elif msg == '/stickers':
            print("Trying to send sticker")
            bot.send_text(chat_id=event.from_chat, text="cicq.org/s/b3DzmMRhqz")
            print("Sticker sent")
        
        elif msg == "/familyfilms":
            films = []
            print("familyflims")
            with open("./familyfilms/" + str(random.randrange(1, NFILMSFAMILY + 1)) + ".txt", 'r') as f:
                films = f.read().split('\n')
                print("File read")
            inf = "Вот список фильмов, которые мы рекомендуем посмотреть:\n" + '\n'.join(films)
            bot.send_text(chat_id=event.from_chat, text=inf)

        elif msg == "/alonefilms":
            films = []
            print("alonefilms")
            with open("./alonefilms/" + str(random.randrange(1, NFILMSALNOE + 1)) + ".txt", 'r') as f:
                films = f.read().split('\n')
                print("file read")
            inf = "Вот список фильмов, которые мы рекомендуем посмотреть:\n" + '\n'.join(films)
            bot.send_text(chat_id=event.from_chat, text=inf)

        elif msg == "/experiments":
            exp = ""
            print("experiments")
            with open("./experiments/" + str(random.randrange(1, NEXPERIMENTS + 1)) + '.txt', 'r') as f:
                exp = f.read()
                print("file read")
            bot.send_text(chat_id=event.from_chat, text=exp)
             
        else:
            inf = GetInfo(msg)
            print(inf)
            if inf == 'empty':
                bot.send_text(chat_id=event.from_chat, text="Простите, такого я не понимаю:(")
            else:
                bot.send_text(chat_id=event.from_chat, text=inf)
                
                send_graph(msg, event.from_chat)


    bot.dispatcher.add_handler(MessageHandler(callback=message_cb))
    bot.start_polling()
    bot.idle()
Esempio n. 13
0
import covid
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

# common variables
GITHUB_REFERENCE = "<h5><a href='https://github.com/ChiragSaini/' target='_blank'>Github</a></h5>"
LINKED_IN_REFERENCE = "<h5><a href='https://www.linkedin.com/in/chiragsaini97/' target='_blank'>LinkedIn</a></h5>"
TWITTER_REFERENCE = "<h5><a href='https://twitter.com/ChiragSaini97' target='_blank'>Twitter</a></h5>"
SUBHEAD_TITLE = "Covid19 Dashboard"
SUBHEAD_CREDITS = "Made by Chirag Saini"
c = covid.Covid()


# converts DataFrame to presentable card view in rows
def get_ui_for_data(data_input):
    column_properties = "margin:3%; float:right; width:15%; text-align: right"
    base_card_styling = "margin:1%; padding:1%; " \
                        "text-align:center;" \
                        "width:16%; " \
                        "box-shadow:0 4px 8px 0 rgba(0,0,0,0.2);"
    return f"<div class='row'>" \
           f"<h5 style='color:black; {column_properties}'>{data_input[0]}</h5>" \
           f"<h5 style='color:blue; {base_card_styling}'><h6>Total</h6>{data_input[1]}</h5> " \
           f"<h5 style='color:orange; {base_card_styling}'><h6>Deaths</h6>{data_input[2]}</h5> " \
           f"<h5 style='color:green; {base_card_styling}'><h6>Saved</h6>{data_input[3]}</h5> " \
           f"<h5 style='color:red; {base_card_styling}'><h6>Active</h6>{data_input[4]}</h5> " \
           f"</div>"


@st.cache
Esempio n. 14
0
import covid
import pyttsx3
import speech_recognition as sr
import json

covid = covid.Covid(source="john_hopkins")
engine = pyttsx3.init()
r = sr.Recognizer()

with sr.Microphone() as src:
    print("Say country name or if you want global cases, say global cases.")
    engine.say(
        "Say country name or if you want global cases, say global cases.")
    engine.runAndWait()
    userInp = r.recognize_google(r.listen(src))

if userInp.lower() == "global cases":
    print(
        f"{'{:,}'.format(covid.get_total_confirmed_cases())} confirmed cases")
    engine.say(
        f"{'{:,}'.format(covid.get_total_confirmed_cases())} confirmed cases")
    engine.runAndWait()

    print(f"{'{:,}'.format(covid.get_total_deaths())} deaths")
    engine.say(f"{'{:,}'.format(covid.get_total_deaths())} deaths")
    engine.runAndWait()

    print(f"{'{:,}'.format(covid.get_total_recovered())} recoveries")
    engine.say(f"{'{:,}'.format(covid.get_total_recovered())} recoveries")
    engine.runAndWait()
else:
Esempio n. 15
0
import covid 
import matplotlib.pyplot as plt
covid=covid.Covid()
name=input("enter the country name::")
virusdata=covid.get_status_by_country_name(name)
remove=['id','country','latitude','longitude','last_update']
for i in remove:
    virusdata.pop(i)
all=virusdata.pop('confirmed')
id=list(virusdata.keys())
value=[str(i) for i in virusdata.values()]
plt.pie(value,labels=id,colors=['r','y','g','b'],autopct='%2.1f%%')
plt.title("COUNTRY:"+name.upper() +"\n TOTAL CASES : "+str(all))
plt.legend()
plt.show()