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("