Spaces:
Runtime error
Runtime error
Commit ·
16db73f
1
Parent(s): 72a8a28
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import sqlite3
|
| 4 |
+
import uuid
|
| 5 |
+
|
| 6 |
+
UPLOADS_FOLDER = 'uploads'
|
| 7 |
+
|
| 8 |
+
if not os.path.exists(UPLOADS_FOLDER):
|
| 9 |
+
os.mkdir(UPLOADS_FOLDER)
|
| 10 |
+
|
| 11 |
+
conn = sqlite3.connect('documents.db')
|
| 12 |
+
c = conn.cursor()
|
| 13 |
+
c.execute('''CREATE TABLE IF NOT EXISTS documents
|
| 14 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 15 |
+
name TEXT NOT NULL,
|
| 16 |
+
user_id TEXT NOT NULL,
|
| 17 |
+
file_path TEXT NOT NULL)''')
|
| 18 |
+
conn.commit()
|
| 19 |
+
|
| 20 |
+
def save_file(upload_file, user_id):
|
| 21 |
+
user_folder = os.path.join(UPLOADS_FOLDER, user_id)
|
| 22 |
+
if not os.path.exists(user_folder):
|
| 23 |
+
os.mkdir(user_folder)
|
| 24 |
+
file_path = os.path.join(user_folder, upload_file.name)
|
| 25 |
+
with open(file_path, 'wb') as f:
|
| 26 |
+
f.write(upload_file.read())
|
| 27 |
+
return file_path
|
| 28 |
+
|
| 29 |
+
def save_to_database(file_path, user_id):
|
| 30 |
+
name = os.path.basename(file_path)
|
| 31 |
+
c.execute("INSERT INTO documents (name, user_id, file_path) VALUES (?, ?, ?)", (name, user_id, file_path))
|
| 32 |
+
conn.commit()
|
| 33 |
+
return "File saved successfully!"
|
| 34 |
+
|
| 35 |
+
def upload_and_save_file(upload_file, user_id):
|
| 36 |
+
file_path = save_file(upload_file, user_id)
|
| 37 |
+
save_to_database(file_path, user_id)
|
| 38 |
+
return "File uploaded and saved to database successfully!"
|
| 39 |
+
|
| 40 |
+
inputs = [gr.inputs.File(label="Upload a file"), gr.inputs.Hidden(label="User ID")]
|
| 41 |
+
outputs = gr.outputs.Textbox(label="Status")
|
| 42 |
+
|
| 43 |
+
gr.Interface(upload_and_save_file, inputs, outputs, title="Document Uploader", allow_screenshot=False).launch()
|