-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapp.py
75 lines (67 loc) · 2.26 KB
/
app.py
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
import os
from flask import Flask, json, abort, request
from flask_cors import CORS
from werkzeug.exceptions import HTTPException
from langchain.chat_models import ChatOpenAI, ChatAnthropic
from file_organizer.main import analyze_file
from file_organizer.file import move_file
import logging
app = Flask(__name__)
logging.getLogger('flask_cors').level = logging.DEBUG
CORS(app, origins=["http://localhost:3000"])
@app.errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps(
{
"code": e.code,
"name": e.name,
"description": e.description,
}
)
response.content_type = "application/json"
return response
@app.route("/")
def index():
return "<p>Hello, World!</p>"
@app.post("/listdir")
def listdir():
dir = os.path.expanduser(request.get_json().get("dir") or "~")
app.logger.info(f"Listing directory {dir}")
# check if the directory exists
if not os.path.isdir(dir):
abort(404, description=f"Directory {dir} does not exist.")
# TODO: add options to recursively search for files
# search for files in the directory
files = [
file
for file in os.listdir(dir)
if (not file.startswith(".")) and os.path.isfile(os.path.join(dir, file))
]
return files
@app.post("/analyze")
def analyze():
dir = request.get_json().get("dir")
file = request.get_json().get("file")
destinations = request.get_json().get("destinations")
result = analyze_file(dir, file, destinations)
if result is None:
return {"error": "No suggestion found."}
else:
return {"destination": result}
@app.post("/move_files")
def move_files():
dir = request.get_json().get("dir")
operations = request.get_json().get("operations")
if dir is None:
abort(400, description="No directory provided.")
if operations is None or len(operations) == 0:
abort(400, description="No files provided.")
print(dir)
print(operations)
for op in operations:
move_file(dir, op['file'], op['destination'])
return {"success": True}