First_agent_template / Gradio_UI.py
Tbaberca's picture
Update Gradio_UI.py
8396721 verified
raw
history blame
1.59 kB
def upload_file(
self,
file,
file_uploads_log,
allowed_file_types=[
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"text/plain",
],
):
"""
Handle file uploads, default allowed types are .pdf, .docx, and .txt
"""
import gradio as gr
if file is None:
return gr.Textbox("No file uploaded", visible=True), file_uploads_log
try:
mime_type, _ = mimetypes.guess_type(file.name)
except Exception as e:
return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
if mime_type not in allowed_file_types:
return gr.Textbox("File type disallowed", visible=True), file_uploads_log
# Sanitize file name
original_name = os.path.basename(file.name)
sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
# Map mime type to extension
type_to_ext = {}
for ext, t in mimetypes.types_map.items():
if t not in type_to_ext:
type_to_ext[t] = ext
name_without_ext = ".".join(sanitized_name.split(".")[:-1])
ext = type_to_ext.get(mime_type, "")
if not ext.startswith("."):
ext = "." + ext if ext else ""
sanitized_name = f"{name_without_ext}{ext}"
# Save file
file_path = os.path.join(self.file_upload_folder, sanitized_name)
with open(file_path, "wb") as f:
f.write(file.read())
# Update log or return success message
file_uploads_log.append(file_path)
return gr.Textbox(f"File uploaded: {sanitized_name}", visible=True), file_uploads_log