Switched UI from Tkinter to PyQT because that is much better

This commit is contained in:
Patrick Müller 2020-03-29 22:23:30 +02:00
parent c99e43a762
commit 6646e0bbe6
5 changed files with 356 additions and 31 deletions

View File

@ -26,16 +26,25 @@ from datetime import datetime, timedelta
class Analyser:
# Pandas Settings
pd.set_option('display.max_row', 50)
pd.set_option('display.max_column', 10)
df = pd.read_csv('statsfile.csv')
df['dateRep'] = pd.to_datetime(df['dateRep'])
def __init__(self):
# Pandas Settings
pd.set_option('display.max_row', 50)
pd.set_option('display.max_column', 10)
self.df = pd.read_csv('statsfile.csv')
self.df['dateRep'] = pd.to_datetime(self.df['dateRep'], format='%d/%m/%Y')
def getAvailableCountries(self):
return self.df['countriesAndTerritories'].unique()
def getAvailableDates(self):
retList = []
for date in self.df['dateRep'].unique():
# To only get the substring in the format YYYY-MM-DD
retList.append(str(date)[:10])
retList.sort()
return retList
def getCasesGraph(self, country, start_date='2019-12-31', end_date=datetime.now().strftime('%Y-%m-%d')) -> str:
"""
Get a graph with the absolute number of cases by day for the entered country
@ -45,10 +54,7 @@ class Analyser:
if country in self.getAvailableCountries():
fig = plt.figure()
ax = fig.add_subplot(111)
# casesPerDayDict = {}
# for date in self.df['dateRep']:
# casesPerDayDict[date] = self.getTotalCases(country, date)
plt.title(('Total cases graph for ' + country))
countryData = self.df[self.df['countriesAndTerritories'].isin([country])]
mask = (countryData['dateRep'] > start_date) & (countryData['dateRep'] <= end_date)
@ -56,8 +62,6 @@ class Analyser:
countryTimeData = countryTimeData.sort_values('dateRep')
countryTimeData['cases'] = countryTimeData['cases'].cumsum()
print(countryTimeData)
countryTimeData.plot(ax=ax, x='dateRep', y='cases')
plt.show(block=True)
@ -69,7 +73,7 @@ class Analyser:
print('Unknown country')
return '-1'
def getCaseIncreaseGraph(self, country):
def getCaseIncreaseGraph(self, country, start_date='2019-12-31', end_date=datetime.now().strftime('%Y-%m-%d')) -> str:
"""
Get a graph with the daily increase number of cases for the entered country
:param country: The country you wish to get the graph for
@ -78,13 +82,10 @@ class Analyser:
if country in self.getAvailableCountries():
fig = plt.figure()
ax = fig.add_subplot(111)
# casesPerDayDict = {}
# for date in self.df['dateRep']:
# casesPerDayDict[date] = self.getTotalCases(country, date)
plt.title(('Cases increase graph for ' + country))
countryData = self.df[self.df['countriesAndTerritories'].isin([country])]
mask = (countryData['dateRep'] <= datetime.now().strftime('%Y-%m-%d'))
mask = (countryData['dateRep'] > start_date) & (countryData['dateRep'] <= end_date)
countryTimeData = countryData.loc[mask]
countryTimeData.plot(ax=ax, x='dateRep', y='cases')

View File

@ -21,3 +21,4 @@ def updateStatsFile():
file.write(writeString)
# Done we are
file.close()
print('DEBUG: Updated Stats File')

View File

@ -6,12 +6,8 @@ Project: Analyse worldwide COVID-19 Data and provide graphs etc.
"""
import DataFetcher as fetcher
import Analyser as ana
import UserInterface as UI
if __name__ == '__main__':
analyser = ana.Analyser()
print(analyser.getAvailableCountries())
country = input('What country do you want the graph for: ')
analyser.getCasesGraph(country, start_date='2020-02-14')
print(analyser.getTotalCases(country))
analyser.getCaseIncreaseGraph(country)
fetcher.updateStatsFile()
UI.main()

132
UserInterface.py Normal file
View File

@ -0,0 +1,132 @@
# -*- coding: utf-8 -*-
"""
Project: Analyse worldwide COVID-19 Data and provide graphs etc.
@author Patrick Müller
"""
import sys
from datetime import datetime
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import Analyser as ana
class UserInterface(QWidget):
def __init__(self, app):
super().__init__()
# Get Analyser instance and required stuff from it
self.analyser = ana.Analyser()
countries = self.analyser.getAvailableCountries()
dates = self.analyser.getAvailableDates()
# PyQT Setup
self.setWindowTitle('COVID-19 Analytics')
screen_width, screen_height = app.desktop().screenGeometry().width(), app.desktop().screenGeometry().height()
# screen_width, screen_height = 3840, 2160
self.setGeometry(((screen_width / 2) - 750), ((screen_height / 2) - 375), 1500, 750)
self.setMinimumWidth(1300)
# Layout boxes
self.header_box = QHBoxLayout()
h2box1 = QHBoxLayout()
labelBox = QHBoxLayout()
picklistBox = QHBoxLayout()
buttonBox = QHBoxLayout()
caseNumberBox = QHBoxLayout()
self.graphBox = QHBoxLayout()
# Heading
heading = QLabel('<h1>COVID-19 Analytics</h1>')
self.header_box.addWidget(heading)
# Sub-Header
subheader1 = QLabel('<h2>Statistics about one country</h2>')
h2box1.addWidget(subheader1)
# Country Picker
countryPickerLabel = QLabel('<h3>Pick a country:</h3>')
labelBox.addWidget(countryPickerLabel)
self.countryPicker = QComboBox(parent=self)
self.countryPicker.addItems(countries)
self.countryPicker.setCurrentText('Germany')
picklistBox.addWidget(self.countryPicker, 1)
# Start Date Picker
startDatePickerLabel = QLabel('<h3>Pick a start date:</h3>')
labelBox.addWidget(startDatePickerLabel)
self.startDatePicker = QComboBox(parent=self)
self.startDatePicker.addItems(dates)
self.startDatePicker.setCurrentText('2019-12-31')
picklistBox.addWidget(self.startDatePicker, 1)
# End Date Picker
endDatePickerLabel = QLabel('<h3>Pick an end date:</h3>')
labelBox.addWidget(endDatePickerLabel)
self.endDatePicker = QComboBox(parent=self)
self.endDatePicker.addItems(dates)
self.endDatePicker.setCurrentText(datetime.now().strftime('%Y-%m-%d'))
picklistBox.addWidget(self.endDatePicker, 1)
# Calculate Button
self.calculateSingleCountryStats = QPushButton('Calculate')
buttonBox.addWidget(self.calculateSingleCountryStats)
self.calculateSingleCountryStats.setCheckable(True)
self.calculateSingleCountryStats.clicked.connect(self.btnstate)
# Total cases number
self.casesNumber = QLabel('<h4>Total Case Number: NaN</h4>')
caseNumberBox.addWidget(self.casesNumber)
# Generate Layout
layout = QVBoxLayout()
layout.addLayout(self.header_box)
layout.addSpacing(50)
layout.addLayout(h2box1)
layout.addSpacing(10)
layout.addLayout(labelBox)
layout.addLayout(picklistBox)
layout.addSpacing(10)
layout.addLayout(buttonBox)
layout.addSpacing(10)
layout.addLayout(caseNumberBox)
layout.addSpacing(10)
layout.addLayout(self.graphBox)
layout.addStretch(1)
self.setLayout(layout)
self.show()
def btnstate(self):
if self.calculateSingleCountryStats.isChecked():
# To reset the button
print('pressed')
self.calculateSingleCountryStats.toggle()
country = self.countryPicker.currentText()
startDate = self.startDatePicker.currentText()
endDate = self.endDatePicker.currentText()
casesGraphPath = self.analyser.getCasesGraph(country, startDate, endDate)
caseIncreaseGraphPath = self.analyser.getCaseIncreaseGraph(country, startDate, endDate)
self.casesNumber.setText(
('<h4>Total case number in ' + country + ' as of ' + endDate + ': ' + str(self.analyser.getTotalCases(country,
endDate))+'</h4>'))
self.casesGraphPlaceHolder = QLabel(self)
self.casesIncreasePlaceHolder = QLabel(self)
self.clearLayout(self.graphBox)
self.graphBox.addWidget(self.casesGraphPlaceHolder)
self.graphBox.addWidget(self.casesIncreasePlaceHolder)
self.casesGraphPlaceHolder.setPixmap(QPixmap(casesGraphPath))
self.casesIncreasePlaceHolder.setPixmap(QPixmap(caseIncreaseGraphPath))
def clearLayout(self, layout):
for i in reversed(range(layout.count())):
widgetToRemove = layout.itemAt(i).widget()
# remove it from the layout list
layout.removeWidget(widgetToRemove)
# remove it from the gui
widgetToRemove.setParent(None)
def main():
app = QApplication(sys.argv)
ex = UserInterface(app)
sys.exit(app.exec_())

File diff suppressed because it is too large Load Diff