import gradio as gr import numpy as np from mdutils import MdUtils import matplotlib.pyplot as plt import matplotlib.ticker as ticker import base64 import io import json WIDTH = 10 HEIGHT = 4 def generate_charts(unique, counts, d, format="png", grayscale: bool = True) -> dict: plot = io.BytesIO() hist = io.BytesIO() pie = io.BytesIO() # Generate Plot fig = plt.figure(figsize=(WIDTH, HEIGHT)) ax = fig.add_subplot() ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) if grayscale: ax.plot(unique.astype("str"), counts, marker="o", color="black") else: ax.plot(unique.astype("str"), counts, marker="o", color="blue") plt.savefig(plot, bbox_inches="tight", orientation="landscape", format=format) # Generate Histogram fig, ax = plt.subplots(figsize=(WIDTH, HEIGHT)) if grayscale: ax.bar(x=[str(i) for i in unique], height=counts, width=0.5, color=["black"]) else: ax.bar(x=[str(i) for i in unique], height=counts, width=0.5, color=["blue"]) plt.savefig(hist, bbox_inches="tight", format=format) # Generate Pie Chart fig, ax = plt.subplots(figsize=(WIDTH, HEIGHT)) if grayscale: ax.pie( list(d.values()), labels=list(d.keys()), colors=["black", "grey"], wedgeprops={ "edgecolor": "white", "linewidth": 0.7, }, ) else: ax.pie( list(d.values()), labels=list(d.keys()), wedgeprops={ "edgecolor": "white", "linewidth": 0.7, }, ) plt.savefig(pie, format=format) plot.seek(0) hist.seek(0) pie.seek(0) plot_content = base64.b64encode(plot.read()).decode() hist_content = base64.b64encode(hist.read()).decode() pie_content = base64.b64encode(pie.read()).decode() return {"plot": plot_content, "hist": hist_content, "pie": pie_content} def add_image_b64(mdfile: MdUtils, image_content: str, format: str = "png"): mdfile.new_paragraph(f"") mdfile.new_line() def make_all(numbers, grayscale: bool): arr = np.array(numbers) unique, counts = np.unique(arr, return_counts=True) d = dict(zip(unique, counts)) # Counts of number of occurences mode = ", ".join( [ str(unique[i]) for i in np.argwhere(counts == np.max(counts)).flatten().tolist() ] ) mean = np.mean(arr) rng = np.max(arr) - np.min(arr) vrnc = np.var(arr) mdFile = MdUtils( file_name="Практическая работа по статистике", title="Практическая работа по статистике", ) mdFile.new_paragraph(",".join([str(x) for x in arr])) mdFile.new_paragraph(",".join([str(x) for x in sorted(arr)])) mdFile.new_paragraph(f"Размах: {rng}") mdFile.new_paragraph(f"Мода: {mode}") mdFile.new_paragraph(f"А ср.: {mean:.2f}") mdFile.new_paragraph(f"D = {vrnc:.2f}") list_of_strings = ["Элемент"] for x in d: list_of_strings.extend([f"{str(x)}"]) list_of_strings.append("Кол-во") for value in d.values(): list_of_strings.extend([f"{str(value)}"]) mdFile.new_line() mdFile.new_table( columns=len(d) + 1, rows=2, text=list_of_strings, text_align="center" ) mdFile.new_line() # Insert Images charts = generate_charts(unique, counts, d, "png", grayscale) mdFile.new_paragraph("
") add_image_b64(mdFile, charts["plot"], "png") add_image_b64(mdFile, charts["hist"], "png") add_image_b64(mdFile, charts["pie"], "png") mdFile.new_paragraph("
") # mdFile.create_md_file() mdFile2 = MdUtils(file_name="Практическая работа по статистике_2") mdFile2.new_paragraph("## Расчет дисперсии по отклонениям и их квадратам") mdFile2.new_line() mdFile2.new_paragraph("

\n\n
") list_of_strings = ["Элемент", "Отклонение", "Квадрат отклонения"] for x in sorted(arr): list_of_strings.extend([f"{x}", f"{(mean - x):.2f}", f"{(mean - x) ** 2:.2f}"]) mdFile2.new_line() mdFile2.new_table( columns=3, rows=len(arr) + 1, text=list_of_strings, ) mdFile2.new_line() mdFile2.new_paragraph("
") mdfile_enc = mdFile.get_md_text() mdfile_var_enc = mdFile2.get_md_text() return mdfile_enc, mdfile_var_enc def getints(numbers: str, grayscale: bool = True): ls = list(map(int, numbers.split(" "))) return make_all(ls, grayscale) with open("examples.json") as jf: examples = json.load(jf) iface = gr.Interface( fn=getints, inputs=[gr.Textbox(show_copy_button=True, label="Numbers"), "checkbox"], outputs=[ gr.Textbox(show_copy_button=True, label="Chart"), gr.Textbox(show_copy_button=True, label="Variance"), ], title="Tilted Calculator", examples=examples, ) iface.launch()