-
Notifications
You must be signed in to change notification settings - Fork 314
/
server.py
165 lines (129 loc) · 4.39 KB
/
server.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import json
import os
import pathlib
import queue
from collections import defaultdict
from pathlib import Path
from typing import Optional
import time
import shutil # Add this import at the beginning of your file
import agentops
import colorama
import ollama
import threading
from asciitree import LeftAligned
from asciitree.drawing import BOX_LIGHT, BoxStyle
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from groq import Groq
from llama_index.core import SimpleDirectoryReader
from pydantic import BaseModel
from termcolor import colored
from watchdog.observers import Observer
from src.loader import get_dir_summaries
from src.tree_generator import create_file_tree
from src.watch_utils import Handler
from src.watch_utils import create_file_tree as create_watch_file_tree
from dotenv import load_dotenv
load_dotenv()
agentops.init(tags=["llama-fs"],
auto_start_session=False)
class Request(BaseModel):
path: Optional[str] = None
instruction: Optional[str] = None
incognito: Optional[bool] = False
class CommitRequest(BaseModel):
base_path: str
src_path: str # Relative to base_path
dst_path: str # Relative to base_path
app = FastAPI()
origins = [
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"], # Or restrict to ['POST', 'GET', etc.]
allow_headers=["*"],
)
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/batch")
async def batch(request: Request):
session = agentops.start_session(tags=["LlamaFS"])
path = request.path
if not os.path.exists(path):
raise HTTPException(
status_code=400, detail="Path does not exist in filesystem")
summaries = await get_dir_summaries(path)
# Get file tree
files = create_file_tree(summaries, session)
# Recursively create dictionary from file paths
tree = {}
for file in files:
parts = Path(file["dst_path"]).parts
current = tree
for part in parts:
current = current.setdefault(part, {})
tree = {path: tree}
tr = LeftAligned(draw=BoxStyle(gfx=BOX_LIGHT, horiz_len=1))
print(tr(tree))
# Prepend base path to dst_path
for file in files:
# file["dst_path"] = os.path.join(path, file["dst_path"])
file["summary"] = summaries[files.index(file)]["summary"]
agentops.end_session(
"Success", end_state_reason="Reorganized directory structure")
return files
@app.post("/watch")
async def watch(request: Request):
path = request.path
if not os.path.exists(path):
raise HTTPException(
status_code=400, detail="Path does not exist in filesystem")
response_queue = queue.Queue()
observer = Observer()
event_handler = Handler(path, create_watch_file_tree, response_queue)
await event_handler.set_summaries()
observer.schedule(event_handler, path, recursive=True)
observer.start()
# background_tasks.add_task(observer.start)
def stream():
while True:
response = response_queue.get()
yield json.dumps(response) + "\n"
# yield json.dumps({"status": "watching"}) + "\n"
# time.sleep(5)
return StreamingResponse(stream())
@app.post("/commit")
async def commit(request: CommitRequest):
print('*'*80)
print(request)
print(request.base_path)
print(request.src_path)
print(request.dst_path)
print('*'*80)
src = os.path.join(request.base_path, request.src_path)
dst = os.path.join(request.base_path, request.dst_path)
if not os.path.exists(src):
raise HTTPException(
status_code=400, detail="Source path does not exist in filesystem"
)
# Ensure the destination directory exists
dst_directory = os.path.dirname(dst)
os.makedirs(dst_directory, exist_ok=True)
try:
# If src is a file and dst is a directory, move the file into dst with the original filename.
if os.path.isfile(src) and os.path.isdir(dst):
shutil.move(src, os.path.join(dst, os.path.basename(src)))
else:
shutil.move(src, dst)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"An error occurred while moving the resource: {e}"
)
return {"message": "Commit successful"}