13ze commited on
Commit
9501a09
·
verified ·
1 Parent(s): 03b3462

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -78
app.py CHANGED
@@ -1,92 +1,67 @@
1
- import gradio as gr
2
  import os
3
  import shutil
4
- import re
5
- from PIL import Image
6
 
7
- # Diretório onde os arquivos serão armazenados
8
  STORAGE_DIR = "storage"
9
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
10
- MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
11
-
12
- # Nome do espaço HuggingFace
13
- SPACE_NAME = os.getenv('SPACE_NAME', '13ze/cloud-storage')
14
-
15
- # Função para inicializar o diretório de armazenamento
16
- def initialize_storage():
17
- if not os.path.exists(STORAGE_DIR):
18
- os.makedirs(STORAGE_DIR)
19
-
20
- # Função para verificar o tipo de arquivo
21
- def allowed_file(filename):
22
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
23
-
24
- # Função para normalizar o nome do arquivo
25
- def secure_filename(filename):
26
- filename = re.sub(r'[^a-zA-Z0-9_.-]', '_', filename)
27
- return filename
28
 
29
- # Função para verificar o conteúdo do arquivo
30
- def is_image(file_path):
31
- try:
32
- with Image.open(file_path) as img:
33
- img.verify()
34
- return True
35
- except (IOError, SyntaxError) as e:
36
- return False
37
 
38
- # Função para fazer upload do arquivo
39
  def upload_file(file):
40
- if file:
41
- # Normalizar nome do arquivo
42
- filename = secure_filename(file.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # Verificar extensão do arquivo
45
- if not allowed_file(filename):
46
- return "Tipo de arquivo não permitido."
47
-
48
- # Verificar tamanho do arquivo
49
- if os.path.getsize(file.name) > MAX_FILE_SIZE:
50
- return "Arquivo excede o tamanho máximo permitido de 10MB."
51
-
52
- # Salvar arquivo
53
- file_path = os.path.join(STORAGE_DIR, filename)
54
- shutil.copyfile(file.name, file_path)
55
-
56
- # Verificar conteúdo do arquivo
57
- if not is_image(file_path):
58
- os.remove(file_path)
59
- return "O conteúdo do arquivo não é uma imagem válida."
60
 
61
- base_url = f"https://{SPACE_NAME}.hf.space/files/{filename}"
62
- delete_url = f"https://{SPACE_NAME}.hf.space/delete?file={filename}"
63
- return f"Arquivo disponível em: {base_url}\nLink para deletar: {delete_url}"
64
- return "Falha no upload do arquivo."
 
65
 
66
- # Função para deletar o arquivo
67
- def delete_file(file_name):
68
- file_path = os.path.join(STORAGE_DIR, file_name)
69
- if os.path.isfile(file_path):
70
- os.remove(file_path)
71
- return f"Arquivo {file_name} deletado com sucesso."
72
- return f"Arquivo {file_name} não encontrado."
73
 
74
- # Inicializar o diretório de armazenamento
75
- initialize_storage()
 
76
 
77
- # Interface Gradio
78
- with gr.Blocks() as app:
79
- with gr.Row():
80
- gr.Markdown("## Gerenciamento de Arquivos na Nuvem")
81
- with gr.Row():
82
- upload = gr.File(label="Selecione um arquivo para upload")
83
- output = gr.Textbox(label="Status")
84
- with gr.Row():
85
- delete_file_name = gr.Textbox(label="Nome do arquivo para deletar")
86
- delete_button = gr.Button("Deletar arquivo")
87
- delete_output = gr.Textbox(label="Status de deleção")
88
 
89
- upload.upload(upload_file, inputs=[upload], outputs=[output])
90
- delete_button.click(delete_file, inputs=[delete_file_name], outputs=[delete_output])
91
 
92
- app.launch()
 
 
 
1
  import os
2
  import shutil
3
+ import gradio as gr
 
4
 
5
+ # Configuração do diretório de armazenamento
6
  STORAGE_DIR = "storage"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Criar o diretório de armazenamento se não existir
9
+ if not os.path.exists(STORAGE_DIR):
10
+ os.makedirs(STORAGE_DIR)
 
 
 
 
 
11
 
12
+ # Função para upload de arquivos
13
  def upload_file(file):
14
+ # Salvar o arquivo no diretório de armazenamento
15
+ file_path = os.path.join(STORAGE_DIR, file.name)
16
+ with open(file_path, "wb") as f:
17
+ f.write(file.read())
18
+ return "Arquivo enviado com sucesso!"
19
+
20
+ # Função para listar arquivos
21
+ def list_files():
22
+ file_tree = {}
23
+ for root, dirs, files in os.walk(STORAGE_DIR):
24
+ for name in files:
25
+ folder_path = os.path.relpath(root, STORAGE_DIR)
26
+ if folder_path not in file_tree:
27
+ file_tree[folder_path] = []
28
+ file_tree[folder_path].append(name)
29
+ return file_tree
30
+
31
+ # Função para deletar arquivos
32
+ def delete_file(file_path):
33
+ abs_path = os.path.join(STORAGE_DIR, file_path)
34
+ if os.path.isfile(abs_path):
35
+ os.remove(abs_path)
36
+ return f"Arquivo {file_path} deletado com sucesso!"
37
+ else:
38
+ return f"Arquivo {file_path} não encontrado!"
39
 
40
+ # Interface Gradio
41
+ def file_explorer_ui():
42
+ with gr.Blocks() as demo:
43
+ gr.Markdown("# Gerenciamento de Armazenamento em Nuvem")
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ with gr.Row():
46
+ with gr.Column():
47
+ upload = gr.File(label="Enviar Arquivo")
48
+ upload_btn = gr.Button("Enviar")
49
+ upload_output = gr.Textbox()
50
 
51
+ with gr.Column():
52
+ delete_file_input = gr.Textbox(label="Caminho do arquivo para deletar")
53
+ delete_file_btn = gr.Button("Deletar")
54
+ delete_output = gr.Textbox()
 
 
 
55
 
56
+ with gr.Row():
57
+ list_files_btn = gr.Button("Listar Arquivos")
58
+ file_list_output = gr.JSON()
59
 
60
+ upload_btn.click(upload_file, inputs=upload, outputs=upload_output)
61
+ delete_file_btn.click(delete_file, inputs=delete_file_input, outputs=delete_output)
62
+ list_files_btn.click(list_files, outputs=file_list_output)
 
 
 
 
 
 
 
 
63
 
64
+ return demo
 
65
 
66
+ # Rodar a aplicação
67
+ file_explorer_ui().launch()