Advertisement
Danila_lipatov

different_type_of_framework_for_python

Oct 28th, 2022 (edited)
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.58 KB | None | 0 0
  1. import streamlit as st
  2. import pandas as pd
  3. import numpy as np
  4. #https://towardsdatascience.com/5-python-gui-frameworks-to-create-desktop-web-and-even-mobile-apps-c25f1bcfb561
  5. # for streamlit(pandas / numpy for everything)
  6.  
  7.  
  8.  
  9. from dash import Dash, html, dcc
  10. import plotly.express as px
  11. import matplotlib.pyplot as plt
  12. #https://dash.plotly.com/datatable
  13. #https://towardsdatascience.com/5-python-gui-frameworks-to-create-desktop-web-and-even-mobile-apps-c25f1bcfb561
  14. #for dash
  15.  
  16.  
  17. from PyQt5 import QtCore, QtGui, QtWidgets
  18. from PySide6.QtWidgets import QTableView, QApplication
  19. from PySide6.QtCore import QAbstractTableModel, Qt, QModelIndex
  20. import sys
  21. #for PySide6
  22.  
  23.  
  24. import random
  25. import sys
  26. from faker import Faker
  27. #from bootstrap_table import db, User
  28. from flask_table import Table, Col
  29. from flask import Flask, request, render_template, session, redirect
  30.  
  31. #https://blog.miguelgrinberg.com/post/beautiful-interactive-tables-for-your-flask-templates
  32. #https://flask-table.readthedocs.io/en/stable/
  33. #for flask
  34.  
  35. #app = Dash(__name__) #running Dash framework without terminal
  36. app = Flask(__name__)
  37.  
  38.  
  39. def streamlit_ex(): #plot/add buttons/ table(df) / everything else +
  40. df = pd.read_csv(
  41. "https://raw.githubusercontent.com/ThuwarakeshM/PracticalML-KMeans-Election/master/voters_demo_sample.csv"
  42. ) #example of table
  43.  
  44. st.title("Interactive K-Means Clustering") #easy to add title
  45.  
  46. st.write("Here is the dataset used in this analysis:")
  47.  
  48. st.write(df) #display table(or everything)
  49.  
  50. arr = np.random.normal(1, 1, size=100) #np array for plot
  51. fig, ax = plt.subplots()
  52. ax.hist(arr, bins=20)
  53.  
  54. if st.button('Say hello'): #examp of buttons
  55. st.write('Why hello there')
  56. else:
  57. st.write('Goodbye')
  58.  
  59.  
  60.  
  61. st.pyplot(fig) #examp of plotting
  62.  
  63.  
  64. def Dash_ex(): #good for plot graph, not need to run using terminal +
  65. #also can be shown the df as table and other datas
  66.  
  67. # assume you have a "long-form" data frame
  68. # see https://plotly.com/python/px-arguments/ for more options
  69. df = pd.DataFrame({
  70. "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
  71. "Amount": [4, 1, 2, 2, 4, 5],
  72. "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
  73. })
  74.  
  75. fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
  76.  
  77. app.layout = html.Div(children=[
  78. html.H1(children='Hello Dash'),
  79.  
  80. html.Div(children='''
  81. Dash: A web application framework for your data.
  82. '''),
  83.  
  84. dcc.Graph(
  85. id='example-graph',
  86. figure=fig
  87. )
  88. ])
  89.  
  90.  
  91. class PandasModel(QAbstractTableModel):
  92. """A model to interface a Qt view with pandas dataframe """
  93.  
  94. def __init__(self, dataframe: pd.DataFrame, parent=None):
  95. QAbstractTableModel.__init__(self, parent)
  96. self._dataframe = dataframe
  97.  
  98. def rowCount(self, parent=QModelIndex()) -> int:
  99. """ Override method from QAbstractTableModel
  100.  
  101. Return row count of the pandas DataFrame
  102. """
  103. if parent == QModelIndex():
  104. return len(self._dataframe)
  105.  
  106. return 0
  107.  
  108. def columnCount(self, parent=QModelIndex()) -> int:
  109. """Override method from QAbstractTableModel
  110.  
  111. Return column count of the pandas DataFrame
  112. """
  113. if parent == QModelIndex():
  114. return len(self._dataframe.columns)
  115. return 0
  116.  
  117. def data(self, index: QModelIndex, role=Qt.ItemDataRole):
  118. """Override method from QAbstractTableModel
  119.  
  120. Return data cell from the pandas DataFrame
  121. """
  122. if not index.isValid():
  123. return None
  124.  
  125. if role == Qt.DisplayRole:
  126. return str(self._dataframe.iloc[index.row(), index.column()])
  127.  
  128. return None
  129.  
  130. def headerData(
  131. self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole
  132. ):
  133. """Override method from QAbstractTableModel
  134.  
  135. Return dataframe index as vertical header data and columns as horizontal header data.
  136. """
  137. if role == Qt.DisplayRole:
  138. if orientation == Qt.Horizontal:
  139. return str(self._dataframe.columns[section])
  140.  
  141. if orientation == Qt.Vertical:
  142. return str(self._dataframe.index[section])
  143.  
  144. return None
  145. def Pyside6_ex(): #for pandas df it is not good(need specific class)
  146. app = QApplication(sys.argv)
  147.  
  148. df = pd.read_csv(
  149. "https://raw.githubusercontent.com/ThuwarakeshM/PracticalML-KMeans-Election/master/voters_demo_sample.csv"
  150. )
  151.  
  152. view = QTableView()
  153. view.resize(800, 500)
  154. view.horizontalHeader().setStretchLastSection(True)
  155. view.setAlternatingRowColors(True)
  156. view.setSelectionBehavior(QTableView.SelectRows)
  157.  
  158. model = PandasModel(df)
  159. view.setModel(model)
  160. view.show()
  161. app.exec()
  162.  
  163.  
  164.  
  165. class ItemTable(Table):
  166. name = Col('Name')
  167. description = Col('Description')
  168.  
  169. # Get some objects
  170. class Item(object):
  171. def __init__(self, name, description):
  172. self.name = name
  173. self.description = description
  174.  
  175.  
  176.  
  177. @app.route('/', methods=("POST", "GET"))
  178.  
  179.  
  180. def flask_ex():
  181. items = [Item('Name1', 'Description1'),
  182. Item('Name2', 'Description2'),
  183. Item('Name3', 'Description3')]
  184.  
  185.  
  186. # Or, equivalently, some dicts
  187. items = [dict(name='Name1', description='Description1'),
  188. dict(name='Name2', description='Description2'),
  189. dict(name='Name3', description='Description3')]
  190.  
  191. # Or, more likely, load items from your database with something like
  192. #items = ItemModel.query.all()
  193.  
  194. # Populate the table
  195. table = ItemTable(items)
  196.  
  197. # Print the html
  198. return table.__html__()
  199. # or just {{ table }} from within a Jinja template
  200.  
  201.  
  202.  
  203.  
  204. if __name__ == '__main__':
  205. #Dash_ex() # so-so
  206. #app.run_server(debug=True)
  207. #streamlit_ex() #the best variant, but need upgrade to connect not through terminal
  208. #Pyside6_ex() #not good
  209. flask_ex()
  210. # or just {{ table }} from within a Jinja template
  211. app.run(host='0.0.0.0', port=5000) # Todo add html script for flask
  212.  
  213.  
  214.  
  215.  
  216. stop = 0
  217. #https://www.khanacademy.org/math/statistics-probability/analyzing-categorical-data for test knowledge
  218.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement