File size: 2,516 Bytes
bf63a98 fa8d7bc 6f5962c fa8d7bc cef45b9 6f5962c bf63a98 6f5962c bf63a98 cef45b9 6f5962c cef45b9 6f5962c cef45b9 6f5962c cef45b9 6f5962c bf63a98 6f5962c fa8d7bc 6f5962c cef45b9 6f5962c cef45b9 fa8d7bc 6f5962c bf63a98 6f5962c cef45b9 6f5962c bf63a98 cef45b9 bf63a98 6f5962c bf63a98 6f5962c bf63a98 6f5962c bf63a98 6f5962c bf63a98 | 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | import os
import time
import shutil
import gradio as gr
from supabase import create_client, Client
# -------------------------------------------------------
# Supabase config
# -------------------------------------------------------
url = os.environ["SUPABASE_URL"]
key = os.environ["SUPABASE_SERVICE_KEY"]
supabase: Client = create_client(url, key)
BUCKET = "examfiles"
# -------------------------------------------------------
# Upload file to Supabase Storage
# -------------------------------------------------------
def upload_to_supabase(local_path, remote_path):
with open(local_path, "rb") as f:
supabase.storage.from_(BUCKET).upload(
remote_path,
f,
file_options={"upsert": "true"} # IMPORTANT FIX
)
# Construct public URL
public_url = (
f"{url}/storage/v1/object/public/{BUCKET}/{remote_path}"
)
return public_url
# -------------------------------------------------------
# Processing upload for each file
# -------------------------------------------------------
def process_upload(qp, ms, ans):
timestamp = str(int(time.time()))
temp_dir = "/tmp/upload"
os.makedirs(temp_dir, exist_ok=True)
def handle_file(gr_file):
if gr_file is None:
return None
# Gradio returns dict or filepath depending on environment
src = gr_file if isinstance(gr_file, str) else gr_file["name"]
original_name = os.path.basename(src)
local_path = os.path.join(temp_dir, original_name)
shutil.copy(src, local_path)
remote_path = f"{timestamp}/{original_name}"
return upload_to_supabase(local_path, remote_path)
qp_url = handle_file(qp)
ms_url = handle_file(ms)
ans_url = handle_file(ans)
output = "Uploaded:\n"
if qp_url: output += f"{qp_url}\n"
if ms_url: output += f"{ms_url}\n"
if ans_url: output += f"{ans_url}\n"
return output
# -------------------------------------------------------
# Gradio UI
# -------------------------------------------------------
with gr.Blocks() as demo:
gr.Markdown("### Upload PDFs (original filenames preserved)")
qp = gr.File(label="Upload QP PDF (e.g., akshaya_qp)")
ms = gr.File(label="Upload MS PDF (e.g., ms(2))")
ans = gr.File(label="Upload Answer PDF (e.g., ans)")
submit = gr.Button("Upload to Supabase")
output = gr.Textbox(lines=10, label="File URLs")
submit.click(process_upload, inputs=[qp, ms, ans], outputs=output)
demo.launch()
|