Spaces:
Sleeping
Sleeping
| 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() |