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()