Spaces:
No application file
No application file
Ctrl+K
import gradio as gr from sympy import symbols, Eq, lcm, linsolve import re import pandas as pd # --- Hàm phân tích công thức --- def parse_formula(formula): pattern = r'([A-Z][a-z]?)(\d*)' elements = re.findall(pattern, formula) counts = {} for (elem, num) in elements: num = int(num) if num else 1 counts[elem] = counts.get(elem, 0) + num return counts # --- Hàm cân bằng --- def balance_equation(reactants, products): elements = set() for compound in reactants + products: elements.update(parse_formula(compound).keys()) elements = list(elements) coeffs = symbols(' '.join([f'a{i}' for i in range(len(reactants)+len(products))]), integer=True) equations = [] for element in elements: lhs = sum(parse_formula(reactants[i]).get(element, 0) * coeffs[i] for i in range(len(reactants))) rhs = sum(parse_formula(products[i]).get(element, 0) * coeffs[i+len(reactants)] for i in range(len(products))) equations.append(Eq(lhs, rhs)) equations.append(Eq(coeffs[0], 1)) sol = linsolve(equations, coeffs) if not sol: return None sol = list(sol)[0] denoms = [term.as_numer_denom()[1] for term in sol] multiple = lcm(denoms) coeff_ints = [int(term * multiple) for term in sol] return coeff_ints # --- Hàm chạy app --- def run_app(reactants_input, products_input): reactants = [r.strip() for r in reactants_input.split(',')] products = [p.strip() for p in products_input.split(',')] all_compounds = reactants + products # tạo bảng nguyên tố & số nguyên tử data = [] for c in all_compounds: parsed = parse_formula(c) for elem, count in parsed.items(): side = 'Tham gia' if c in reactants else 'Sản phẩm' data.append({'Chất': c, 'Nguyên tố': elem, 'Số lượng': count, 'Vế': side}) df = pd.DataFrame(data) # cân bằng phương trình coeffs = balance_equation(reactants, products) if coeffs: lhs = ' + '.join(f"{coeffs[i]} {reactants[i]}" for i in range(len(reactants))) rhs = ' + '.join(f"{coeffs[i+len(reactants)]} {products[i]}" for i in range(len(products))) equation = f"✅ Phương trình đã cân bằng:\n\n{lhs} → {rhs}" else: equation = "❌ Không cân bằng được phương trình." return df, equation # --- Tạo giao diện --- iface = gr.Interface( fn=run_app, inputs=[ gr.Textbox(label="Chất tham gia (cách nhau bằng dấu ,)", placeholder="Ví dụ: Fe, O2"), gr.Textbox(label="Chất sản phẩm (cách nhau bằng dấu ,)", placeholder="Ví dụ: Fe2O3") ], outputs=[ gr.Dataframe(label="Bảng nguyên tố & số nguyên tử", wrap=True), gr.Textbox(label="Kết quả phương trình", lines=4) ], title="⚗️ Ứng dụng cân bằng phương trình hóa học", description="Nhập chất tham gia và chất sản phẩm, cách nhau bằng dấu phẩy. App sẽ hiển thị bảng nguyên tố & số nguyên tử + phương trình đã cân bằng." ) iface.launch()
8e26015 verified