schema.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import hashlib
  6. import os
  7. import shutil
  8. import tempfile
  9. from pathlib import Path
  10. from typing import Iterable, List, Optional, Tuple, Union
  11. import av
  12. import strawberry
  13. from app_conf import (
  14. DATA_PATH,
  15. DEFAULT_VIDEO_PATH,
  16. MAX_UPLOAD_VIDEO_DURATION,
  17. UPLOADS_PATH,
  18. UPLOADS_PREFIX,
  19. )
  20. from data.data_types import (
  21. AddPointsInput,
  22. CancelPropagateInVideo,
  23. CancelPropagateInVideoInput,
  24. ClearPointsInFrameInput,
  25. ClearPointsInVideo,
  26. ClearPointsInVideoInput,
  27. CloseSession,
  28. CloseSessionInput,
  29. RemoveObjectInput,
  30. RLEMask,
  31. RLEMaskForObject,
  32. RLEMaskListOnFrame,
  33. StartSession,
  34. StartSessionInput,
  35. Video,
  36. )
  37. from data.loader import get_video
  38. from data.store import get_videos
  39. from data.transcoder import get_video_metadata, transcode, VideoMetadata
  40. from inference.data_types import (
  41. AddPointsRequest,
  42. CancelPropagateInVideoRequest,
  43. CancelPropagateInVideoRequest,
  44. ClearPointsInFrameRequest,
  45. ClearPointsInVideoRequest,
  46. CloseSessionRequest,
  47. RemoveObjectRequest,
  48. StartSessionRequest,
  49. )
  50. from inference.predictor import InferenceAPI
  51. from strawberry import relay
  52. from strawberry.file_uploads import Upload
  53. @strawberry.type
  54. class Query:
  55. @strawberry.field
  56. def default_video(self) -> Video:
  57. """
  58. Return the default video.
  59. The default video can be set with the DEFAULT_VIDEO_PATH environment
  60. variable. It will return the video that matches this path. If no video
  61. is found, it will return the first video.
  62. """
  63. all_videos = get_videos()
  64. # Find the video that matches the default path and return that as
  65. # default video.
  66. for _, v in all_videos.items():
  67. if v.path == DEFAULT_VIDEO_PATH:
  68. return v
  69. # Fallback is returning the first video
  70. return next(iter(all_videos.values()))
  71. @relay.connection(relay.ListConnection[Video])
  72. def videos(
  73. self,
  74. ) -> Iterable[Video]:
  75. """
  76. Return all available videos.
  77. """
  78. all_videos = get_videos()
  79. return all_videos.values()
  80. @strawberry.type
  81. class Mutation:
  82. @strawberry.mutation
  83. def upload_video(
  84. self,
  85. file: Upload,
  86. start_time_sec: Optional[float] = None,
  87. duration_time_sec: Optional[float] = None,
  88. ) -> Video:
  89. """
  90. Receive a video file and store it in the configured S3 bucket.
  91. """
  92. max_time = MAX_UPLOAD_VIDEO_DURATION
  93. filepath, file_key, vm = process_video(
  94. file,
  95. max_time=max_time,
  96. start_time_sec=start_time_sec,
  97. duration_time_sec=duration_time_sec,
  98. )
  99. video = get_video(
  100. filepath,
  101. UPLOADS_PATH,
  102. file_key=file_key,
  103. width=vm.width,
  104. height=vm.height,
  105. generate_poster=False,
  106. )
  107. return video
  108. @strawberry.mutation
  109. def start_session(
  110. self, input: StartSessionInput, info: strawberry.Info
  111. ) -> StartSession:
  112. inference_api: InferenceAPI = info.context["inference_api"]
  113. request = StartSessionRequest(
  114. type="start_session",
  115. path=f"{DATA_PATH}/{input.path}",
  116. )
  117. response = inference_api.start_session(request=request)
  118. return StartSession(session_id=response.session_id)
  119. @strawberry.mutation
  120. def close_session(
  121. self, input: CloseSessionInput, info: strawberry.Info
  122. ) -> CloseSession:
  123. inference_api: InferenceAPI = info.context["inference_api"]
  124. request = CloseSessionRequest(
  125. type="close_session",
  126. session_id=input.session_id,
  127. )
  128. response = inference_api.close_session(request)
  129. return CloseSession(success=response.success)
  130. @strawberry.mutation
  131. def add_points(
  132. self, input: AddPointsInput, info: strawberry.Info
  133. ) -> RLEMaskListOnFrame:
  134. inference_api: InferenceAPI = info.context["inference_api"]
  135. request = AddPointsRequest(
  136. type="add_points",
  137. session_id=input.session_id,
  138. frame_index=input.frame_index,
  139. object_id=input.object_id,
  140. points=input.points,
  141. labels=input.labels,
  142. clear_old_points=input.clear_old_points,
  143. )
  144. reponse = inference_api.add_points(request)
  145. return RLEMaskListOnFrame(
  146. frame_index=reponse.frame_index,
  147. rle_mask_list=[
  148. RLEMaskForObject(
  149. object_id=r.object_id,
  150. rle_mask=RLEMask(counts=r.mask.counts, size=r.mask.size, order="F"),
  151. )
  152. for r in reponse.results
  153. ],
  154. )
  155. @strawberry.mutation
  156. def remove_object(
  157. self, input: RemoveObjectInput, info: strawberry.Info
  158. ) -> List[RLEMaskListOnFrame]:
  159. inference_api: InferenceAPI = info.context["inference_api"]
  160. request = RemoveObjectRequest(
  161. type="remove_object", session_id=input.session_id, object_id=input.object_id
  162. )
  163. response = inference_api.remove_object(request)
  164. return [
  165. RLEMaskListOnFrame(
  166. frame_index=res.frame_index,
  167. rle_mask_list=[
  168. RLEMaskForObject(
  169. object_id=r.object_id,
  170. rle_mask=RLEMask(
  171. counts=r.mask.counts, size=r.mask.size, order="F"
  172. ),
  173. )
  174. for r in res.results
  175. ],
  176. )
  177. for res in response.results
  178. ]
  179. @strawberry.mutation
  180. def clear_points_in_frame(
  181. self, input: ClearPointsInFrameInput, info: strawberry.Info
  182. ) -> RLEMaskListOnFrame:
  183. inference_api: InferenceAPI = info.context["inference_api"]
  184. request = ClearPointsInFrameRequest(
  185. type="clear_points_in_frame",
  186. session_id=input.session_id,
  187. frame_index=input.frame_index,
  188. object_id=input.object_id,
  189. )
  190. response = inference_api.clear_points_in_frame(request)
  191. return RLEMaskListOnFrame(
  192. frame_index=response.frame_index,
  193. rle_mask_list=[
  194. RLEMaskForObject(
  195. object_id=r.object_id,
  196. rle_mask=RLEMask(counts=r.mask.counts, size=r.mask.size, order="F"),
  197. )
  198. for r in response.results
  199. ],
  200. )
  201. @strawberry.mutation
  202. def clear_points_in_video(
  203. self, input: ClearPointsInVideoInput, info: strawberry.Info
  204. ) -> ClearPointsInVideo:
  205. inference_api: InferenceAPI = info.context["inference_api"]
  206. request = ClearPointsInVideoRequest(
  207. type="clear_points_in_video",
  208. session_id=input.session_id,
  209. )
  210. response = inference_api.clear_points_in_video(request)
  211. return ClearPointsInVideo(success=response.success)
  212. @strawberry.mutation
  213. def cancel_propagate_in_video(
  214. self, input: CancelPropagateInVideoInput, info: strawberry.Info
  215. ) -> CancelPropagateInVideo:
  216. inference_api: InferenceAPI = info.context["inference_api"]
  217. request = CancelPropagateInVideoRequest(
  218. type="cancel_propagate_in_video",
  219. session_id=input.session_id,
  220. )
  221. response = inference_api.cancel_propagate_in_video(request)
  222. return CancelPropagateInVideo(success=response.success)
  223. def get_file_hash(video_path_or_file) -> str:
  224. if isinstance(video_path_or_file, str):
  225. with open(video_path_or_file, "rb") as in_f:
  226. result = hashlib.sha256(in_f.read()).hexdigest()
  227. else:
  228. video_path_or_file.seek(0)
  229. result = hashlib.sha256(video_path_or_file.read()).hexdigest()
  230. return result
  231. def _get_start_sec_duration_sec(
  232. start_time_sec: Union[float, None],
  233. duration_time_sec: Union[float, None],
  234. max_time: float,
  235. ) -> Tuple[float, float]:
  236. default_seek_t = int(os.environ.get("VIDEO_ENCODE_SEEK_TIME", "0"))
  237. if start_time_sec is None:
  238. start_time_sec = default_seek_t
  239. if duration_time_sec is not None:
  240. duration_time_sec = min(duration_time_sec, max_time)
  241. else:
  242. duration_time_sec = max_time
  243. return start_time_sec, duration_time_sec
  244. def process_video(
  245. file: Upload,
  246. max_time: float,
  247. start_time_sec: Optional[float] = None,
  248. duration_time_sec: Optional[float] = None,
  249. ) -> Tuple[Optional[str], str, str, VideoMetadata]:
  250. """
  251. Process file upload including video trimming and content moderation checks.
  252. Returns the filepath, s3_file_key, hash & video metaedata as a tuple.
  253. """
  254. with tempfile.TemporaryDirectory() as tempdir:
  255. in_path = f"{tempdir}/in.mp4"
  256. out_path = f"{tempdir}/out.mp4"
  257. with open(in_path, "wb") as in_f:
  258. in_f.write(file.read())
  259. try:
  260. video_metadata = get_video_metadata(in_path)
  261. except av.InvalidDataError:
  262. raise Exception("not valid video file")
  263. if video_metadata.num_video_streams == 0:
  264. raise Exception("video container does not contain a video stream")
  265. if video_metadata.width is None or video_metadata.height is None:
  266. raise Exception("video container does not contain width or height metadata")
  267. if video_metadata.duration_sec in (None, 0):
  268. raise Exception("video container does time duration metadata")
  269. start_time_sec, duration_time_sec = _get_start_sec_duration_sec(
  270. max_time=max_time,
  271. start_time_sec=start_time_sec,
  272. duration_time_sec=duration_time_sec,
  273. )
  274. # Transcode video to make sure videos returned to the app are all in
  275. # the same format, duration, resolution, fps.
  276. transcode(
  277. in_path,
  278. out_path,
  279. video_metadata,
  280. seek_t=start_time_sec,
  281. duration_time_sec=duration_time_sec,
  282. )
  283. os.remove(in_path) # don't need original video now
  284. out_video_metadata = get_video_metadata(out_path)
  285. if out_video_metadata.num_video_frames == 0:
  286. raise Exception(
  287. "transcode produced empty video; check seek time or your input video"
  288. )
  289. filepath = None
  290. file_key = None
  291. with open(out_path, "rb") as file_data:
  292. file_hash = get_file_hash(file_data)
  293. file_data.seek(0)
  294. file_key = UPLOADS_PREFIX + "/" + f"{file_hash}.mp4"
  295. filepath = os.path.join(UPLOADS_PATH, f"{file_hash}.mp4")
  296. assert filepath is not None and file_key is not None
  297. shutil.move(out_path, filepath)
  298. return filepath, file_key, out_video_metadata
  299. schema = strawberry.Schema(
  300. query=Query,
  301. mutation=Mutation,
  302. )