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()