hedtorresca's picture
Update app.py
e0ff385 verified
raw
history blame
3.42 kB
import gradio as gr
import matplotlib.pyplot as plt
from matplotlib_venn import venn3
from io import BytesIO
from PIL import Image
def validate_inputs(A, B, C, AB, AC, BC, ABC, U):
errors = []
if A < AB + AC - ABC:
errors.append("A no puede ser menor que la suma de AB y AC menos ABC.")
if B < AB + BC - ABC:
errors.append("B no puede ser menor que la suma de AB y BC menos ABC.")
if C < AC + BC - ABC:
errors.append("C no puede ser menor que la suma de AC y BC menos ABC.")
if U < A + B + C - AB - AC - BC + ABC:
errors.append("El conjunto universal U es menor que la suma total de los conjuntos y sus intersecciones.")
return errors
def suggest_intersections(A, B, C, U):
max_AB = min(A, B, U - (A + B + C - A - B))
max_AC = min(A, C, U - (A + B + C - A - C))
max_BC = min(B, C, U - (A + B + C - B - C))
max_ABC = min(max_AB, max_AC, max_BC)
suggestions = {
"Máximo valor sugerido para A ∩ B": max_AB,
"Máximo valor sugerido para A ∩ C": max_AC,
"Máximo valor sugerido para B ∩ C": max_BC,
"Máximo valor sugerido para A ∩ B ∩ C": max_ABC,
}
return suggestions
def calculate_probabilities(A, B, C, AB, AC, BC, ABC, U):
total = U if U > 0 else (A + B + C - AB - AC - BC + ABC)
if total == 0:
return {
"P(A)": 0,
"P(B)": 0,
"P(C)": 0,
"P(A ∩ B)": 0,
"P(A ∩ C)": 0,
"P(B ∩ C)": 0,
"P(A ∩ B ∩ C)": 0,
}
P_A = A / total
P_B = B / total
P_C = C / total
P_AB = AB / total
P_AC = AC / total
P_BC = BC / total
P_ABC = ABC / total
formatted_probs = {
"P(A)": f"{P_A:.2%} ({A}/{total})",
"P(B)": f"{P_B:.2%} ({B}/{total})",
"P(C)": f"{P_C:.2%} ({C}/{total})",
"P(A ∩ B)": f"{P_AB:.2%} ({AB}/{total})",
"P(A ∩ C)": f"{P_AC:.2%} ({AC}/{total})",
"P(B ∩ C)": f"{P_BC:.2%} ({BC}/{total})",
"P(A ∩ B ∩ C)": f"{P_ABC:.2%} ({ABC}/{total})",
}
return formatted_probs
def plot_venn(A, B, C, AB, AC, BC, ABC):
plt.figure(figsize=(8, 8))
venn = venn3(subsets=(A, B, AB, C, AC, BC, ABC), set_labels=('A', 'B', 'C'))
plt.title("Venn Diagram")
buf = BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
img = Image.open(buf)
return img
def main(A, B, C, AB, AC, BC, ABC, U):
errors = validate_inputs(A, B, C, AB, AC, BC, ABC, U)
if errors:
suggestions = suggest_intersections(A, B, C, U)
return None, {"error": "\n".join(errors), "sugerencias": suggestions}
venn_diagram = plot_venn(A, B, C, AB, AC, BC, ABC)
probabilities = calculate_probabilities(A, B, C, AB, AC, BC, ABC, U)
return venn_diagram, probabilities
iface = gr.Interface(
fn=main,
inputs=[
gr.Number(label="Cantidad en A"),
gr.Number(label="Cantidad en B"),
gr.Number(label="Cantidad en C"),
gr.Number(label="Cantidad en A ∩ B"),
gr.Number(label="Cantidad en A ∩ C"),
gr.Number(label="Cantidad en B ∩ C"),
gr.Number(label="Cantidad en A ∩ B ∩ C"),
gr.Number(label="Conjunto Universal (U)")
],
outputs=[
gr.Image(type="pil", label="Diagrama de Venn"),
gr.JSON(label="Resultados")
],
live=True
)
iface.launch()