I’m having some trouble with simply saving .txt results as downloadable using Gradio’s File() method.
Referencing the docs: Gradio Docs
Additionally, here is a related example on a space: app.py · radames/dpt-depth-estimation-3d-obj at main
However, this is using Gradio version 4.26.0 and saving a different file type; I am using 5.42.0;
When I attempt to download my results, my browser shows “File wasn’t available on site” in the downloads section.
Here is the code:
import gradio as gr
import json
import os
from datetime import datetime
from pathlib import Path
gr.set_static_paths(paths=[Path.cwd().absolute()])
print("Current Working Directory: ", os.getcwd())
cwd = os.getcwd()
def process_question(question):
try:
answer = {"doc1": "document 1 contents", "doc2": "document 2 contents"}
# Create file in current directory with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"my_answer_{timestamp}.txt"# Get the current working directory
filepath = os.path.join(cwd, filename)
f = open(filename, "w", encoding="utf-8")
try:
answer = json.dumps(answer, indent=2, ensure_ascii=False)
f.write(answer)
finally:
f.close()
return [answer, filepath]
except Exception as e:
return f"Error processing question: {str(e)}", None
# Create Gradio interface
iface = gr.Interface(
fn=process_question,
inputs=gr.Textbox(label="Ask a question about documents", placeholder="Extract the text from this document."),
outputs=[
gr.Textbox(label="Answer"),
gr.File(label="Download Answer as txt", file_count="single", file_types=[".txt"], type="filepath" )
],
title="Document Reader",
description="Ask questions about documents using AI vision to read scanned PDFs"
)
iface.launch(ssr_mode=False, allowed_paths=[cwd])
Take note: I also outputted the filename from the process_question() with the same result
When I attempt to right click on the download link and open as a new tab, I’m met with a 404 error and the address URL is https://huggingface.co/proxy/myhfspace.hf.space/gradio_api/file=answer.txt (note: I’ve changes the name, but it’s similar)
If anyone has any idea how to get this to work, it would be appreciated.