File size: 2,323 Bytes
b39fe3e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | import os
import json
import csv
import nbformat
from docx import Document
from PyPDF2 import PdfReader
def read_file(filepath):
ext = filepath.lower().split('.')[-1]
try:
if ext == 'txt':
with open(filepath, 'r', encoding='utf-8') as f:
return f.read()
elif ext == 'json':
with open(filepath, 'r', encoding='utf-8') as f:
return json.dumps(json.load(f), indent=2)
elif ext == 'csv':
with open(filepath, 'r', encoding='utf-8') as f:
return f.read()
elif ext == 'pdf':
reader = PdfReader(filepath)
return "\n".join([page.extract_text() or '' for page in reader.pages])
elif ext == 'docx':
doc = Document(filepath)
return "\n".join([para.text for para in doc.paragraphs])
elif ext == 'ipynb':
with open(filepath, 'r', encoding='utf-8') as f:
nb = nbformat.read(f, as_version=4)
cells = [cell['source'] for cell in nb.cells if cell['cell_type'] == 'code']
return "\n\n".join(cells)
else:
return "Unsupported file type: " + ext
except Exception as e:
return f"โ Error reading file: {e}"
def list_files():
files = [f for f in os.listdir('.') if os.path.isfile(f)]
return "\n".join(files) if files else "No files found."
def mini_file_ai():
print("๐ค MiniAI FileBot: Type 'list' to view files, 'read filename.ext', or 'bye' to exit.")
while True:
user_input = input("You: ").strip()
if user_input.lower() == 'bye':
print("MiniAI: Goodbye! ๐")
break
elif user_input.lower() == 'list':
print("๐ Files in current folder:\n" + list_files())
elif user_input.lower().startswith('read '):
filename = user_input[5:].strip()
if os.path.exists(filename):
content = read_file(filename)
print(f"\n๐ Content of {filename}:\n")
print(content[:3000]) # Limit to 3000 chars
else:
print("โ File not found.")
else:
print("MiniAI: I can only 'list', 'read filename', or 'bye'.")
# Run the AI
if __name__ == "__main__":
mini_file_ai() |