Spaces:
Build error
Build error
File size: 5,176 Bytes
d6b7194 c74999f 08b07c5 a0d3937 c74999f 412aa57 c74999f cd4b2cd a0d3937 c74999f a0d3937 6befecd c74999f 6befecd a0d3937 eecb42d 9f9efe3 38f5e8d eecb42d 6befecd eecb42d 6befecd 11169fc a0d3937 6488045 b2be744 98d992e b2be744 98d992e b2be744 6befecd 11169fc 6befecd 11169fc b2be744 6befecd b2be744 b5c9e54 eecb42d b5c9e54 d6b7194 a0d3937 d6b7194 cd4b2cd a0d3937 d6b7194 6befecd a0d3937 cd4b2cd c48f196 cd4b2cd a0d3937 6befecd d6b7194 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | 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"<img src='data:image/{format};base64,{image_content}'>")
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("<center>")
add_image_b64(mdFile, charts["plot"], "png")
add_image_b64(mdFile, charts["hist"], "png")
add_image_b64(mdFile, charts["pie"], "png")
mdFile.new_paragraph("</center>")
# mdFile.create_md_file()
mdFile2 = MdUtils(file_name="Практическая работа по статистике_2")
mdFile2.new_paragraph("## Расчет дисперсии по отклонениям и их квадратам")
mdFile2.new_line()
mdFile2.new_paragraph("<br><br>\n\n<center>")
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("</center>")
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()
|