rahul755025/Mathematical_Calculation
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference import gradio as gr import sympy as sp import pandas as pd import kagglehub import time
=============================
LOAD DATASET (AI CHAT)
=============================
try: path = kagglehub.datasetdownload("ashishkumarak/chatgpt-reviews-daily-updated") df = pd.readcsv(path + "/chatgpt_reviews.csv") df = df[['review', 'rating']].dropna() except: df = pd.DataFrame({"review": ["Dataset not loaded"], "rating": [0]})
=============================
MATRIX PARSER
=============================
def parsematrix(matrixinputstr): rows = matrixinput_str.strip().split('\n')
if not rows or all(not row.strip() for row in rows): raise ValueError("Matrix input cannot be empty.")
matrixlist = [] numcols = None
for i, row in enumerate(rows): elements = [e.strip() for e in row.replace(',', ' ').split() if e.strip()]
if not elements: raise ValueError(f"Row {i+1} is empty.")
try: row_values = [sp.Rational(e) for e in elements] except: raise ValueError(f"Invalid number in row {i+1}")
if numcols is None: numcols = len(rowvalues) elif len(rowvalues) != num_cols: raise ValueError("All rows must have same number of columns.")
matrixlist.append(rowvalues)
A = sp.Matrix(matrix_list)
if not A.is_square: raise ValueError("Matrix must be square.")
return A
=============================
MATRIX OPERATIONS
=============================
def matrixoperations(matrixinput_str): steps = []
try: steps.append("โณ Parsing matrix...") A = parsematrix(matrixinput_str) time.sleep(0.3)
steps.append("๐ข Calculating determinant...") det = A.det() time.sleep(0.3)
steps.append("๐ Computing cofactor matrix...") cofactor = A.cofactor_matrix() time.sleep(0.3)
steps.append("๐ Computing adjugate matrix...") adjugate = A.adjugate() time.sleep(0.3)
steps.append("๐งฎ Computing inverse...") if det == 0: inversetext = "โ Inverse does not exist (Determinant = 0)" inverselatex = inversetext else: inverse = A.inv() inversetext = sp.pretty(inverse) inverse_latex = f"${sp.latex(inverse)}$" time.sleep(0.3)
steps.append("๐ Computing advanced properties...") rank = A.rank() transpose = A.T eigenvals = A.eigenvals()
return ( "\n".join(steps),
f"Determinant:\n{det}", f"Cofactor Matrix:\n{sp.pretty(cofactor)}", f"Adjugate Matrix:\n{sp.pretty(adjugate)}", f"Inverse Matrix:\n{inverse_text}",
f"### Determinant\n${sp.latex(det)}$", f"### Cofactor\n${sp.latex(cofactor)}$", f"### Adjugate\n${sp.latex(adjugate)}$", f"### Inverse\n{inverse_latex}",
f"### Rank\n${rank}$", f"### Transpose\n${sp.latex(transpose)}$", f"### Eigenvalues\n${sp.latex(eigenvals)}$" )
except Exception as e: return (f"Error: {e}", "", "", "", "", "", "", "", "", "", "")
=============================
AI CHAT (DATASET BASED)
=============================
def chatbotresponse(userinput): userinput = userinput.lower()
matches = df[df['review'].str.lower().str.contains(user_input)]
if not matches.empty: row = matches.iloc[0] return f"๐ Similar Review:\n\n{row['review']}\n\nโญ Rating: {row['rating']}" else: return "No similar review found. Try different keywords."
def chatinterface(message, history): response = chatbotresponse(message) history.append((message, response)) return "", history
=============================
UI DESIGN
=============================
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("## ๐งฎ Advanced Matrix + AI Chat System") gr.Markdown("Matrix Operations + AI Chat (Dataset-based)")
# -------- MATRIX INPUT -------- matrix_input = gr.Textbox( lines=6, label="Enter Matrix", placeholder="Example:\n1 2 3\n4 5 6\n7 8 9" )
run_btn = gr.Button("๐ Compute")
progress = gr.Textbox(label="Processing Steps")
with gr.Tabs():
# ===== TAB 1 ===== with gr.Tab("๐ Basic Outputs"): detout = gr.Textbox(label="Determinant") cofout = gr.Textbox(label="Cofactor Matrix") adjout = gr.Textbox(label="Adjugate Matrix") invout = gr.Textbox(label="Inverse Matrix")
# ===== TAB 2 ===== with gr.Tab("๐ Mathematical View"): detlatex = gr.Markdown() coflatex = gr.Markdown() adjlatex = gr.Markdown() invlatex = gr.Markdown()
# ===== TAB 3 ===== with gr.Tab("๐ Advanced Properties"): rankout = gr.Markdown() transposeout = gr.Markdown() eigen_out = gr.Markdown()
# ===== TAB 4 (AI CHAT) ===== with gr.Tab("๐ค AI Chat"): chatbot = gr.Chatbot() msg = gr.Textbox(label="Ask about reviews") clear = gr.Button("Clear Chat")
msg.submit(chat_interface, [msg, chatbot], [msg, chatbot]) clear.click(lambda: None, None, chatbot, queue=False)
runbtn.click( matrixoperations, inputs=matrixinput, outputs=[ progress, detout, cofout, adjout, invout, detlatex, coflatex, adjlatex, invlatex, rankout, transposeout, eigenout ] )
demo.launch()
