ai_assistant1 / app.py
Percy3822's picture
Update app.py
c8d59dd verified
import gradio as gr
import json
import pandas as pd
def analyze_file(message, file):
if not file:
return "Please upload a file."
filepath = file.name
filename = filepath.split("/")[-1]
ext = filename.split(".")[-1].lower()
try:
# Known types
if ext == "jsonl":
with open(filepath, "r", encoding="utf-8") as f:
lines = f.readlines()
data = [json.loads(line) for line in lines]
return f"πŸ“„ JSONL file with *{len(data)}* entries."
elif ext == "json":
with open(filepath, "r", encoding="utf-8") as f:
content = json.load(f)
if isinstance(content, dict):
return f"πŸ“ JSON with *{len(content.keys())}* top-level keys."
elif isinstance(content, list):
return f"πŸ“ JSON with *{len(content)}* list items."
else:
return f"πŸŒ€ JSON with data type: {type(content)}"
elif ext == "csv":
df = pd.read_csv(filepath)
return f"πŸ“Š CSV with *{df.shape[0]}* rows and *{df.shape[1]}* columns."
elif ext == "py":
with open(filepath, "r", encoding="utf-8") as f:
code = f.read()
return f"πŸ’» Python file with *{len(code.splitlines())}* lines of code."
# Unknown types – attempt plain text preview
else:
try:
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
preview = content[:1000]
return f"πŸ“¦ {ext} file preview:\n\n\n{preview}\n"
except Exception as e:
return f"❌ Cannot preview this {ext} file. Likely binary. Error: {e}"
except Exception as e:
return f"❌ Error processing file: {e}"
# Gradio interface
iface = gr.Interface(
fn=analyze_file,
inputs=[
gr.Textbox(label="Message (not used yet)", placeholder="You can ask questions soon"),
gr.File(label="Upload any file")
],
outputs="text",
title="AI Assistant – Universal File Reader",
description="Upload any file (.json, .csv, .py, .txt, .docx, etc). I’ll preview what I can."
)
iface.launch()