DOT_Calculator / app.py
duypro247's picture
Update app.py
e0bd7a1
raw
history blame
1.94 kB
import gradio as gr
import networkx as nx
import pydot
import pandas as pd
def calculate_parameters(dot_file):
# Read the dot file with specified encoding
with open(dot_file.name, 'r', encoding='utf-8') as f:
dot_data = f.read()
# Parse dot data using pydot
graphs = pydot.graph_from_dot_data(dot_data)
G = nx.nx_pydot.from_pydot(graphs[0])
# Initialize the list of lengths and the node-to-index map
all_lengths = [0] * len(G.nodes())
node_to_index = {node: i for i, node in enumerate(G.nodes())}
# Calculate absolute depth (Dabs) and depth of each node
for node in nx.topological_sort(G):
if G.in_degree(node) > 0: # This node has a predecessor
all_lengths[node_to_index[node]] = max(all_lengths[node_to_index[n]]+1 for n in G.predecessors(node))
Dabs = sum(all_lengths)
# Create node depth dictionary
node_depth = {node: all_lengths[node_to_index[node]] for node in G.nodes()}
# Calculate maximum depth (Dmax)
Dmax = max(all_lengths)
# Calculate average depth (Davg)
Davg = Dabs / len(all_lengths)
# Calculate absolute width (Wabs)
Wabs = len(G.nodes())
# Calculate maximum width (Wmax)
level_count = [all_lengths.count(i) for i in set(all_lengths)]
Wmax = max(level_count)
# Calculate average width (Wavg)
Wavg = Wabs / len(set(all_lengths))
# Create a DataFrame for better visualization
df = pd.DataFrame.from_dict(node_depth, orient='index', columns=['Depth'])
df_str = df.to_string()
result_str = (f"Node Depths:\n{df_str}\n\nFinal Calculations:\n"
f"Dabs = {Dabs}, Dmax = {Dmax}, Davg = {Davg:.3f}\n"
f"Wabs = {Wabs}, Wmax = {Wmax}, Wavg = {Wavg:.3f}")
return result_str
iface = gr.Interface(fn=calculate_parameters,
inputs=gr.inputs.File(label="Upload .dot file"),
outputs="text")
iface.launch()