lightning-pose-app 1.8.1a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.3
2
+ Name: lightning-pose-app
3
+ Version: 1.8.1a1
4
+ Summary:
5
+ Requires-Python: >=3.10
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.10
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Requires-Dist: fastapi
12
+ Requires-Dist: tomli
13
+ Requires-Dist: tomli_w
14
+ Requires-Dist: uvicorn[standard]
15
+ Requires-Dist: wcmatch
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["poetry-core>=1.0.0"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [project]
6
+ name = "lightning-pose-app"
7
+ version = "1.8.1a1"
8
+ requires-python = ">=3.10"
9
+ dependencies = [
10
+ "fastapi",
11
+ "uvicorn[standard]",
12
+ "wcmatch",
13
+ "tomli",
14
+ "tomli_w",
15
+ ]
16
+
17
+ [tool.poetry]
18
+ packages = [
19
+ { include = "litpose_app", from = "src" }
20
+ ]
21
+ # We need this to override the .gitignore.
22
+ include = ["**/ngdist/**/*"]
23
+
File without changes
@@ -0,0 +1,290 @@
1
+ from pathlib import Path
2
+ from textwrap import dedent
3
+
4
+ import tomli
5
+ import tomli_w
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.responses import FileResponse
8
+ import sys
9
+ import uvicorn
10
+ from pydantic import BaseModel, ValidationError
11
+ from starlette import status
12
+ from starlette.requests import Request
13
+ from starlette.responses import Response
14
+ from starlette.staticfiles import StaticFiles
15
+
16
+ from .run_ffprobe import run_ffprobe
17
+ from .super_rglob import super_rglob
18
+
19
+ # use this example to pull useful features from:
20
+ # https://github.com/fastapi/full-stack-fastapi-template
21
+ app = FastAPI()
22
+
23
+
24
+ @app.exception_handler(Exception)
25
+ async def debug_exception_handler(request: Request, exc: Exception):
26
+ """Puts error stack trace in response when any server exception occurs.
27
+
28
+ By default, FastAPI returns 500 "internal server error" on any Exception
29
+ that is not a subclass of HttpException. This is usually recommended in production apps.
30
+
31
+ In our app, it's more convenient to expose exception details to the user. The
32
+ security risk is minimal."""
33
+ import traceback
34
+
35
+ return Response(
36
+ status_code=500,
37
+ content="".join(
38
+ traceback.format_exception(type(exc), value=exc, tb=exc.__traceback__)
39
+ ),
40
+ headers={"Content-Type": "text/plain"},
41
+ )
42
+
43
+
44
+ PROJECT_INFO_TOML_PATH = Path("~/.lightning_pose/project.toml").expanduser()
45
+
46
+
47
+ class ProjectInfo(BaseModel):
48
+ """Class to hold information about the project"""
49
+
50
+ data_dir: Path = Path("")
51
+ model_dir: Path = Path("")
52
+ views: list[str] = []
53
+
54
+
55
+ """
56
+ All our methods are RPC style (http url corresponds to method name).
57
+ They should be POST requests, /rpc/<method_name>.
58
+ Request body is some object (pydantic model).
59
+ Response body is some object pydantic model.
60
+
61
+ The client expects all RPC methods to succeed. If any RPC doesn't
62
+ return the expected response object, it will be shown as an
63
+ error in a dialog to the user. So if the client is supposed to
64
+ handle the error in any way, for example, special form validation UX
65
+ like underlining the invalid field,
66
+ then the information about the error should be included in a valid
67
+ response object rather than raised as a python error.
68
+ """
69
+
70
+
71
+ class GetProjectInfoResponse(BaseModel):
72
+ projectInfo: ProjectInfo | None # None if project info not yet initialized
73
+
74
+
75
+ @app.post("/app/v0/rpc/getProjectInfo")
76
+ def get_project_info() -> GetProjectInfoResponse:
77
+ try:
78
+ # Open the file in binary read mode, as recommended by tomli
79
+ with open(PROJECT_INFO_TOML_PATH, "rb") as f:
80
+ # Load the TOML data into a Python dictionary
81
+ toml_data = tomli.load(f)
82
+
83
+ # Unpack the dictionary into the Pydantic model
84
+ # Pydantic will handle all the validation from here.
85
+ obj = ProjectInfo(**toml_data)
86
+ return GetProjectInfoResponse(projectInfo=obj)
87
+
88
+ except FileNotFoundError:
89
+ return GetProjectInfoResponse(projectInfo=None)
90
+ except tomli.TOMLDecodeError as e:
91
+ print(f"Error: Could not decode the TOML file. Invalid syntax: {e}")
92
+ raise
93
+ except ValidationError as e:
94
+ # Pydantic's validation error is very informative
95
+ print(f"Error: Configuration is invalid. {e}")
96
+ raise
97
+
98
+
99
+ class SetProjectInfoRequest(BaseModel):
100
+ projectInfo: ProjectInfo
101
+
102
+
103
+ @app.post("/app/v0/rpc/setProjectInfo")
104
+ def set_project_info(request: SetProjectInfoRequest) -> None:
105
+ try:
106
+ PROJECT_INFO_TOML_PATH.parent.mkdir(parents=True, exist_ok=True)
107
+
108
+ # Convert the Pydantic model to a dictionary for TOML serialization.
109
+ # Use mode=json to make the resulting dict json-serializable (and thus
110
+ # also toml serializable)
111
+ project_data_dict = request.projectInfo.model_dump(mode="json")
112
+
113
+ # Open the file in binary write mode to write the TOML data
114
+ with open(PROJECT_INFO_TOML_PATH, "wb") as f:
115
+ tomli_w.dump(project_data_dict, f)
116
+
117
+ return None
118
+
119
+ except IOError as e:
120
+ # This catches errors related to file operations (e.g., permissions, disk full)
121
+ error_message = f"Failed to write project information to file: {str(e)}"
122
+ print(error_message) # Log server-side
123
+ raise e
124
+ except Exception as e: # Catch any other unexpected errors
125
+ error_message = (
126
+ f"An unexpected error occurred while saving project info: {str(e)}"
127
+ )
128
+ print(error_message) # Log server-side
129
+ raise e
130
+
131
+
132
+ class RGlobRequest(BaseModel):
133
+ baseDir: Path
134
+ pattern: str
135
+ noDirs: bool = False
136
+ stat: bool = False
137
+
138
+
139
+ class RGlobResponseEntry(BaseModel):
140
+ path: Path
141
+
142
+ # Present only if request had stat=True or noDirs=True
143
+ type: str | None
144
+
145
+ # Present only if request had stat=True
146
+
147
+ size: int | None
148
+ # Creation timestamp, ISO format.
149
+ cTime: str | None
150
+ # Modified timestamp, ISO format.
151
+ mTime: str | None
152
+
153
+
154
+ class RGlobResponse(BaseModel):
155
+ entries: list[RGlobResponseEntry]
156
+ relativeTo: Path # this is going to be the same base_dir that was in the request.
157
+
158
+
159
+ @app.post("/app/v0/rpc/rglob")
160
+ def rglob(request: RGlobRequest) -> RGlobResponse:
161
+ # Prevent secrets like /etc/passwd and ~/.ssh/ from being leaked.
162
+ if not (request.pattern.endswith(".csv") or request.pattern.endswith(".mp4")):
163
+ raise HTTPException(
164
+ status_code=status.HTTP_403_FORBIDDEN,
165
+ detail="Only csv and mp4 files are supported.",
166
+ )
167
+
168
+ response = RGlobResponse(entries=[], relativeTo=request.baseDir)
169
+
170
+ results = super_rglob(
171
+ str(request.baseDir),
172
+ pattern=request.pattern,
173
+ no_dirs=request.noDirs,
174
+ stat=request.stat,
175
+ )
176
+ for r in results:
177
+ # Convert dict to pydantic model
178
+ converted = RGlobResponseEntry.model_validate(r)
179
+ response.entries.append(converted)
180
+
181
+ return response
182
+
183
+
184
+ class FFProbeRequest(BaseModel):
185
+ path: Path
186
+
187
+
188
+ class FFProbeResponse(BaseModel):
189
+ codec: str
190
+ width: int
191
+ height: int
192
+ fps: int
193
+ duration: float
194
+
195
+
196
+ @app.post("/app/v0/rpc/ffprobe")
197
+ def ffprobe(request: FFProbeRequest) -> FFProbeResponse:
198
+ if request.path.suffix != ".mp4":
199
+ raise HTTPException(
200
+ status_code=status.HTTP_403_FORBIDDEN,
201
+ detail="Only mp4 files are supported.",
202
+ )
203
+
204
+ result = run_ffprobe(str(request.path))
205
+
206
+ response = FFProbeResponse.model_validate(result)
207
+
208
+ return response
209
+
210
+
211
+ """
212
+ File server to serve csv and video files.
213
+ FileResponse supports range requests for video buffering.
214
+ For security - only supports reading out of data_dir and model_dir
215
+ If we need to read out of other directories, they should be added to Project Info.
216
+ """
217
+
218
+
219
+ @app.get("/app/v0/files/{file_path:path}")
220
+ def read_file(file_path: Path):
221
+ # Prevent secrets like /etc/passwd and ~/.ssh/ from being leaked.
222
+ if file_path.suffix not in (".csv", ".mp4"):
223
+ raise HTTPException(
224
+ status_code=status.HTTP_403_FORBIDDEN,
225
+ detail="Only csv and mp4 files are supported.",
226
+ )
227
+ file_path = Path("/") / file_path
228
+
229
+ # Only capable of returning files that exist (not directories).
230
+ if not file_path.is_file():
231
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
232
+
233
+ return FileResponse(file_path)
234
+
235
+
236
+ ###########################################################################
237
+ # Serving angular
238
+ #
239
+ # In dev mode, `ng serve` serves ng, and proxies to us for backend requests.
240
+ # In production mode, we will serve ng.
241
+ # This is necessary to use HTTP2 for faster concurrent request performance (ng serve doesn't support it).
242
+ ###########################################################################
243
+
244
+ # Serve ng assets (js, css)
245
+ STATIC_DIR = Path(__file__).parent / "ngdist" / "ng_app"
246
+ if not STATIC_DIR.is_dir():
247
+ message = dedent(
248
+ f"""
249
+ ⚠️ Warning: We couldn't find the necessary static assets (like HTML, CSS, JavaScript files).
250
+ As a result, only the HTTP API is currently running.
251
+
252
+ This usually happens if you've cloned the source code directly.
253
+ To fix this and get the full application working, you'll need to either:
254
+
255
+ - Build the application: Refer to development.md in the repository for steps.
256
+ - Copy static files: Obtain these files from a PyPI source distribution of a released
257
+ version and place them in:
258
+
259
+ {STATIC_DIR}
260
+ """
261
+ )
262
+ # print(f'{Fore.white}{Back.yellow}{message}{Style.reset}', file=sys.stderr)
263
+ print(f"{message}", file=sys.stderr)
264
+
265
+ app.mount("/static", StaticFiles(directory=STATIC_DIR, check_dir=False), name="static")
266
+
267
+
268
+ @app.get("/favicon.ico")
269
+ def favicon():
270
+ return FileResponse(Path(__file__).parent / "ngdist" / "ng_app" / "favicon.ico")
271
+
272
+
273
+ # Catch-all route. serve index.html.
274
+ @app.get("/{full_path:path}")
275
+ def index(full_path: Path):
276
+ return FileResponse(Path(__file__).parent / "ngdist" / "ng_app" / "index.html")
277
+
278
+
279
+ def get_static_files_if_needed():
280
+ cache_dir = Path("~/.lightning_pose/cache").expanduser()
281
+ # Version check
282
+ # App should run with "latest compatible version"
283
+ # this means that if lightning pose is installed, it gets the latest version compatible with that version.
284
+ # otherwise it gets just the latest version.
285
+ # Download the files?
286
+
287
+
288
+ def run_app(host: str, port: int):
289
+ get_static_files_if_needed()
290
+ uvicorn.run(app, host=host, port=port)