christopi commited on
Commit ·
5a4e7b8
1
Parent(s): e6280e4
feat: refactor whole repo
Browse files- neurons/miner.py +216 -116
- neurons/validator.py +218 -32
- services/google_drive/google_drive_manager.py +1 -16
- services/miner_utilities/miner_utils.py +123 -34
- services/scoring/server.py +255 -39
- services/upscaling/server.py +202 -82
- services/video_scheduler/video_utils.py +272 -97
- services/video_scheduler/worker.py +257 -102
- vidaio_subnet_core/global_config.py +1 -1
- vidaio_subnet_core/utilities/rate_limit.py +49 -13
- vidaio_subnet_core/validating/managing/miner_manager.py +263 -72
neurons/miner.py
CHANGED
|
@@ -1,158 +1,258 @@
|
|
| 1 |
-
import bittensor as bt
|
| 2 |
-
from vidaio_subnet_core.base.miner import BaseMiner
|
| 3 |
-
from typing import Tuple
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import time
|
|
|
|
|
|
|
|
|
|
| 5 |
from loguru import logger
|
|
|
|
|
|
|
| 6 |
from vidaio_subnet_core.protocol import VideoUpscalingProtocol
|
| 7 |
from services.miner_utilities.miner_utils import download_video, video_upscaler
|
| 8 |
from vidaio_subnet_core.utilities.minio_client import minio_client
|
| 9 |
-
import traceback
|
| 10 |
-
import uuid
|
| 11 |
|
| 12 |
class Miner(BaseMiner):
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
async def forward_upscaling_requests(self, synapse: VideoUpscalingProtocol):
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
logger.info(f"Receiving Request: {synapse}")
|
|
|
|
| 20 |
try:
|
| 21 |
-
payload_url = synapse.miner_payload.reference_video_url
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
object_name = f"{uploaded_file_id}.mp4"
|
| 29 |
|
| 30 |
await minio_client.upload_file(object_name, processed_video_path)
|
| 31 |
logger.info("Video uploaded successfully.")
|
| 32 |
-
sharing_link = await minio_client.get_presigned_url(object_name)
|
| 33 |
-
|
| 34 |
-
if uploaded_file_id is None or sharing_link is None:
|
| 35 |
-
logger.error("Upload failed")
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
# Schedule the deletion of the uploaded file after 60 seconds
|
| 42 |
-
# await asyncio.sleep(60)
|
| 43 |
-
# minio_client.delete_file(object_name)
|
| 44 |
|
| 45 |
-
logger.info(f"
|
|
|
|
|
|
|
|
|
|
| 46 |
return synapse
|
| 47 |
-
|
| 48 |
except Exception as e:
|
| 49 |
-
logger.error(f"Failed to
|
| 50 |
traceback.print_exc()
|
| 51 |
-
|
| 52 |
|
| 53 |
async def blacklist_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> Tuple[bool, str]:
|
| 54 |
"""
|
| 55 |
-
Determines whether
|
| 56 |
-
define the logic for blacklisting requests based on your needs and desired security parameters.
|
| 57 |
-
|
| 58 |
-
Blacklist runs before the synapse data has been deserialized (i.e. before synapse.data is available).
|
| 59 |
-
The synapse is instead contracted via the headers of the request. It is important to blacklist
|
| 60 |
-
requests before they are deserialized to avoid wasting resources on requests that will be ignored.
|
| 61 |
-
|
| 62 |
-
Args:
|
| 63 |
-
synapse (vectornet.protocol.Dummy): A synapse object constructed from the headers of the incoming request.
|
| 64 |
-
|
| 65 |
-
Returns:
|
| 66 |
-
Tuple[bool, str]: A tuple containing a boolean indicating whether the synapse's hotkey is blacklisted,
|
| 67 |
-
and a string providing the reason for the decision.
|
| 68 |
-
|
| 69 |
-
This function is a security measure to prevent resource wastage on undesired requests. It should be enhanced
|
| 70 |
-
to include checks against the metagraph for entity registration, validator status, and sufficient stake
|
| 71 |
-
before deserialization of synapse data to minimize processing overhead.
|
| 72 |
-
|
| 73 |
-
Example blacklist logic:
|
| 74 |
-
- Reject if the hotkey is not a registered entity within the metagraph.
|
| 75 |
-
- Consider blacklisting entities that are not validators or have insufficient stake.
|
| 76 |
-
|
| 77 |
-
In practice it would be wise to blacklist requests from entities that are not validators, or do not have
|
| 78 |
-
enough stake. This can be checked via metagraph.S and metagraph.validator_permit. You can always attain
|
| 79 |
-
the uid of the sender via a metagraph.hotkeys.index( synapse.dendrite.hotkey ) call.
|
| 80 |
-
|
| 81 |
-
Otherwise, allow the request to be processed further.
|
| 82 |
"""
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
logger.warning(
|
| 86 |
-
"Received a request without a dendrite or hotkey."
|
| 87 |
-
)
|
| 88 |
return True, "Missing dendrite or hotkey"
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
if (
|
| 93 |
not self.config.blacklist.allow_non_registered
|
| 94 |
and synapse.dendrite.hotkey not in self.metagraph.hotkeys
|
| 95 |
):
|
| 96 |
-
|
| 97 |
-
logger.trace(
|
| 98 |
-
f"Blacklisting un-registered hotkey {synapse.dendrite.hotkey}"
|
| 99 |
-
)
|
| 100 |
return True, "Unrecognized hotkey"
|
| 101 |
|
| 102 |
-
if self.config.blacklist.force_validator_permit:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
)
|
| 108 |
-
return True, "Non-validator hotkey"
|
| 109 |
-
|
| 110 |
-
logger.trace(
|
| 111 |
-
f"Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}"
|
| 112 |
-
)
|
| 113 |
return False, "Hotkey recognized!"
|
| 114 |
|
| 115 |
async def priority_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> float:
|
| 116 |
"""
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
This implementation assigns priority to incoming requests based on the calling entity's stake in the metagraph.
|
| 121 |
-
|
| 122 |
-
Args:
|
| 123 |
-
synapse (vectornet.protocol.Dummy): The synapse object that contains metadata about the incoming request.
|
| 124 |
-
|
| 125 |
-
Returns:
|
| 126 |
-
float: A priority score derived from the stake of the calling entity.
|
| 127 |
-
|
| 128 |
-
Miners may receive messages from multiple entities at once. This function determines which request should be
|
| 129 |
-
processed first. Higher values indicate that the request should be processed first. Lower values indicate
|
| 130 |
-
that the request should be processed later.
|
| 131 |
-
|
| 132 |
-
Example priority logic:
|
| 133 |
-
- A higher stake results in a higher priority value.
|
| 134 |
"""
|
| 135 |
-
if synapse.dendrite
|
| 136 |
-
logger.warning(
|
| 137 |
-
"Received a request without a dendrite or hotkey."
|
| 138 |
-
)
|
| 139 |
return 0.0
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
priority = float(
|
| 146 |
-
self.metagraph.S[caller_uid]
|
| 147 |
-
) # Return the stake as the priority.
|
| 148 |
-
logger.trace(
|
| 149 |
-
f"Prioritizing {synapse.dendrite.hotkey} with value: {priority}"
|
| 150 |
-
)
|
| 151 |
return priority
|
| 152 |
-
|
| 153 |
-
|
| 154 |
if __name__ == "__main__":
|
| 155 |
with Miner() as miner:
|
| 156 |
while True:
|
| 157 |
logger.info(f"Miner running... {time.time()}")
|
| 158 |
-
time.sleep(30)
|
|
|
|
| 1 |
+
# import bittensor as bt
|
| 2 |
+
# from vidaio_subnet_core.base.miner import BaseMiner
|
| 3 |
+
# from typing import Tuple
|
| 4 |
+
# import time
|
| 5 |
+
# from loguru import logger
|
| 6 |
+
# from vidaio_subnet_core.protocol import VideoUpscalingProtocol
|
| 7 |
+
# from services.miner_utilities.miner_utils import download_video, video_upscaler
|
| 8 |
+
# from vidaio_subnet_core.utilities.minio_client import minio_client
|
| 9 |
+
# import traceback
|
| 10 |
+
# import uuid
|
| 11 |
+
|
| 12 |
+
# class Miner(BaseMiner):
|
| 13 |
+
|
| 14 |
+
# def __init__(self, config=None):
|
| 15 |
+
# super(Miner, self).__init__()
|
| 16 |
+
|
| 17 |
+
# async def forward_upscaling_requests(self, synapse: VideoUpscalingProtocol):
|
| 18 |
+
|
| 19 |
+
# logger.info(f"Receiving Request: {synapse}")
|
| 20 |
+
# try:
|
| 21 |
+
# payload_url = synapse.miner_payload.reference_video_url
|
| 22 |
+
# allowed_maximum_size = synapse.miner_payload.maximum_optimized_size_mb
|
| 23 |
+
# payload_video_path = await download_video(payload_url)
|
| 24 |
+
# processed_video_path = await video_upscaler(payload_video_path)
|
| 25 |
+
# logger.info(f"Proceesed video path: {processed_video_path}")
|
| 26 |
+
|
| 27 |
+
# uploaded_file_id = uuid.uuid4()
|
| 28 |
+
# object_name = f"{uploaded_file_id}.mp4"
|
| 29 |
+
|
| 30 |
+
# await minio_client.upload_file(object_name, processed_video_path)
|
| 31 |
+
# logger.info("Video uploaded successfully.")
|
| 32 |
+
# sharing_link = await minio_client.get_presigned_url(object_name)
|
| 33 |
+
|
| 34 |
+
# if uploaded_file_id is None or sharing_link is None:
|
| 35 |
+
# logger.error("Upload failed")
|
| 36 |
+
|
| 37 |
+
# if sharing_link:
|
| 38 |
+
# logger.info(f"Public download link: {sharing_link}")
|
| 39 |
+
# synapse.miner_response.optimized_video_url = sharing_link
|
| 40 |
+
|
| 41 |
+
# # Schedule the deletion of the uploaded file after 60 seconds
|
| 42 |
+
# # await asyncio.sleep(60)
|
| 43 |
+
# # minio_client.delete_file(object_name)
|
| 44 |
+
|
| 45 |
+
# logger.info(f"Returning Response{synapse}")
|
| 46 |
+
# return synapse
|
| 47 |
+
|
| 48 |
+
# except Exception as e:
|
| 49 |
+
# logger.error(f"Failed to run forward_upscaling_request: {e}")
|
| 50 |
+
# traceback.print_exc()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# async def blacklist_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> Tuple[bool, str]:
|
| 54 |
+
# """
|
| 55 |
+
# Determines whether an incoming request should be blacklisted and thus ignored. Your implementation should
|
| 56 |
+
# define the logic for blacklisting requests based on your needs and desired security parameters.
|
| 57 |
+
|
| 58 |
+
# Blacklist runs before the synapse data has been deserialized (i.e. before synapse.data is available).
|
| 59 |
+
# The synapse is instead contracted via the headers of the request. It is important to blacklist
|
| 60 |
+
# requests before they are deserialized to avoid wasting resources on requests that will be ignored.
|
| 61 |
+
|
| 62 |
+
# Args:
|
| 63 |
+
# synapse (vectornet.protocol.Dummy): A synapse object constructed from the headers of the incoming request.
|
| 64 |
+
|
| 65 |
+
# Returns:
|
| 66 |
+
# Tuple[bool, str]: A tuple containing a boolean indicating whether the synapse's hotkey is blacklisted,
|
| 67 |
+
# and a string providing the reason for the decision.
|
| 68 |
+
|
| 69 |
+
# This function is a security measure to prevent resource wastage on undesired requests. It should be enhanced
|
| 70 |
+
# to include checks against the metagraph for entity registration, validator status, and sufficient stake
|
| 71 |
+
# before deserialization of synapse data to minimize processing overhead.
|
| 72 |
+
|
| 73 |
+
# Example blacklist logic:
|
| 74 |
+
# - Reject if the hotkey is not a registered entity within the metagraph.
|
| 75 |
+
# - Consider blacklisting entities that are not validators or have insufficient stake.
|
| 76 |
+
|
| 77 |
+
# In practice it would be wise to blacklist requests from entities that are not validators, or do not have
|
| 78 |
+
# enough stake. This can be checked via metagraph.S and metagraph.validator_permit. You can always attain
|
| 79 |
+
# the uid of the sender via a metagraph.hotkeys.index( synapse.dendrite.hotkey ) call.
|
| 80 |
+
|
| 81 |
+
# Otherwise, allow the request to be processed further.
|
| 82 |
+
# """
|
| 83 |
+
|
| 84 |
+
# if synapse.dendrite is None or synapse.dendrite.hotkey is None:
|
| 85 |
+
# logger.warning(
|
| 86 |
+
# "Received a request without a dendrite or hotkey."
|
| 87 |
+
# )
|
| 88 |
+
# return True, "Missing dendrite or hotkey"
|
| 89 |
+
|
| 90 |
+
# # TODO(developer): Define how miners should blacklist requests.
|
| 91 |
+
# uid = self.metagraph.hotkeys.index(synapse.dendrite.hotkey)
|
| 92 |
+
# if (
|
| 93 |
+
# not self.config.blacklist.allow_non_registered
|
| 94 |
+
# and synapse.dendrite.hotkey not in self.metagraph.hotkeys
|
| 95 |
+
# ):
|
| 96 |
+
# # Ignore requests from un-registered entities.
|
| 97 |
+
# logger.trace(
|
| 98 |
+
# f"Blacklisting un-registered hotkey {synapse.dendrite.hotkey}"
|
| 99 |
+
# )
|
| 100 |
+
# return True, "Unrecognized hotkey"
|
| 101 |
+
|
| 102 |
+
# if self.config.blacklist.force_validator_permit:
|
| 103 |
+
# # If the config is set to force validator permit, then we should only allow requests from validators.
|
| 104 |
+
# if not self.metagraph.validator_permit[uid]:
|
| 105 |
+
# logger.warning(
|
| 106 |
+
# f"Blacklisting a request from non-validator hotkey {synapse.dendrite.hotkey}"
|
| 107 |
+
# )
|
| 108 |
+
# return True, "Non-validator hotkey"
|
| 109 |
+
|
| 110 |
+
# logger.trace(
|
| 111 |
+
# f"Not Blacklisting recognized hotkey {synapse.dendrite.hotkey}"
|
| 112 |
+
# )
|
| 113 |
+
# return False, "Hotkey recognized!"
|
| 114 |
+
|
| 115 |
+
# async def priority_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> float:
|
| 116 |
+
# """
|
| 117 |
+
# The priority function determines the order in which requests are handled. More valuable or higher-priority
|
| 118 |
+
# requests are processed before others. You should design your own priority mechanism with care.
|
| 119 |
+
|
| 120 |
+
# This implementation assigns priority to incoming requests based on the calling entity's stake in the metagraph.
|
| 121 |
+
|
| 122 |
+
# Args:
|
| 123 |
+
# synapse (vectornet.protocol.Dummy): The synapse object that contains metadata about the incoming request.
|
| 124 |
+
|
| 125 |
+
# Returns:
|
| 126 |
+
# float: A priority score derived from the stake of the calling entity.
|
| 127 |
+
|
| 128 |
+
# Miners may receive messages from multiple entities at once. This function determines which request should be
|
| 129 |
+
# processed first. Higher values indicate that the request should be processed first. Lower values indicate
|
| 130 |
+
# that the request should be processed later.
|
| 131 |
+
|
| 132 |
+
# Example priority logic:
|
| 133 |
+
# - A higher stake results in a higher priority value.
|
| 134 |
+
# """
|
| 135 |
+
# if synapse.dendrite is None or synapse.dendrite.hotkey is None:
|
| 136 |
+
# logger.warning(
|
| 137 |
+
# "Received a request without a dendrite or hotkey."
|
| 138 |
+
# )
|
| 139 |
+
# return 0.0
|
| 140 |
+
|
| 141 |
+
# # TODO(developer): Define how miners should prioritize requests.
|
| 142 |
+
# caller_uid = self.metagraph.hotkeys.index(
|
| 143 |
+
# synapse.dendrite.hotkey
|
| 144 |
+
# ) # Get the caller index.
|
| 145 |
+
# priority = float(
|
| 146 |
+
# self.metagraph.S[caller_uid]
|
| 147 |
+
# ) # Return the stake as the priority.
|
| 148 |
+
# logger.trace(
|
| 149 |
+
# f"Prioritizing {synapse.dendrite.hotkey} with value: {priority}"
|
| 150 |
+
# )
|
| 151 |
+
# return priority
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# if __name__ == "__main__":
|
| 155 |
+
# with Miner() as miner:
|
| 156 |
+
# while True:
|
| 157 |
+
# logger.info(f"Miner running... {time.time()}")
|
| 158 |
+
# time.sleep(30)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
|
| 162 |
import time
|
| 163 |
+
import uuid
|
| 164 |
+
import traceback
|
| 165 |
+
from typing import Tuple
|
| 166 |
from loguru import logger
|
| 167 |
+
import bittensor as bt
|
| 168 |
+
from vidaio_subnet_core.base.miner import BaseMiner
|
| 169 |
from vidaio_subnet_core.protocol import VideoUpscalingProtocol
|
| 170 |
from services.miner_utilities.miner_utils import download_video, video_upscaler
|
| 171 |
from vidaio_subnet_core.utilities.minio_client import minio_client
|
|
|
|
|
|
|
| 172 |
|
| 173 |
class Miner(BaseMiner):
|
| 174 |
+
def __init__(self, config: dict | None = None) -> None:
|
| 175 |
+
"""
|
| 176 |
+
Initializes the Miner instance.
|
| 177 |
+
"""
|
| 178 |
+
super().__init__()
|
| 179 |
|
| 180 |
+
async def forward_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> VideoUpscalingProtocol:
|
| 181 |
+
"""
|
| 182 |
+
Processes a video upscaling request by downloading, upscaling,
|
| 183 |
+
uploading, and returning a sharing link.
|
| 184 |
+
"""
|
| 185 |
logger.info(f"Receiving Request: {synapse}")
|
| 186 |
+
|
| 187 |
try:
|
| 188 |
+
payload_url: str = synapse.miner_payload.reference_video_url
|
| 189 |
+
payload_video_path: str = await download_video(payload_url)
|
| 190 |
+
processed_video_path: str = await video_upscaler(payload_video_path)
|
| 191 |
+
logger.info(f"Processed video path: {processed_video_path}")
|
| 192 |
+
|
| 193 |
+
uploaded_file_id: uuid.UUID = uuid.uuid4()
|
| 194 |
+
object_name: str = f"{uploaded_file_id}.mp4"
|
|
|
|
| 195 |
|
| 196 |
await minio_client.upload_file(object_name, processed_video_path)
|
| 197 |
logger.info("Video uploaded successfully.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
sharing_link: str | None = await minio_client.get_presigned_url(object_name)
|
| 200 |
+
if not sharing_link:
|
| 201 |
+
logger.error("Upload failed")
|
| 202 |
+
return synapse
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
logger.info(f"Public download link: {sharing_link}")
|
| 205 |
+
synapse.miner_response.optimized_video_url = sharing_link
|
| 206 |
+
|
| 207 |
+
logger.info(f"Returning Response: {synapse}")
|
| 208 |
return synapse
|
| 209 |
+
|
| 210 |
except Exception as e:
|
| 211 |
+
logger.error(f"Failed to process upscaling request: {e}")
|
| 212 |
traceback.print_exc()
|
| 213 |
+
return synapse
|
| 214 |
|
| 215 |
async def blacklist_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> Tuple[bool, str]:
|
| 216 |
"""
|
| 217 |
+
Determines whether a request should be blacklisted based on the hotkey status.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
"""
|
| 219 |
+
if not synapse.dendrite or not synapse.dendrite.hotkey:
|
| 220 |
+
logger.warning("Received a request without a dendrite or hotkey.")
|
|
|
|
|
|
|
|
|
|
| 221 |
return True, "Missing dendrite or hotkey"
|
| 222 |
|
| 223 |
+
uid: int = self.metagraph.hotkeys.index(synapse.dendrite.hotkey)
|
| 224 |
+
|
| 225 |
if (
|
| 226 |
not self.config.blacklist.allow_non_registered
|
| 227 |
and synapse.dendrite.hotkey not in self.metagraph.hotkeys
|
| 228 |
):
|
| 229 |
+
logger.trace(f"Blacklisting unregistered hotkey {synapse.dendrite.hotkey}")
|
|
|
|
|
|
|
|
|
|
| 230 |
return True, "Unrecognized hotkey"
|
| 231 |
|
| 232 |
+
if self.config.blacklist.force_validator_permit and not self.metagraph.validator_permit[uid]:
|
| 233 |
+
logger.warning(f"Blacklisting non-validator hotkey {synapse.dendrite.hotkey}")
|
| 234 |
+
return True, "Non-validator hotkey"
|
| 235 |
+
|
| 236 |
+
logger.trace(f"Hotkey {synapse.dendrite.hotkey} recognized and allowed.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
return False, "Hotkey recognized!"
|
| 238 |
|
| 239 |
async def priority_upscaling_requests(self, synapse: VideoUpscalingProtocol) -> float:
|
| 240 |
"""
|
| 241 |
+
Assigns a priority to requests based on the stake of the requesting entity.
|
| 242 |
+
Higher stakes result in higher priority.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
"""
|
| 244 |
+
if not synapse.dendrite or not synapse.dendrite.hotkey:
|
| 245 |
+
logger.warning("Received a request without a dendrite or hotkey.")
|
|
|
|
|
|
|
| 246 |
return 0.0
|
| 247 |
|
| 248 |
+
caller_uid: int = self.metagraph.hotkeys.index(synapse.dendrite.hotkey)
|
| 249 |
+
priority: float = float(self.metagraph.S[caller_uid])
|
| 250 |
+
|
| 251 |
+
logger.trace(f"Prioritizing {synapse.dendrite.hotkey} with value: {priority}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
return priority
|
| 253 |
+
|
|
|
|
| 254 |
if __name__ == "__main__":
|
| 255 |
with Miner() as miner:
|
| 256 |
while True:
|
| 257 |
logger.info(f"Miner running... {time.time()}")
|
| 258 |
+
time.sleep(30)
|
neurons/validator.py
CHANGED
|
@@ -1,3 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from vidaio_subnet_core import validating, CONFIG, base, protocol
|
| 2 |
import bittensor as bt
|
| 3 |
import random
|
|
@@ -13,6 +164,19 @@ from concurrent.futures import ThreadPoolExecutor
|
|
| 13 |
|
| 14 |
|
| 15 |
class Validator(base.BaseValidator):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __init__(self):
|
| 17 |
super().__init__()
|
| 18 |
self.miner_manager = validating.managing.MinerManager(
|
|
@@ -31,13 +195,21 @@ class Validator(base.BaseValidator):
|
|
| 31 |
)
|
| 32 |
self.set_weights_executor = ThreadPoolExecutor(max_workers=1)
|
| 33 |
|
| 34 |
-
async def start_epoch(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
logger.info("Starting forward pass")
|
| 36 |
uids = list(range(len(self.metagraph.hotkeys)))
|
| 37 |
logger.debug(f"Initial UIDs: {uids}")
|
| 38 |
uids = self.miner_manager.consume(uids)
|
| 39 |
-
# uids = [2]
|
| 40 |
logger.info(f"Filtered UIDs after consumption: {uids}")
|
|
|
|
| 41 |
axons = [self.metagraph.axons[uid] for uid in uids]
|
| 42 |
miners = list(zip(axons, uids))
|
| 43 |
batch_size = 20
|
|
@@ -50,75 +222,89 @@ class Validator(base.BaseValidator):
|
|
| 50 |
logger.info(f"Processing batch {batch_idx + 1}/{len(miner_batches)}")
|
| 51 |
video_id, uploaded_object_name, synapse = await self.challenge_synthesizer.build_protocol()
|
| 52 |
logger.debug(f"Built challenge protocol {synapse.__dict__}")
|
| 53 |
-
|
| 54 |
-
axons =
|
| 55 |
-
for miner in batch:
|
| 56 |
-
uids.append(miner[1])
|
| 57 |
-
axons.append(miner[0])
|
| 58 |
logger.debug(f"Processing UIDs in batch: {uids}")
|
| 59 |
responses = await self.dendrite.forward(
|
| 60 |
axons=axons, synapse=synapse, timeout=200
|
| 61 |
)
|
| 62 |
logger.info(f"Received {len(responses)} responses from miners, deleting uploaded_file")
|
| 63 |
logger.info(responses)
|
| 64 |
-
video_4k_path = get_4k_vide_path(video_id)
|
| 65 |
|
|
|
|
| 66 |
await self.score(uids, responses, video_4k_path)
|
| 67 |
|
| 68 |
-
# minio_client.delete_file(uploaded_object_name)
|
| 69 |
-
# delete_videos_with_fileid(video_id)
|
| 70 |
-
|
| 71 |
logger.debug("Waiting 4 seconds before next batch")
|
| 72 |
await asyncio.sleep(4)
|
| 73 |
|
| 74 |
-
async def score(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
logger.info(f"Starting scoring for {len(uids)} miners")
|
| 76 |
-
distorted_urls = []
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
distorted_urls.append(response.miner_response.optimized_video_url)
|
| 80 |
-
logger.info(f"distored_urls: {distorted_urls}")
|
| 81 |
score_response = await self.score_client.post(
|
| 82 |
"/score",
|
| 83 |
-
json
|
| 84 |
"distorted_urls": distorted_urls,
|
| 85 |
-
"reference_path": reference_4k_path
|
| 86 |
},
|
| 87 |
-
timeout=60
|
| 88 |
)
|
|
|
|
| 89 |
response_json = score_response.json() # Get the full JSON response
|
| 90 |
scores: List[float] = response_json.get("scores", []) # Extract only the list
|
| 91 |
logger.info(f"Scores: {scores}")
|
| 92 |
logger.info(f"Updating miner manager with {len(scores)} scores")
|
| 93 |
self.miner_manager.step(scores, uids)
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
self.current_block = self.subtensor.get_current_block()
|
| 98 |
self.last_update = self.metagraph.last_update[self.uid]
|
| 99 |
uids, weights = self.miner_manager.weights
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
) = bt.utils.weight_utils.process_weights_for_netuid(
|
| 104 |
-
# uids=self.metagraph.uids,
|
| 105 |
-
uids = uids,
|
| 106 |
weights=weights,
|
| 107 |
netuid=self.config.netuid,
|
| 108 |
subtensor=self.subtensor,
|
| 109 |
metagraph=self.metagraph,
|
| 110 |
)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
uint_weights,
|
| 114 |
-
) = bt.utils.weight_utils.convert_weights_and_uids_for_emit(
|
| 115 |
uids=processed_weight_uids, weights=processed_weights
|
| 116 |
)
|
|
|
|
| 117 |
if self.current_block > self.last_update + CONFIG.SUBNET_TEMPO:
|
| 118 |
weight_info = list(zip(uint_uids, uint_weights))
|
| 119 |
weight_info_df = pd.DataFrame(weight_info, columns=["uid", "weight"])
|
| 120 |
logger.info(f"Weight info:\n{weight_info_df.to_markdown()}")
|
| 121 |
logger.info("Actually trying to set weights.")
|
|
|
|
| 122 |
try:
|
| 123 |
future = self.set_weights_executor.submit(
|
| 124 |
self.subtensor.set_weights,
|
|
@@ -130,7 +316,7 @@ class Validator(base.BaseValidator):
|
|
| 130 |
success, msg = future.result(timeout=120)
|
| 131 |
if not success:
|
| 132 |
logger.error(f"Failed to set weights: {msg}")
|
| 133 |
-
else:
|
| 134 |
logger.debug("Set weights successfully 😎")
|
| 135 |
except Exception as e:
|
| 136 |
logger.error(f"Failed to set weights: {e}")
|
|
|
|
| 1 |
+
# from vidaio_subnet_core import validating, CONFIG, base, protocol
|
| 2 |
+
# import bittensor as bt
|
| 3 |
+
# import random
|
| 4 |
+
# import httpx
|
| 5 |
+
# import asyncio
|
| 6 |
+
# from loguru import logger
|
| 7 |
+
# import traceback
|
| 8 |
+
# import pandas as pd
|
| 9 |
+
# from typing import List
|
| 10 |
+
# from vidaio_subnet_core.utilities.minio_client import minio_client
|
| 11 |
+
# from services.video_scheduler.video_utils import get_4k_vide_path, delete_videos_with_fileid
|
| 12 |
+
# from concurrent.futures import ThreadPoolExecutor
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# class Validator(base.BaseValidator):
|
| 16 |
+
# def __init__(self):
|
| 17 |
+
# super().__init__()
|
| 18 |
+
# self.miner_manager = validating.managing.MinerManager(
|
| 19 |
+
# uid=self.uid, wallet=self.wallet, metagraph=self.metagraph
|
| 20 |
+
# )
|
| 21 |
+
# logger.info("Initialized miner manager")
|
| 22 |
+
# self.challenge_synthesizer = validating.synthesizing.Synthesizer()
|
| 23 |
+
# logger.info("Initialized challenge synthesizer")
|
| 24 |
+
# self.dendrite = bt.dendrite(wallet=self.wallet)
|
| 25 |
+
# logger.info("Initialized dendrite")
|
| 26 |
+
# self.score_client = httpx.AsyncClient(
|
| 27 |
+
# base_url=f"http://{CONFIG.score.host}:{CONFIG.score.port}"
|
| 28 |
+
# )
|
| 29 |
+
# logger.info(
|
| 30 |
+
# f"Initialized score client with base URL: {CONFIG.score.host}:{CONFIG.score.port}"
|
| 31 |
+
# )
|
| 32 |
+
# self.set_weights_executor = ThreadPoolExecutor(max_workers=1)
|
| 33 |
+
|
| 34 |
+
# async def start_epoch(self):
|
| 35 |
+
# logger.info("Starting forward pass")
|
| 36 |
+
# uids = list(range(len(self.metagraph.hotkeys)))
|
| 37 |
+
# logger.debug(f"Initial UIDs: {uids}")
|
| 38 |
+
# uids = self.miner_manager.consume(uids)
|
| 39 |
+
# # uids = [2]
|
| 40 |
+
# logger.info(f"Filtered UIDs after consumption: {uids}")
|
| 41 |
+
# axons = [self.metagraph.axons[uid] for uid in uids]
|
| 42 |
+
# miners = list(zip(axons, uids))
|
| 43 |
+
# batch_size = 20
|
| 44 |
+
# miner_batches = [
|
| 45 |
+
# miners[i : i + batch_size] for i in range(0, len(miners), batch_size)
|
| 46 |
+
# ]
|
| 47 |
+
# logger.info(f"Created {len(miner_batches)} batches of size {batch_size}")
|
| 48 |
+
|
| 49 |
+
# for batch_idx, batch in enumerate(miner_batches):
|
| 50 |
+
# logger.info(f"Processing batch {batch_idx + 1}/{len(miner_batches)}")
|
| 51 |
+
# video_id, uploaded_object_name, synapse = await self.challenge_synthesizer.build_protocol()
|
| 52 |
+
# logger.debug(f"Built challenge protocol {synapse.__dict__}")
|
| 53 |
+
# uids = []
|
| 54 |
+
# axons = []
|
| 55 |
+
# for miner in batch:
|
| 56 |
+
# uids.append(miner[1])
|
| 57 |
+
# axons.append(miner[0])
|
| 58 |
+
# logger.debug(f"Processing UIDs in batch: {uids}")
|
| 59 |
+
# responses = await self.dendrite.forward(
|
| 60 |
+
# axons=axons, synapse=synapse, timeout=200
|
| 61 |
+
# )
|
| 62 |
+
# logger.info(f"Received {len(responses)} responses from miners, deleting uploaded_file")
|
| 63 |
+
# logger.info(responses)
|
| 64 |
+
# video_4k_path = get_4k_vide_path(video_id)
|
| 65 |
+
|
| 66 |
+
# await self.score(uids, responses, video_4k_path)
|
| 67 |
+
|
| 68 |
+
# # minio_client.delete_file(uploaded_object_name)
|
| 69 |
+
# # delete_videos_with_fileid(video_id)
|
| 70 |
+
|
| 71 |
+
# logger.debug("Waiting 4 seconds before next batch")
|
| 72 |
+
# await asyncio.sleep(4)
|
| 73 |
+
|
| 74 |
+
# async def score(self, uids: list[int], responses: list[protocol.Synapse], reference_4k_path: str):
|
| 75 |
+
# logger.info(f"Starting scoring for {len(uids)} miners")
|
| 76 |
+
# distorted_urls = []
|
| 77 |
+
# print(responses, uids)
|
| 78 |
+
# for uid, response in zip(uids, responses):
|
| 79 |
+
# distorted_urls.append(response.miner_response.optimized_video_url)
|
| 80 |
+
# logger.info(f"distored_urls: {distorted_urls}")
|
| 81 |
+
# score_response = await self.score_client.post(
|
| 82 |
+
# "/score",
|
| 83 |
+
# json = {
|
| 84 |
+
# "distorted_urls": distorted_urls,
|
| 85 |
+
# "reference_path": reference_4k_path
|
| 86 |
+
# },
|
| 87 |
+
# timeout=60
|
| 88 |
+
# )
|
| 89 |
+
# response_json = score_response.json() # Get the full JSON response
|
| 90 |
+
# scores: List[float] = response_json.get("scores", []) # Extract only the list
|
| 91 |
+
# logger.info(f"Scores: {scores}")
|
| 92 |
+
# logger.info(f"Updating miner manager with {len(scores)} scores")
|
| 93 |
+
# self.miner_manager.step(scores, uids)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# def set_weights(self):
|
| 97 |
+
# self.current_block = self.subtensor.get_current_block()
|
| 98 |
+
# self.last_update = self.metagraph.last_update[self.uid]
|
| 99 |
+
# uids, weights = self.miner_manager.weights
|
| 100 |
+
# (
|
| 101 |
+
# processed_weight_uids,
|
| 102 |
+
# processed_weights,
|
| 103 |
+
# ) = bt.utils.weight_utils.process_weights_for_netuid(
|
| 104 |
+
# # uids=self.metagraph.uids,
|
| 105 |
+
# uids = uids,
|
| 106 |
+
# weights=weights,
|
| 107 |
+
# netuid=self.config.netuid,
|
| 108 |
+
# subtensor=self.subtensor,
|
| 109 |
+
# metagraph=self.metagraph,
|
| 110 |
+
# )
|
| 111 |
+
# (
|
| 112 |
+
# uint_uids,
|
| 113 |
+
# uint_weights,
|
| 114 |
+
# ) = bt.utils.weight_utils.convert_weights_and_uids_for_emit(
|
| 115 |
+
# uids=processed_weight_uids, weights=processed_weights
|
| 116 |
+
# )
|
| 117 |
+
# if self.current_block > self.last_update + CONFIG.SUBNET_TEMPO:
|
| 118 |
+
# weight_info = list(zip(uint_uids, uint_weights))
|
| 119 |
+
# weight_info_df = pd.DataFrame(weight_info, columns=["uid", "weight"])
|
| 120 |
+
# logger.info(f"Weight info:\n{weight_info_df.to_markdown()}")
|
| 121 |
+
# logger.info("Actually trying to set weights.")
|
| 122 |
+
# try:
|
| 123 |
+
# future = self.set_weights_executor.submit(
|
| 124 |
+
# self.subtensor.set_weights,
|
| 125 |
+
# netuid=self.config.netuid,
|
| 126 |
+
# wallet=self.wallet,
|
| 127 |
+
# uids=uint_uids,
|
| 128 |
+
# weights=uint_weights,
|
| 129 |
+
# )
|
| 130 |
+
# success, msg = future.result(timeout=120)
|
| 131 |
+
# if not success:
|
| 132 |
+
# logger.error(f"Failed to set weights: {msg}")
|
| 133 |
+
# else:
|
| 134 |
+
# logger.debug("Set weights successfully 😎")
|
| 135 |
+
# except Exception as e:
|
| 136 |
+
# logger.error(f"Failed to set weights: {e}")
|
| 137 |
+
# traceback.print_exc()
|
| 138 |
+
|
| 139 |
+
# logger.info(f"Set weights result: {success}")
|
| 140 |
+
# else:
|
| 141 |
+
# logger.info(
|
| 142 |
+
# f"Not setting weights because current block {self.current_block} is not greater than last update {self.last_update} + tempo {CONFIG.SUBNET_TEMPO}"
|
| 143 |
+
# )
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# if __name__ == "__main__":
|
| 147 |
+
# validator = Validator()
|
| 148 |
+
# asyncio.run(validator.run())
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
|
| 152 |
from vidaio_subnet_core import validating, CONFIG, base, protocol
|
| 153 |
import bittensor as bt
|
| 154 |
import random
|
|
|
|
| 164 |
|
| 165 |
|
| 166 |
class Validator(base.BaseValidator):
|
| 167 |
+
"""
|
| 168 |
+
Validator class responsible for managing miners, synthesizing challenges,
|
| 169 |
+
scoring responses, and setting weights in the network.
|
| 170 |
+
It operates with a batch processing mechanism to handle forward passes and scoring.
|
| 171 |
+
|
| 172 |
+
Attributes:
|
| 173 |
+
miner_manager: Manages miner actions such as consumption.
|
| 174 |
+
challenge_synthesizer: Synthesizes challenge protocols for the miners.
|
| 175 |
+
dendrite: Interface for interacting with the dendrite service.
|
| 176 |
+
score_client: Async HTTP client for scoring miners.
|
| 177 |
+
set_weights_executor: Thread pool executor for setting weights.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
def __init__(self):
|
| 181 |
super().__init__()
|
| 182 |
self.miner_manager = validating.managing.MinerManager(
|
|
|
|
| 195 |
)
|
| 196 |
self.set_weights_executor = ThreadPoolExecutor(max_workers=1)
|
| 197 |
|
| 198 |
+
async def start_epoch(self) -> None:
|
| 199 |
+
"""
|
| 200 |
+
Starts the forward pass for the miners, processes them in batches,
|
| 201 |
+
builds a challenge protocol, scores the miners, and then deletes the
|
| 202 |
+
uploaded files after scoring.
|
| 203 |
+
|
| 204 |
+
This method involves interacting with the challenge synthesizer,
|
| 205 |
+
dendrite, and the scoring client in each batch processing loop.
|
| 206 |
+
"""
|
| 207 |
logger.info("Starting forward pass")
|
| 208 |
uids = list(range(len(self.metagraph.hotkeys)))
|
| 209 |
logger.debug(f"Initial UIDs: {uids}")
|
| 210 |
uids = self.miner_manager.consume(uids)
|
|
|
|
| 211 |
logger.info(f"Filtered UIDs after consumption: {uids}")
|
| 212 |
+
|
| 213 |
axons = [self.metagraph.axons[uid] for uid in uids]
|
| 214 |
miners = list(zip(axons, uids))
|
| 215 |
batch_size = 20
|
|
|
|
| 222 |
logger.info(f"Processing batch {batch_idx + 1}/{len(miner_batches)}")
|
| 223 |
video_id, uploaded_object_name, synapse = await self.challenge_synthesizer.build_protocol()
|
| 224 |
logger.debug(f"Built challenge protocol {synapse.__dict__}")
|
| 225 |
+
|
| 226 |
+
uids, axons = zip(*batch)
|
|
|
|
|
|
|
|
|
|
| 227 |
logger.debug(f"Processing UIDs in batch: {uids}")
|
| 228 |
responses = await self.dendrite.forward(
|
| 229 |
axons=axons, synapse=synapse, timeout=200
|
| 230 |
)
|
| 231 |
logger.info(f"Received {len(responses)} responses from miners, deleting uploaded_file")
|
| 232 |
logger.info(responses)
|
|
|
|
| 233 |
|
| 234 |
+
video_4k_path = get_4k_vide_path(video_id)
|
| 235 |
await self.score(uids, responses, video_4k_path)
|
| 236 |
|
|
|
|
|
|
|
|
|
|
| 237 |
logger.debug("Waiting 4 seconds before next batch")
|
| 238 |
await asyncio.sleep(4)
|
| 239 |
|
| 240 |
+
async def score(
|
| 241 |
+
self,
|
| 242 |
+
uids: List[int],
|
| 243 |
+
responses: List[protocol.Synapse],
|
| 244 |
+
reference_4k_path: str
|
| 245 |
+
) -> None:
|
| 246 |
+
"""
|
| 247 |
+
Scores the miners by comparing their responses with the reference 4k video.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
uids: List of miner UIDs that are being scored.
|
| 251 |
+
responses: List of Synapse responses from the miners.
|
| 252 |
+
reference_4k_path: Path to the reference 4k video for comparison.
|
| 253 |
+
|
| 254 |
+
This method sends the responses to the score service, retrieves the scores,
|
| 255 |
+
and updates the miner manager with the new scores.
|
| 256 |
+
"""
|
| 257 |
logger.info(f"Starting scoring for {len(uids)} miners")
|
| 258 |
+
distorted_urls = [response.miner_response.optimized_video_url for response in responses]
|
| 259 |
+
logger.info(f"distorted_urls: {distorted_urls}")
|
| 260 |
+
|
|
|
|
|
|
|
| 261 |
score_response = await self.score_client.post(
|
| 262 |
"/score",
|
| 263 |
+
json={
|
| 264 |
"distorted_urls": distorted_urls,
|
| 265 |
+
"reference_path": reference_4k_path,
|
| 266 |
},
|
| 267 |
+
timeout=60,
|
| 268 |
)
|
| 269 |
+
|
| 270 |
response_json = score_response.json() # Get the full JSON response
|
| 271 |
scores: List[float] = response_json.get("scores", []) # Extract only the list
|
| 272 |
logger.info(f"Scores: {scores}")
|
| 273 |
logger.info(f"Updating miner manager with {len(scores)} scores")
|
| 274 |
self.miner_manager.step(scores, uids)
|
| 275 |
|
| 276 |
+
def set_weights(self) -> None:
|
| 277 |
+
"""
|
| 278 |
+
Sets the weights for the network if the current block exceeds the last update
|
| 279 |
+
plus the configured tempo. It retrieves the processed weights and UIDs,
|
| 280 |
+
then submits the weight-setting operation to a separate thread.
|
| 281 |
|
| 282 |
+
This method logs the weight information and handles the submission of weights
|
| 283 |
+
to the subtensor. If the weights are set successfully, it logs the success
|
| 284 |
+
message; otherwise, it logs an error.
|
| 285 |
+
"""
|
| 286 |
self.current_block = self.subtensor.get_current_block()
|
| 287 |
self.last_update = self.metagraph.last_update[self.uid]
|
| 288 |
uids, weights = self.miner_manager.weights
|
| 289 |
+
|
| 290 |
+
processed_weight_uids, processed_weights = bt.utils.weight_utils.process_weights_for_netuid(
|
| 291 |
+
uids=uids,
|
|
|
|
|
|
|
|
|
|
| 292 |
weights=weights,
|
| 293 |
netuid=self.config.netuid,
|
| 294 |
subtensor=self.subtensor,
|
| 295 |
metagraph=self.metagraph,
|
| 296 |
)
|
| 297 |
+
|
| 298 |
+
uint_uids, uint_weights = bt.utils.weight_utils.convert_weights_and_uids_for_emit(
|
|
|
|
|
|
|
| 299 |
uids=processed_weight_uids, weights=processed_weights
|
| 300 |
)
|
| 301 |
+
|
| 302 |
if self.current_block > self.last_update + CONFIG.SUBNET_TEMPO:
|
| 303 |
weight_info = list(zip(uint_uids, uint_weights))
|
| 304 |
weight_info_df = pd.DataFrame(weight_info, columns=["uid", "weight"])
|
| 305 |
logger.info(f"Weight info:\n{weight_info_df.to_markdown()}")
|
| 306 |
logger.info("Actually trying to set weights.")
|
| 307 |
+
|
| 308 |
try:
|
| 309 |
future = self.set_weights_executor.submit(
|
| 310 |
self.subtensor.set_weights,
|
|
|
|
| 316 |
success, msg = future.result(timeout=120)
|
| 317 |
if not success:
|
| 318 |
logger.error(f"Failed to set weights: {msg}")
|
| 319 |
+
else:
|
| 320 |
logger.debug("Set weights successfully 😎")
|
| 321 |
except Exception as e:
|
| 322 |
logger.error(f"Failed to set weights: {e}")
|
services/google_drive/google_drive_manager.py
CHANGED
|
@@ -200,19 +200,4 @@ class GoogleDriveManager:
|
|
| 200 |
|
| 201 |
if __name__ == '__main__':
|
| 202 |
gdrive = GoogleDriveManager()
|
| 203 |
-
|
| 204 |
-
# uploaded_file_id, sharing_link = gdrive.upload_file("/workspace/vidaio-subnet/vidaio-subnet/services/video_scheduler/videos/857020_hd.mp4")
|
| 205 |
-
|
| 206 |
-
# if sharing_link:
|
| 207 |
-
# print(f"Public download link: {sharing_link}")
|
| 208 |
-
|
| 209 |
-
# if uploaded_file_id:
|
| 210 |
-
# gdrive.download_file(
|
| 211 |
-
# uploaded_file_id,
|
| 212 |
-
# "/workspace/vidaio-subnet/vidaio-subnet/services/upscaling/videos/downloaded_file.mp4"
|
| 213 |
-
# )
|
| 214 |
-
|
| 215 |
-
# gdrive.init_drive()
|
| 216 |
-
|
| 217 |
-
# if uploaded_file_id:
|
| 218 |
-
# gdrive.delete_files(uploaded_file_id)
|
|
|
|
| 200 |
|
| 201 |
if __name__ == '__main__':
|
| 202 |
gdrive = GoogleDriveManager()
|
| 203 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
services/miner_utilities/miner_utils.py
CHANGED
|
@@ -1,26 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import uuid
|
| 2 |
-
import
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
import httpx
|
| 5 |
-
import
|
| 6 |
from fastapi import HTTPException
|
| 7 |
from loguru import logger
|
| 8 |
-
import aiohttp
|
| 9 |
-
import json
|
| 10 |
from vidaio_subnet_core import CONFIG
|
| 11 |
|
| 12 |
async def download_video(url: str) -> Path:
|
| 13 |
"""
|
| 14 |
-
|
| 15 |
|
| 16 |
Args:
|
| 17 |
-
url: URL of the video to download
|
| 18 |
-
|
| 19 |
Returns:
|
| 20 |
-
Path:
|
| 21 |
-
|
| 22 |
Raises:
|
| 23 |
-
HTTPException: If download fails
|
| 24 |
"""
|
| 25 |
try:
|
| 26 |
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
|
@@ -36,33 +124,38 @@ async def download_video(url: str) -> Path:
|
|
| 36 |
|
| 37 |
response.raise_for_status()
|
| 38 |
|
| 39 |
-
# Define video directory and
|
| 40 |
video_dir = Path(__file__).parent.parent / "upscaling" / "videos"
|
| 41 |
video_dir.mkdir(parents=True, exist_ok=True)
|
| 42 |
|
| 43 |
-
# Generate a
|
| 44 |
filename = f"{uuid.uuid4()}.mp4"
|
| 45 |
output_path = video_dir / filename
|
| 46 |
|
| 47 |
-
# Save
|
| 48 |
-
|
| 49 |
-
video_file.write(response.content)
|
| 50 |
|
| 51 |
logger.info(f"Video downloaded successfully to {output_path}")
|
| 52 |
return output_path
|
| 53 |
-
|
| 54 |
except httpx.HTTPStatusError as e:
|
| 55 |
-
logger.error(f"HTTP error downloading video: {
|
| 56 |
-
|
| 57 |
-
logger.error(f"Response headers: {e.response.headers}")
|
| 58 |
-
raise HTTPException(status_code=500, detail=f"Failed to download video: {str(e)}")
|
| 59 |
except Exception as e:
|
| 60 |
-
logger.error(f"Error downloading video: {
|
| 61 |
-
raise HTTPException(status_code=500, detail=f"Failed to download video: {
|
| 62 |
-
|
| 63 |
|
| 64 |
-
async def video_upscaler(input_file_path):
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
headers = {"Content-Type": "application/json"}
|
| 67 |
data = {"task_file_path": str(input_file_path)}
|
| 68 |
|
|
@@ -71,16 +164,12 @@ async def video_upscaler(input_file_path):
|
|
| 71 |
if response.status == 200:
|
| 72 |
result = await response.json()
|
| 73 |
upscaled_video_path = result.get("upscaled_video_path")
|
| 74 |
-
|
| 75 |
return upscaled_video_path
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
|
| 81 |
if __name__ == "__main__":
|
| 82 |
video_url = "/root/workspace/vidaio-subnet/services/upscaling/videos/7a4297c6-970b-4f62-8aef-f4fb4f40156f.mp4"
|
| 83 |
-
|
| 84 |
-
# response = asyncio.run(video_upscaler(video_url))
|
| 85 |
-
# print(response)
|
| 86 |
-
asyncio.run(video_upscaler(video_url))
|
|
|
|
| 1 |
+
# import uuid
|
| 2 |
+
# import requests
|
| 3 |
+
# from pathlib import Path
|
| 4 |
+
# import httpx
|
| 5 |
+
# import asyncio
|
| 6 |
+
# from fastapi import HTTPException
|
| 7 |
+
# from loguru import logger
|
| 8 |
+
# import aiohttp
|
| 9 |
+
# import json
|
| 10 |
+
# from vidaio_subnet_core import CONFIG
|
| 11 |
+
|
| 12 |
+
# async def download_video(url: str) -> Path:
|
| 13 |
+
# """
|
| 14 |
+
# Download video with retries and proper redirect handling.
|
| 15 |
+
|
| 16 |
+
# Args:
|
| 17 |
+
# url: URL of the video to download
|
| 18 |
+
|
| 19 |
+
# Returns:
|
| 20 |
+
# Path: Path to the downloaded video file
|
| 21 |
+
|
| 22 |
+
# Raises:
|
| 23 |
+
# HTTPException: If download fails
|
| 24 |
+
# """
|
| 25 |
+
# try:
|
| 26 |
+
# async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
| 27 |
+
# response = await client.get(url)
|
| 28 |
+
|
| 29 |
+
# if "drive.google.com" in url:
|
| 30 |
+
# if "drive.usercontent.google.com" in response.url.path:
|
| 31 |
+
# download_url = str(response.url)
|
| 32 |
+
# else:
|
| 33 |
+
# file_id = url.split("id=")[1].split("&")[0]
|
| 34 |
+
# download_url = f"https://drive.usercontent.google.com/download?id={file_id}&export=download"
|
| 35 |
+
# response = await client.get(download_url)
|
| 36 |
+
|
| 37 |
+
# response.raise_for_status()
|
| 38 |
+
|
| 39 |
+
# # Define video directory and create it if necessary
|
| 40 |
+
# video_dir = Path(__file__).parent.parent / "upscaling" / "videos"
|
| 41 |
+
# video_dir.mkdir(parents=True, exist_ok=True)
|
| 42 |
+
|
| 43 |
+
# # Generate a UUID filename
|
| 44 |
+
# filename = f"{uuid.uuid4()}.mp4"
|
| 45 |
+
# output_path = video_dir / filename
|
| 46 |
+
|
| 47 |
+
# # Save the video content to the output path
|
| 48 |
+
# with open(output_path, "wb") as video_file:
|
| 49 |
+
# video_file.write(response.content)
|
| 50 |
+
|
| 51 |
+
# logger.info(f"Video downloaded successfully to {output_path}")
|
| 52 |
+
# return output_path
|
| 53 |
+
|
| 54 |
+
# except httpx.HTTPStatusError as e:
|
| 55 |
+
# logger.error(f"HTTP error downloading video: {str(e)}")
|
| 56 |
+
# logger.error(f"Response status code: {e.response.status_code}")
|
| 57 |
+
# logger.error(f"Response headers: {e.response.headers}")
|
| 58 |
+
# raise HTTPException(status_code=500, detail=f"Failed to download video: {str(e)}")
|
| 59 |
+
# except Exception as e:
|
| 60 |
+
# logger.error(f"Error downloading video: {str(e)}")
|
| 61 |
+
# raise HTTPException(status_code=500, detail=f"Failed to download video: {str(e)}")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# async def video_upscaler(input_file_path):
|
| 65 |
+
# url=f"http://{CONFIG.video_upscaler.host}:{CONFIG.video_upscaler.port}/upscale-video"
|
| 66 |
+
# headers = {"Content-Type": "application/json"}
|
| 67 |
+
# data = {"task_file_path": str(input_file_path)}
|
| 68 |
+
|
| 69 |
+
# async with aiohttp.ClientSession() as session:
|
| 70 |
+
# async with session.post(url, headers=headers, data=json.dumps(data)) as response:
|
| 71 |
+
# if response.status == 200:
|
| 72 |
+
# result = await response.json()
|
| 73 |
+
# upscaled_video_path = result.get("upscaled_video_path")
|
| 74 |
+
# print("upscaled_video_path:", upscaled_video_path)
|
| 75 |
+
# return upscaled_video_path
|
| 76 |
+
# else:
|
| 77 |
+
# print("Error:", response.status)
|
| 78 |
+
# return None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# if __name__ == "__main__":
|
| 82 |
+
# video_url = "/root/workspace/vidaio-subnet/services/upscaling/videos/7a4297c6-970b-4f62-8aef-f4fb4f40156f.mp4"
|
| 83 |
+
# # # asyncio.run(download_video(video_url))
|
| 84 |
+
# # response = asyncio.run(video_upscaler(video_url))
|
| 85 |
+
# # print(response)
|
| 86 |
+
# asyncio.run(video_upscaler(video_url))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
import uuid
|
| 91 |
+
import json
|
| 92 |
+
import asyncio
|
| 93 |
from pathlib import Path
|
| 94 |
import httpx
|
| 95 |
+
import aiohttp
|
| 96 |
from fastapi import HTTPException
|
| 97 |
from loguru import logger
|
|
|
|
|
|
|
| 98 |
from vidaio_subnet_core import CONFIG
|
| 99 |
|
| 100 |
async def download_video(url: str) -> Path:
|
| 101 |
"""
|
| 102 |
+
Downloads a video from the given URL with retries and redirect handling.
|
| 103 |
|
| 104 |
Args:
|
| 105 |
+
url (str): The URL of the video to download.
|
| 106 |
+
|
| 107 |
Returns:
|
| 108 |
+
Path: The local path of the downloaded video.
|
| 109 |
+
|
| 110 |
Raises:
|
| 111 |
+
HTTPException: If the download fails.
|
| 112 |
"""
|
| 113 |
try:
|
| 114 |
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
|
|
|
| 124 |
|
| 125 |
response.raise_for_status()
|
| 126 |
|
| 127 |
+
# Define video directory and ensure it exists
|
| 128 |
video_dir = Path(__file__).parent.parent / "upscaling" / "videos"
|
| 129 |
video_dir.mkdir(parents=True, exist_ok=True)
|
| 130 |
|
| 131 |
+
# Generate a unique filename
|
| 132 |
filename = f"{uuid.uuid4()}.mp4"
|
| 133 |
output_path = video_dir / filename
|
| 134 |
|
| 135 |
+
# Save video content to file
|
| 136 |
+
output_path.write_bytes(response.content)
|
|
|
|
| 137 |
|
| 138 |
logger.info(f"Video downloaded successfully to {output_path}")
|
| 139 |
return output_path
|
| 140 |
+
|
| 141 |
except httpx.HTTPStatusError as e:
|
| 142 |
+
logger.error(f"HTTP error downloading video: {e}")
|
| 143 |
+
raise HTTPException(status_code=500, detail=f"Failed to download video: {e}")
|
|
|
|
|
|
|
| 144 |
except Exception as e:
|
| 145 |
+
logger.error(f"Error downloading video: {e}")
|
| 146 |
+
raise HTTPException(status_code=500, detail=f"Failed to download video: {e}")
|
|
|
|
| 147 |
|
| 148 |
+
async def video_upscaler(input_file_path: Path) -> str | None:
|
| 149 |
+
"""
|
| 150 |
+
Sends a video file path to the upscaling service and retrieves the processed video path.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
input_file_path (Path): The path of the video to be upscaled.
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
str | None: The path of the upscaled video or None if an error occurs.
|
| 157 |
+
"""
|
| 158 |
+
url = f"http://{CONFIG.video_upscaler.host}:{CONFIG.video_upscaler.port}/upscale-video"
|
| 159 |
headers = {"Content-Type": "application/json"}
|
| 160 |
data = {"task_file_path": str(input_file_path)}
|
| 161 |
|
|
|
|
| 164 |
if response.status == 200:
|
| 165 |
result = await response.json()
|
| 166 |
upscaled_video_path = result.get("upscaled_video_path")
|
| 167 |
+
logger.info(f"Upscaled video path: {upscaled_video_path}")
|
| 168 |
return upscaled_video_path
|
| 169 |
+
|
| 170 |
+
logger.error(f"Upscaling service error: {response.status}")
|
| 171 |
+
return None
|
|
|
|
| 172 |
|
| 173 |
if __name__ == "__main__":
|
| 174 |
video_url = "/root/workspace/vidaio-subnet/services/upscaling/videos/7a4297c6-970b-4f62-8aef-f4fb4f40156f.mp4"
|
| 175 |
+
asyncio.run(video_upscaler(video_url))
|
|
|
|
|
|
|
|
|
services/scoring/server.py
CHANGED
|
@@ -1,7 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from typing import Optional, List
|
| 4 |
-
from loguru import logger
|
| 5 |
import cv2
|
| 6 |
import numpy as np
|
| 7 |
from firerequests import FireRequests
|
|
@@ -13,13 +202,16 @@ from vmaf_metric import calculate_vmaf
|
|
| 13 |
from lpips_metric import calculate_lpips
|
| 14 |
import aiohttp
|
| 15 |
import logging
|
| 16 |
-
from loguru import logger
|
| 17 |
|
|
|
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
app = FastAPI()
|
| 20 |
fire_requests = FireRequests()
|
| 21 |
|
| 22 |
class ScoringRequest(BaseModel):
|
|
|
|
|
|
|
|
|
|
| 23 |
distorted_urls: List[str]
|
| 24 |
reference_path: str
|
| 25 |
fps: Optional[float] = None
|
|
@@ -28,25 +220,31 @@ class ScoringRequest(BaseModel):
|
|
| 28 |
progress: Optional[bool] = False
|
| 29 |
|
| 30 |
class ScoringResponse(BaseModel):
|
|
|
|
|
|
|
|
|
|
| 31 |
scores: List[float]
|
| 32 |
|
| 33 |
|
| 34 |
async def download_video(video_url: str, verbose: bool) -> str:
|
| 35 |
"""
|
| 36 |
Download a video from the given URL and save it to a temporary file.
|
| 37 |
-
|
| 38 |
Args:
|
| 39 |
video_url (str): The URL of the video to download.
|
| 40 |
verbose (bool): Whether to show download progress.
|
| 41 |
-
|
| 42 |
Returns:
|
| 43 |
str: The path to the downloaded video file.
|
|
|
|
|
|
|
|
|
|
| 44 |
"""
|
| 45 |
try:
|
| 46 |
# Create a temporary file for the video
|
| 47 |
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as vid_temp:
|
| 48 |
file_path = vid_temp.name # Path to the temporary file
|
| 49 |
-
|
| 50 |
|
| 51 |
# Download the file using aiohttp
|
| 52 |
async with aiohttp.ClientSession() as session:
|
|
@@ -63,7 +261,7 @@ async def download_video(video_url: str, verbose: bool) -> str:
|
|
| 63 |
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
|
| 64 |
raise Exception(f"Download failed or file is empty: {file_path}")
|
| 65 |
|
| 66 |
-
|
| 67 |
return file_path
|
| 68 |
|
| 69 |
except Exception as e:
|
|
@@ -72,18 +270,37 @@ async def download_video(video_url: str, verbose: bool) -> str:
|
|
| 72 |
|
| 73 |
|
| 74 |
def calculate_psnr(ref_frame: np.ndarray, dist_frame: np.ndarray) -> float:
|
| 75 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
mse = np.mean((ref_frame - dist_frame) ** 2)
|
| 77 |
if mse == 0:
|
| 78 |
-
return 1000
|
| 79 |
return 10 * np.log10((255.0**2) / mse)
|
| 80 |
|
| 81 |
|
| 82 |
-
|
| 83 |
@app.post("/score")
|
| 84 |
-
async def score(request: ScoringRequest):
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
ref_path = request.reference_path
|
| 88 |
ref_cap = cv2.VideoCapture(ref_path)
|
| 89 |
|
|
@@ -91,26 +308,28 @@ async def score(request: ScoringRequest):
|
|
| 91 |
raise HTTPException(status_code=500, detail="Error opening reference video file")
|
| 92 |
|
| 93 |
ref_total_frames = int(ref_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 94 |
-
|
|
|
|
| 95 |
if ref_total_frames <= 0:
|
| 96 |
raise HTTPException(status_code=500, detail="Invalid reference video: no frames found")
|
| 97 |
|
| 98 |
scores = []
|
| 99 |
for dist_url in request.distorted_urls:
|
| 100 |
ref_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
| 101 |
-
|
| 102 |
dist_path = await download_video(dist_url, request.verbose)
|
| 103 |
dist_cap = cv2.VideoCapture(dist_path)
|
| 104 |
|
| 105 |
if not dist_cap.isOpened():
|
| 106 |
-
|
| 107 |
scores.append(0.0)
|
| 108 |
continue # Skip to the next distorted video
|
| 109 |
|
| 110 |
dist_total_frames = int(dist_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 111 |
-
|
|
|
|
| 112 |
if dist_total_frames != ref_total_frames:
|
| 113 |
-
|
| 114 |
f"Video length mismatch for {dist_url}: ref({ref_total_frames}) != dist({dist_total_frames}). Assigning score of 0."
|
| 115 |
)
|
| 116 |
scores.append(0.0)
|
|
@@ -122,7 +341,7 @@ async def score(request: ScoringRequest):
|
|
| 122 |
try:
|
| 123 |
vmaf_score = calculate_vmaf(ref_path, dist_path)
|
| 124 |
except Exception as e:
|
| 125 |
-
|
| 126 |
scores.append(0.0)
|
| 127 |
dist_cap.release()
|
| 128 |
os.unlink(dist_path)
|
|
@@ -139,18 +358,17 @@ async def score(request: ScoringRequest):
|
|
| 139 |
ret_dist, dist_frame = dist_cap.read()
|
| 140 |
|
| 141 |
if not ret_ref or not ret_dist:
|
| 142 |
-
|
| 143 |
lpips_scores.append(1.0) # Assign a high LPIPS score (bad quality)
|
| 144 |
continue
|
| 145 |
|
| 146 |
lpips_score = calculate_lpips(ref_frame, dist_frame)
|
| 147 |
lpips_scores.append(lpips_score)
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
print(f"Average_lpips{average_lpips}")
|
| 154 |
# Final score calculation
|
| 155 |
final_score = vmaf_score * 0.6 + (1 - average_lpips) * 100 * 0.4
|
| 156 |
scores.append(final_score)
|
|
@@ -163,21 +381,19 @@ async def score(request: ScoringRequest):
|
|
| 163 |
|
| 164 |
return ScoringResponse(scores=scores)
|
| 165 |
|
| 166 |
-
if __name__ == "__main__":
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
# host = CONFIG.score.host
|
| 171 |
-
# port = CONFIG.score.port
|
| 172 |
|
| 173 |
-
|
|
|
|
| 174 |
|
|
|
|
| 175 |
|
| 176 |
-
#
|
| 177 |
-
urls = ScoringRequest(
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
print(scores)
|
|
|
|
| 1 |
+
# from fastapi import FastAPI, HTTPException
|
| 2 |
+
# from pydantic import BaseModel
|
| 3 |
+
# from typing import Optional, List
|
| 4 |
+
# from loguru import logger
|
| 5 |
+
# import cv2
|
| 6 |
+
# import numpy as np
|
| 7 |
+
# from firerequests import FireRequests
|
| 8 |
+
# import tempfile
|
| 9 |
+
# import os
|
| 10 |
+
# import random
|
| 11 |
+
# from vidaio_subnet_core import CONFIG
|
| 12 |
+
# from vmaf_metric import calculate_vmaf
|
| 13 |
+
# from lpips_metric import calculate_lpips
|
| 14 |
+
# import aiohttp
|
| 15 |
+
# import logging
|
| 16 |
+
# from loguru import logger
|
| 17 |
+
|
| 18 |
+
# logger = logging.getLogger(__name__)
|
| 19 |
+
# app = FastAPI()
|
| 20 |
+
# fire_requests = FireRequests()
|
| 21 |
+
|
| 22 |
+
# class ScoringRequest(BaseModel):
|
| 23 |
+
# distorted_urls: List[str]
|
| 24 |
+
# reference_path: str
|
| 25 |
+
# fps: Optional[float] = None
|
| 26 |
+
# subsample: Optional[int] = 1
|
| 27 |
+
# verbose: Optional[bool] = False
|
| 28 |
+
# progress: Optional[bool] = False
|
| 29 |
+
|
| 30 |
+
# class ScoringResponse(BaseModel):
|
| 31 |
+
# scores: List[float]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# async def download_video(video_url: str, verbose: bool) -> str:
|
| 35 |
+
# """
|
| 36 |
+
# Download a video from the given URL and save it to a temporary file.
|
| 37 |
+
|
| 38 |
+
# Args:
|
| 39 |
+
# video_url (str): The URL of the video to download.
|
| 40 |
+
# verbose (bool): Whether to show download progress.
|
| 41 |
+
|
| 42 |
+
# Returns:
|
| 43 |
+
# str: The path to the downloaded video file.
|
| 44 |
+
# """
|
| 45 |
+
# try:
|
| 46 |
+
# # Create a temporary file for the video
|
| 47 |
+
# with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as vid_temp:
|
| 48 |
+
# file_path = vid_temp.name # Path to the temporary file
|
| 49 |
+
# print(f"Downloading video from {video_url} to {file_path}")
|
| 50 |
+
|
| 51 |
+
# # Download the file using aiohttp
|
| 52 |
+
# async with aiohttp.ClientSession() as session:
|
| 53 |
+
# async with session.get(video_url) as response:
|
| 54 |
+
# if response.status != 200:
|
| 55 |
+
# raise Exception(f"Failed to download video. HTTP status: {response.status}")
|
| 56 |
+
|
| 57 |
+
# # Write the content to the temp file in chunks
|
| 58 |
+
# with open(file_path, "wb") as f:
|
| 59 |
+
# async for chunk in response.content.iter_chunked(2 * 1024 * 1024): # 2 MB chunks
|
| 60 |
+
# f.write(chunk)
|
| 61 |
+
|
| 62 |
+
# # Verify the file was successfully downloaded
|
| 63 |
+
# if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
|
| 64 |
+
# raise Exception(f"Download failed or file is empty: {file_path}")
|
| 65 |
+
|
| 66 |
+
# print(f"File successfully downloaded to: {file_path}")
|
| 67 |
+
# return file_path
|
| 68 |
+
|
| 69 |
+
# except Exception as e:
|
| 70 |
+
# logger.error(f"Failed to download video from {video_url}: {str(e)}")
|
| 71 |
+
# raise HTTPException(status_code=500, detail=f"Error downloading video: {str(e)}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# def calculate_psnr(ref_frame: np.ndarray, dist_frame: np.ndarray) -> float:
|
| 75 |
+
# """Calculate PSNR between reference and distorted frames."""
|
| 76 |
+
# mse = np.mean((ref_frame - dist_frame) ** 2)
|
| 77 |
+
# if mse == 0:
|
| 78 |
+
# return 1000
|
| 79 |
+
# return 10 * np.log10((255.0**2) / mse)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# @app.post("/score")
|
| 84 |
+
# async def score(request: ScoringRequest):
|
| 85 |
+
# print("Start scoring..........")
|
| 86 |
+
# print(request.__dict__)
|
| 87 |
+
# ref_path = request.reference_path
|
| 88 |
+
# ref_cap = cv2.VideoCapture(ref_path)
|
| 89 |
+
|
| 90 |
+
# if not ref_cap.isOpened():
|
| 91 |
+
# raise HTTPException(status_code=500, detail="Error opening reference video file")
|
| 92 |
+
|
| 93 |
+
# ref_total_frames = int(ref_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 94 |
+
# print(ref_total_frames)
|
| 95 |
+
# if ref_total_frames <= 0:
|
| 96 |
+
# raise HTTPException(status_code=500, detail="Invalid reference video: no frames found")
|
| 97 |
+
|
| 98 |
+
# scores = []
|
| 99 |
+
# for dist_url in request.distorted_urls:
|
| 100 |
+
# ref_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
| 101 |
+
# print("Attempting to download video....")
|
| 102 |
+
# dist_path = await download_video(dist_url, request.verbose)
|
| 103 |
+
# dist_cap = cv2.VideoCapture(dist_path)
|
| 104 |
+
|
| 105 |
+
# if not dist_cap.isOpened():
|
| 106 |
+
# print(f"Error opening distorted video file from {dist_url}. Assigning score of 0.")
|
| 107 |
+
# scores.append(0.0)
|
| 108 |
+
# continue # Skip to the next distorted video
|
| 109 |
+
|
| 110 |
+
# dist_total_frames = int(dist_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 111 |
+
# print(dist_total_frames)
|
| 112 |
+
# if dist_total_frames != ref_total_frames:
|
| 113 |
+
# print(
|
| 114 |
+
# f"Video length mismatch for {dist_url}: ref({ref_total_frames}) != dist({dist_total_frames}). Assigning score of 0."
|
| 115 |
+
# )
|
| 116 |
+
# scores.append(0.0)
|
| 117 |
+
# dist_cap.release()
|
| 118 |
+
# os.unlink(dist_path)
|
| 119 |
+
# continue # Skip to the next distorted video
|
| 120 |
+
|
| 121 |
+
# # Calculate VMAF
|
| 122 |
+
# try:
|
| 123 |
+
# vmaf_score = calculate_vmaf(ref_path, dist_path)
|
| 124 |
+
# except Exception as e:
|
| 125 |
+
# print(f"Failed to calculate VMAF for {dist_url}: {str(e)}. Assigning score of 0.")
|
| 126 |
+
# scores.append(0.0)
|
| 127 |
+
# dist_cap.release()
|
| 128 |
+
# os.unlink(dist_path)
|
| 129 |
+
# continue # Skip to the next distorted video
|
| 130 |
+
|
| 131 |
+
# # Select two random frames for LPIPS calculation
|
| 132 |
+
# frame_indices = random.sample(range(ref_total_frames), 2)
|
| 133 |
+
# lpips_scores = []
|
| 134 |
+
|
| 135 |
+
# for idx in frame_indices:
|
| 136 |
+
# ref_cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
|
| 137 |
+
# ret_ref, ref_frame = ref_cap.read()
|
| 138 |
+
# dist_cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
|
| 139 |
+
# ret_dist, dist_frame = dist_cap.read()
|
| 140 |
+
|
| 141 |
+
# if not ret_ref or not ret_dist:
|
| 142 |
+
# print(f"Frames cannot be read for {dist_url} at index {idx}. Assigning score of 0.")
|
| 143 |
+
# lpips_scores.append(1.0) # Assign a high LPIPS score (bad quality)
|
| 144 |
+
# continue
|
| 145 |
+
|
| 146 |
+
# lpips_score = calculate_lpips(ref_frame, dist_frame)
|
| 147 |
+
# lpips_scores.append(lpips_score)
|
| 148 |
+
# print(lpips_score)
|
| 149 |
+
# if lpips_scores:
|
| 150 |
+
# average_lpips = sum(lpips_scores) / len(lpips_scores)
|
| 151 |
+
# else:
|
| 152 |
+
# average_lpips = 1.0 # No valid LPIPS scores, assume worst case
|
| 153 |
+
# print(f"Average_lpips{average_lpips}")
|
| 154 |
+
# # Final score calculation
|
| 155 |
+
# final_score = vmaf_score * 0.6 + (1 - average_lpips) * 100 * 0.4
|
| 156 |
+
# scores.append(final_score)
|
| 157 |
+
|
| 158 |
+
# dist_cap.release()
|
| 159 |
+
# os.unlink(dist_path)
|
| 160 |
+
|
| 161 |
+
# # Cleanup
|
| 162 |
+
# ref_cap.release()
|
| 163 |
+
|
| 164 |
+
# return ScoringResponse(scores=scores)
|
| 165 |
+
|
| 166 |
+
# if __name__ == "__main__":
|
| 167 |
+
|
| 168 |
+
# import uvicorn
|
| 169 |
+
|
| 170 |
+
# host = CONFIG.score.host
|
| 171 |
+
# port = CONFIG.score.port
|
| 172 |
+
|
| 173 |
+
# uvicorn.run(app, host=host, port=port)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# # testing
|
| 177 |
+
# # urls = ScoringRequest(
|
| 178 |
+
# # distorted_urls=["https://s3.us-east-005.backblazeb2.com/grabucket/375.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=005b70354ce03130000000003%2F20250217%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250217T181945Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=a0fa1c8478cca42424d58a73d49604bc95d2f955eea52f7951a0bb80f350b043",],
|
| 179 |
+
# # reference_path="/root/workspace/vidaio-subnet/videos/4887282_4k.mp4"
|
| 180 |
+
# # )
|
| 181 |
+
|
| 182 |
+
# # scores = asyncio.run(score(urls))
|
| 183 |
+
# # print(scores)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
|
| 191 |
from fastapi import FastAPI, HTTPException
|
| 192 |
from pydantic import BaseModel
|
| 193 |
from typing import Optional, List
|
|
|
|
| 194 |
import cv2
|
| 195 |
import numpy as np
|
| 196 |
from firerequests import FireRequests
|
|
|
|
| 202 |
from lpips_metric import calculate_lpips
|
| 203 |
import aiohttp
|
| 204 |
import logging
|
|
|
|
| 205 |
|
| 206 |
+
# Set up logging
|
| 207 |
logger = logging.getLogger(__name__)
|
| 208 |
app = FastAPI()
|
| 209 |
fire_requests = FireRequests()
|
| 210 |
|
| 211 |
class ScoringRequest(BaseModel):
|
| 212 |
+
"""
|
| 213 |
+
Request model for scoring. Contains URLs for distorted videos and the reference video path.
|
| 214 |
+
"""
|
| 215 |
distorted_urls: List[str]
|
| 216 |
reference_path: str
|
| 217 |
fps: Optional[float] = None
|
|
|
|
| 220 |
progress: Optional[bool] = False
|
| 221 |
|
| 222 |
class ScoringResponse(BaseModel):
|
| 223 |
+
"""
|
| 224 |
+
Response model for scoring. Contains the list of calculated scores for each distorted video.
|
| 225 |
+
"""
|
| 226 |
scores: List[float]
|
| 227 |
|
| 228 |
|
| 229 |
async def download_video(video_url: str, verbose: bool) -> str:
|
| 230 |
"""
|
| 231 |
Download a video from the given URL and save it to a temporary file.
|
| 232 |
+
|
| 233 |
Args:
|
| 234 |
video_url (str): The URL of the video to download.
|
| 235 |
verbose (bool): Whether to show download progress.
|
| 236 |
+
|
| 237 |
Returns:
|
| 238 |
str: The path to the downloaded video file.
|
| 239 |
+
|
| 240 |
+
Raises:
|
| 241 |
+
HTTPException: If the download fails.
|
| 242 |
"""
|
| 243 |
try:
|
| 244 |
# Create a temporary file for the video
|
| 245 |
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as vid_temp:
|
| 246 |
file_path = vid_temp.name # Path to the temporary file
|
| 247 |
+
logger.info(f"Downloading video from {video_url} to {file_path}")
|
| 248 |
|
| 249 |
# Download the file using aiohttp
|
| 250 |
async with aiohttp.ClientSession() as session:
|
|
|
|
| 261 |
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
|
| 262 |
raise Exception(f"Download failed or file is empty: {file_path}")
|
| 263 |
|
| 264 |
+
logger.info(f"File successfully downloaded to: {file_path}")
|
| 265 |
return file_path
|
| 266 |
|
| 267 |
except Exception as e:
|
|
|
|
| 270 |
|
| 271 |
|
| 272 |
def calculate_psnr(ref_frame: np.ndarray, dist_frame: np.ndarray) -> float:
|
| 273 |
+
"""
|
| 274 |
+
Calculate Peak Signal-to-Noise Ratio (PSNR) between reference and distorted frames.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
ref_frame (np.ndarray): The reference video frame.
|
| 278 |
+
dist_frame (np.ndarray): The distorted video frame.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
float: The PSNR value between the reference and distorted frames.
|
| 282 |
+
"""
|
| 283 |
mse = np.mean((ref_frame - dist_frame) ** 2)
|
| 284 |
if mse == 0:
|
| 285 |
+
return 1000 # Maximum PSNR value (perfect similarity)
|
| 286 |
return 10 * np.log10((255.0**2) / mse)
|
| 287 |
|
| 288 |
|
|
|
|
| 289 |
@app.post("/score")
|
| 290 |
+
async def score(request: ScoringRequest) -> ScoringResponse:
|
| 291 |
+
"""
|
| 292 |
+
Scores the distorted videos by comparing them with the reference video using VMAF and LPIPS.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
request (ScoringRequest): The request object containing URLs for distorted videos
|
| 296 |
+
and the reference video path.
|
| 297 |
+
|
| 298 |
+
Returns:
|
| 299 |
+
ScoringResponse: The response object containing a list of scores for each distorted video.
|
| 300 |
+
"""
|
| 301 |
+
logger.info("Start scoring..........")
|
| 302 |
+
logger.debug(f"Request data: {request.dict()}")
|
| 303 |
+
|
| 304 |
ref_path = request.reference_path
|
| 305 |
ref_cap = cv2.VideoCapture(ref_path)
|
| 306 |
|
|
|
|
| 308 |
raise HTTPException(status_code=500, detail="Error opening reference video file")
|
| 309 |
|
| 310 |
ref_total_frames = int(ref_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 311 |
+
logger.info(f"Reference video has {ref_total_frames} frames.")
|
| 312 |
+
|
| 313 |
if ref_total_frames <= 0:
|
| 314 |
raise HTTPException(status_code=500, detail="Invalid reference video: no frames found")
|
| 315 |
|
| 316 |
scores = []
|
| 317 |
for dist_url in request.distorted_urls:
|
| 318 |
ref_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
| 319 |
+
logger.info("Attempting to download video....")
|
| 320 |
dist_path = await download_video(dist_url, request.verbose)
|
| 321 |
dist_cap = cv2.VideoCapture(dist_path)
|
| 322 |
|
| 323 |
if not dist_cap.isOpened():
|
| 324 |
+
logger.error(f"Error opening distorted video file from {dist_url}. Assigning score of 0.")
|
| 325 |
scores.append(0.0)
|
| 326 |
continue # Skip to the next distorted video
|
| 327 |
|
| 328 |
dist_total_frames = int(dist_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 329 |
+
logger.info(f"Distorted video has {dist_total_frames} frames.")
|
| 330 |
+
|
| 331 |
if dist_total_frames != ref_total_frames:
|
| 332 |
+
logger.warning(
|
| 333 |
f"Video length mismatch for {dist_url}: ref({ref_total_frames}) != dist({dist_total_frames}). Assigning score of 0."
|
| 334 |
)
|
| 335 |
scores.append(0.0)
|
|
|
|
| 341 |
try:
|
| 342 |
vmaf_score = calculate_vmaf(ref_path, dist_path)
|
| 343 |
except Exception as e:
|
| 344 |
+
logger.error(f"Failed to calculate VMAF for {dist_url}: {str(e)}. Assigning score of 0.")
|
| 345 |
scores.append(0.0)
|
| 346 |
dist_cap.release()
|
| 347 |
os.unlink(dist_path)
|
|
|
|
| 358 |
ret_dist, dist_frame = dist_cap.read()
|
| 359 |
|
| 360 |
if not ret_ref or not ret_dist:
|
| 361 |
+
logger.error(f"Frames cannot be read for {dist_url} at index {idx}. Assigning score of 0.")
|
| 362 |
lpips_scores.append(1.0) # Assign a high LPIPS score (bad quality)
|
| 363 |
continue
|
| 364 |
|
| 365 |
lpips_score = calculate_lpips(ref_frame, dist_frame)
|
| 366 |
lpips_scores.append(lpips_score)
|
| 367 |
+
|
| 368 |
+
logger.info(f"LPIPS scores: {lpips_scores}")
|
| 369 |
+
average_lpips = sum(lpips_scores) / len(lpips_scores) if lpips_scores else 1.0 # Worst case
|
| 370 |
+
logger.info(f"Average LPIPS: {average_lpips}")
|
| 371 |
+
|
|
|
|
| 372 |
# Final score calculation
|
| 373 |
final_score = vmaf_score * 0.6 + (1 - average_lpips) * 100 * 0.4
|
| 374 |
scores.append(final_score)
|
|
|
|
| 381 |
|
| 382 |
return ScoringResponse(scores=scores)
|
| 383 |
|
|
|
|
| 384 |
|
| 385 |
+
if __name__ == "__main__":
|
| 386 |
+
import uvicorn
|
|
|
|
|
|
|
| 387 |
|
| 388 |
+
host = CONFIG.score.host
|
| 389 |
+
port = CONFIG.score.port
|
| 390 |
|
| 391 |
+
uvicorn.run(app, host=host, port=port)
|
| 392 |
|
| 393 |
+
# Testing (Uncomment and adjust if necessary)
|
| 394 |
+
# urls = ScoringRequest(
|
| 395 |
+
# distorted_urls=[...],
|
| 396 |
+
# reference_path="..."
|
| 397 |
+
# )
|
| 398 |
+
# scores = asyncio.run(score(urls))
|
| 399 |
+
# print(scores)
|
|
|
services/upscaling/server.py
CHANGED
|
@@ -1,151 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from pathlib import Path
|
| 4 |
import subprocess
|
| 5 |
from fastapi.responses import JSONResponse
|
| 6 |
import time
|
| 7 |
-
import asyncio
|
| 8 |
-
from vidaio_subnet_core import CONFIG
|
| 9 |
import re
|
| 10 |
-
|
|
|
|
| 11 |
from typing import Optional
|
| 12 |
|
| 13 |
app = FastAPI()
|
| 14 |
|
| 15 |
class UpscaleRequest(BaseModel):
|
|
|
|
| 16 |
task_file_path: str
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
def get_frame_rate(input_file: Path) -> float:
|
| 21 |
"""
|
| 22 |
-
|
| 23 |
|
| 24 |
Args:
|
| 25 |
-
input_file (Path):
|
| 26 |
|
| 27 |
Returns:
|
| 28 |
-
float:
|
|
|
|
|
|
|
|
|
|
| 29 |
"""
|
| 30 |
frame_rate_command = [
|
| 31 |
"ffmpeg",
|
| 32 |
"-i", str(input_file),
|
| 33 |
-
"-hide_banner"
|
| 34 |
]
|
| 35 |
process = subprocess.run(frame_rate_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 36 |
-
output = process.stderr # Frame rate is usually in stderr
|
| 37 |
|
| 38 |
-
# Extract frame rate using regex
|
| 39 |
match = re.search(r"(\d+(?:\.\d+)?) fps", output)
|
| 40 |
if match:
|
| 41 |
return float(match.group(1))
|
| 42 |
-
|
| 43 |
-
|
| 44 |
|
| 45 |
|
| 46 |
@app.post("/upscale-video")
|
| 47 |
-
def video_upscaler(request: UpscaleRequest):
|
| 48 |
"""
|
| 49 |
-
Upscales a video using the video2x tool
|
| 50 |
|
| 51 |
Args:
|
| 52 |
-
request (UpscaleRequest):
|
| 53 |
|
| 54 |
Returns:
|
| 55 |
-
dict: A dictionary
|
|
|
|
|
|
|
|
|
|
| 56 |
"""
|
| 57 |
try:
|
| 58 |
input_file = Path(request.task_file_path)
|
| 59 |
|
| 60 |
# Validate input file
|
| 61 |
if not input_file.exists() or not input_file.is_file():
|
| 62 |
-
raise HTTPException(status_code=400, detail="
|
| 63 |
|
| 64 |
-
# Get
|
| 65 |
frame_rate = get_frame_rate(input_file)
|
| 66 |
-
print(f"Frame rate detected: {frame_rate} fps")
|
| 67 |
-
|
| 68 |
-
# Calculate the duration to duplicate 2 frames
|
| 69 |
stop_duration = 2 / frame_rate
|
| 70 |
|
| 71 |
-
#
|
| 72 |
output_file_with_extra_frames = input_file.with_name(f"{input_file.stem}_extra_frames.mp4")
|
| 73 |
output_file_upscaled = input_file.with_name(f"4k_{input_file.stem}.mp4")
|
| 74 |
|
| 75 |
-
# Step 1: Duplicate
|
| 76 |
-
print("Step 1: Duplicating the last frame two times...")
|
| 77 |
-
start_time = time.time()
|
| 78 |
-
|
| 79 |
duplicate_last_frame_command = [
|
| 80 |
"ffmpeg",
|
| 81 |
"-i", str(input_file),
|
| 82 |
-
"-vf", f"tpad=stop_mode=clone:stop_duration={stop_duration}",
|
| 83 |
-
"-c:v", "libx264",
|
| 84 |
-
"-crf", "18",
|
| 85 |
-
"-preset", "fast",
|
| 86 |
-
str(output_file_with_extra_frames)
|
| 87 |
]
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
elapsed_time = time.time() - start_time
|
| 94 |
-
if duplicate_last_frame_process.returncode != 0:
|
| 95 |
-
print(f"Duplicating frames failed: {duplicate_last_frame_process.stderr.strip()}")
|
| 96 |
-
raise HTTPException(status_code=500, detail=f"Duplicating frames failed: {duplicate_last_frame_process.stderr.strip()}")
|
| 97 |
-
if not output_file_with_extra_frames.exists():
|
| 98 |
-
print("MP4 video file with extra frames was not created.")
|
| 99 |
-
raise HTTPException(status_code=500, detail="MP4 video file with extra frames was not created.")
|
| 100 |
-
print(f"Step 1 completed in {elapsed_time:.2f} seconds. File with extra frames: {output_file_with_extra_frames}")
|
| 101 |
|
| 102 |
# Step 2: Upscale video using video2x
|
| 103 |
-
print("Step 2: Upscaling video using video2x...")
|
| 104 |
-
start_time = time.time()
|
| 105 |
video2x_command = [
|
| 106 |
"video2x",
|
| 107 |
"-i", str(output_file_with_extra_frames),
|
| 108 |
"-o", str(output_file_upscaled),
|
| 109 |
-
"-p", "realesrgan",
|
| 110 |
-
"-s", "2",
|
| 111 |
-
"-c", "libx264",
|
| 112 |
-
"-e", "preset=slow",
|
| 113 |
-
"-e", "crf=24"
|
| 114 |
]
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
if
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
print(f"Step 2 completed in {elapsed_time:.2f} seconds. Upscaled MP4 file: {output_file_upscaled}")
|
| 124 |
-
|
| 125 |
-
# Cleanup intermediate files if needed
|
| 126 |
-
if output_file_with_extra_frames.exists():
|
| 127 |
-
output_file_with_extra_frames.unlink()
|
| 128 |
-
print(f"Intermediate file {output_file_with_extra_frames} deleted.")
|
| 129 |
-
|
| 130 |
-
print(f"Returning from FastAPI: {output_file_upscaled}")
|
| 131 |
return {"upscaled_video_path": str(output_file_upscaled)}
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
-
print(f"Error: {str(e)}")
|
| 134 |
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
| 135 |
|
| 136 |
|
| 137 |
if __name__ == "__main__":
|
| 138 |
-
|
| 139 |
-
import uvicorn
|
| 140 |
-
|
| 141 |
-
host = CONFIG.video_upscaler.host
|
| 142 |
-
port = CONFIG.video_upscaler.port
|
| 143 |
-
|
| 144 |
-
uvicorn.run(app, host=host, port=port)
|
| 145 |
-
|
| 146 |
-
# class TestRequest:
|
| 147 |
-
# task_file_path = "/root/workspace/vidaio-subnet/videos/4887282_hd.mp4"
|
| 148 |
-
|
| 149 |
-
# # Simulate a request
|
| 150 |
-
# video = TestRequest()
|
| 151 |
-
# asyncio.run(video_upscaler(UpscaleRequest(task_file_path=video.task_file_path)))
|
|
|
|
| 1 |
+
# from fastapi import FastAPI, HTTPException
|
| 2 |
+
# from pydantic import BaseModel
|
| 3 |
+
# from pathlib import Path
|
| 4 |
+
# import subprocess
|
| 5 |
+
# from fastapi.responses import JSONResponse
|
| 6 |
+
# import time
|
| 7 |
+
# import asyncio
|
| 8 |
+
# from vidaio_subnet_core import CONFIG
|
| 9 |
+
# import re
|
| 10 |
+
# from pydantic import BaseModel
|
| 11 |
+
# from typing import Optional
|
| 12 |
+
|
| 13 |
+
# app = FastAPI()
|
| 14 |
+
|
| 15 |
+
# class UpscaleRequest(BaseModel):
|
| 16 |
+
# task_file_path: str
|
| 17 |
+
# # output_file_upscaled: Optional[str] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# def get_frame_rate(input_file: Path) -> float:
|
| 21 |
+
# """
|
| 22 |
+
# Extracts the frame rate of the input video using FFmpeg.
|
| 23 |
+
|
| 24 |
+
# Args:
|
| 25 |
+
# input_file (Path): The path to the video file.
|
| 26 |
+
|
| 27 |
+
# Returns:
|
| 28 |
+
# float: The frame rate of the video.
|
| 29 |
+
# """
|
| 30 |
+
# frame_rate_command = [
|
| 31 |
+
# "ffmpeg",
|
| 32 |
+
# "-i", str(input_file),
|
| 33 |
+
# "-hide_banner"
|
| 34 |
+
# ]
|
| 35 |
+
# process = subprocess.run(frame_rate_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 36 |
+
# output = process.stderr # Frame rate is usually in stderr
|
| 37 |
+
|
| 38 |
+
# # Extract frame rate using regex
|
| 39 |
+
# match = re.search(r"(\d+(?:\.\d+)?) fps", output)
|
| 40 |
+
# if match:
|
| 41 |
+
# return float(match.group(1))
|
| 42 |
+
# else:
|
| 43 |
+
# raise HTTPException(status_code=500, detail="Unable to determine frame rate of the video.")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# @app.post("/upscale-video")
|
| 47 |
+
# def video_upscaler(request: UpscaleRequest):
|
| 48 |
+
# """
|
| 49 |
+
# Upscales a video using the video2x tool and returns the full paths of the upscaled video and the converted mp4 file.
|
| 50 |
+
|
| 51 |
+
# Args:
|
| 52 |
+
# request (UpscaleRequest): Input containing the path to the video to upscale.
|
| 53 |
+
|
| 54 |
+
# Returns:
|
| 55 |
+
# dict: A dictionary containing the full paths to the upscaled video and the mp4 file.
|
| 56 |
+
# """
|
| 57 |
+
# try:
|
| 58 |
+
# input_file = Path(request.task_file_path)
|
| 59 |
+
|
| 60 |
+
# # Validate input file
|
| 61 |
+
# if not input_file.exists() or not input_file.is_file():
|
| 62 |
+
# raise HTTPException(status_code=400, detail="Input file does not exist or is not a valid file.")
|
| 63 |
+
|
| 64 |
+
# # Get the frame rate of the video
|
| 65 |
+
# frame_rate = get_frame_rate(input_file)
|
| 66 |
+
# print(f"Frame rate detected: {frame_rate} fps")
|
| 67 |
+
|
| 68 |
+
# # Calculate the duration to duplicate 2 frames
|
| 69 |
+
# stop_duration = 2 / frame_rate
|
| 70 |
+
|
| 71 |
+
# # Generate output file paths
|
| 72 |
+
# output_file_with_extra_frames = input_file.with_name(f"{input_file.stem}_extra_frames.mp4")
|
| 73 |
+
# output_file_upscaled = input_file.with_name(f"4k_{input_file.stem}.mp4")
|
| 74 |
+
|
| 75 |
+
# # Step 1: Duplicate the last frame two times
|
| 76 |
+
# print("Step 1: Duplicating the last frame two times...")
|
| 77 |
+
# start_time = time.time()
|
| 78 |
+
|
| 79 |
+
# duplicate_last_frame_command = [
|
| 80 |
+
# "ffmpeg",
|
| 81 |
+
# "-i", str(input_file),
|
| 82 |
+
# "-vf", f"tpad=stop_mode=clone:stop_duration={stop_duration}", # Dynamically calculated duration
|
| 83 |
+
# "-c:v", "libx264", # Ensure proper encoding
|
| 84 |
+
# "-crf", "18", # High-quality encoding
|
| 85 |
+
# "-preset", "fast", # Fast encoding preset
|
| 86 |
+
# str(output_file_with_extra_frames)
|
| 87 |
+
# ]
|
| 88 |
+
|
| 89 |
+
# duplicate_last_frame_process = subprocess.run(
|
| 90 |
+
# duplicate_last_frame_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
|
| 91 |
+
# )
|
| 92 |
+
|
| 93 |
+
# elapsed_time = time.time() - start_time
|
| 94 |
+
# if duplicate_last_frame_process.returncode != 0:
|
| 95 |
+
# print(f"Duplicating frames failed: {duplicate_last_frame_process.stderr.strip()}")
|
| 96 |
+
# raise HTTPException(status_code=500, detail=f"Duplicating frames failed: {duplicate_last_frame_process.stderr.strip()}")
|
| 97 |
+
# if not output_file_with_extra_frames.exists():
|
| 98 |
+
# print("MP4 video file with extra frames was not created.")
|
| 99 |
+
# raise HTTPException(status_code=500, detail="MP4 video file with extra frames was not created.")
|
| 100 |
+
# print(f"Step 1 completed in {elapsed_time:.2f} seconds. File with extra frames: {output_file_with_extra_frames}")
|
| 101 |
+
|
| 102 |
+
# # Step 2: Upscale video using video2x
|
| 103 |
+
# print("Step 2: Upscaling video using video2x...")
|
| 104 |
+
# start_time = time.time()
|
| 105 |
+
# video2x_command = [
|
| 106 |
+
# "video2x",
|
| 107 |
+
# "-i", str(output_file_with_extra_frames),
|
| 108 |
+
# "-o", str(output_file_upscaled),
|
| 109 |
+
# "-p", "realesrgan", # Use Real-ESRGAN for upscaling
|
| 110 |
+
# "-s", "2", # Scale factor of 2
|
| 111 |
+
# "-c", "libx264", # Encode with H.264
|
| 112 |
+
# "-e", "preset=slow", # Slow preset for better quality
|
| 113 |
+
# "-e", "crf=24" # Compression level
|
| 114 |
+
# ]
|
| 115 |
+
# video2x_process = subprocess.run(video2x_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 116 |
+
# elapsed_time = time.time() - start_time
|
| 117 |
+
# if video2x_process.returncode != 0:
|
| 118 |
+
# print(f"Upscaling failed: {video2x_process.stderr.strip()}")
|
| 119 |
+
# raise HTTPException(status_code=500, detail=f"Upscaling failed: {video2x_process.stderr.strip()}")
|
| 120 |
+
# if not output_file_upscaled.exists():
|
| 121 |
+
# print("Upscaled MP4 video file was not created.")
|
| 122 |
+
# raise HTTPException(status_code=500, detail="Upscaled MP4 video file was not created.")
|
| 123 |
+
# print(f"Step 2 completed in {elapsed_time:.2f} seconds. Upscaled MP4 file: {output_file_upscaled}")
|
| 124 |
+
|
| 125 |
+
# # Cleanup intermediate files if needed
|
| 126 |
+
# if output_file_with_extra_frames.exists():
|
| 127 |
+
# output_file_with_extra_frames.unlink()
|
| 128 |
+
# print(f"Intermediate file {output_file_with_extra_frames} deleted.")
|
| 129 |
+
|
| 130 |
+
# print(f"Returning from FastAPI: {output_file_upscaled}")
|
| 131 |
+
# return {"upscaled_video_path": str(output_file_upscaled)}
|
| 132 |
+
# except Exception as e:
|
| 133 |
+
# print(f"Error: {str(e)}")
|
| 134 |
+
# raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# if __name__ == "__main__":
|
| 138 |
+
|
| 139 |
+
# import uvicorn
|
| 140 |
+
|
| 141 |
+
# host = CONFIG.video_upscaler.host
|
| 142 |
+
# port = CONFIG.video_upscaler.port
|
| 143 |
+
|
| 144 |
+
# uvicorn.run(app, host=host, port=port)
|
| 145 |
+
|
| 146 |
+
# # class TestRequest:
|
| 147 |
+
# # task_file_path = "/root/workspace/vidaio-subnet/videos/4887282_hd.mp4"
|
| 148 |
+
|
| 149 |
+
# # # Simulate a request
|
| 150 |
+
# # video = TestRequest()
|
| 151 |
+
# # asyncio.run(video_upscaler(UpscaleRequest(task_file_path=video.task_file_path)))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
|
| 155 |
from fastapi import FastAPI, HTTPException
|
| 156 |
from pydantic import BaseModel
|
| 157 |
from pathlib import Path
|
| 158 |
import subprocess
|
| 159 |
from fastapi.responses import JSONResponse
|
| 160 |
import time
|
|
|
|
|
|
|
| 161 |
import re
|
| 162 |
+
import uvicorn
|
| 163 |
+
from vidaio_subnet_core import CONFIG
|
| 164 |
from typing import Optional
|
| 165 |
|
| 166 |
app = FastAPI()
|
| 167 |
|
| 168 |
class UpscaleRequest(BaseModel):
|
| 169 |
+
"""Request model for video upscaling containing the input file path."""
|
| 170 |
task_file_path: str
|
| 171 |
+
|
|
|
|
| 172 |
|
| 173 |
def get_frame_rate(input_file: Path) -> float:
|
| 174 |
"""
|
| 175 |
+
Extract the frame rate of a video using FFmpeg.
|
| 176 |
|
| 177 |
Args:
|
| 178 |
+
input_file (Path): Path to the video file.
|
| 179 |
|
| 180 |
Returns:
|
| 181 |
+
float: Detected frame rate.
|
| 182 |
+
|
| 183 |
+
Raises:
|
| 184 |
+
HTTPException: If frame rate extraction fails.
|
| 185 |
"""
|
| 186 |
frame_rate_command = [
|
| 187 |
"ffmpeg",
|
| 188 |
"-i", str(input_file),
|
| 189 |
+
"-hide_banner",
|
| 190 |
]
|
| 191 |
process = subprocess.run(frame_rate_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 192 |
+
output = process.stderr # Frame rate info is usually in stderr
|
| 193 |
|
|
|
|
| 194 |
match = re.search(r"(\d+(?:\.\d+)?) fps", output)
|
| 195 |
if match:
|
| 196 |
return float(match.group(1))
|
| 197 |
+
|
| 198 |
+
raise HTTPException(status_code=500, detail="Unable to determine frame rate of the video.")
|
| 199 |
|
| 200 |
|
| 201 |
@app.post("/upscale-video")
|
| 202 |
+
def video_upscaler(request: UpscaleRequest) -> dict:
|
| 203 |
"""
|
| 204 |
+
Upscales a video using the video2x tool.
|
| 205 |
|
| 206 |
Args:
|
| 207 |
+
request (UpscaleRequest): Request containing the path to the video file.
|
| 208 |
|
| 209 |
Returns:
|
| 210 |
+
dict: A dictionary with the upscaled video path.
|
| 211 |
+
|
| 212 |
+
Raises:
|
| 213 |
+
HTTPException: If video processing fails at any stage.
|
| 214 |
"""
|
| 215 |
try:
|
| 216 |
input_file = Path(request.task_file_path)
|
| 217 |
|
| 218 |
# Validate input file
|
| 219 |
if not input_file.exists() or not input_file.is_file():
|
| 220 |
+
raise HTTPException(status_code=400, detail="Invalid input file.")
|
| 221 |
|
| 222 |
+
# Get frame rate and calculate duplicate frame duration
|
| 223 |
frame_rate = get_frame_rate(input_file)
|
|
|
|
|
|
|
|
|
|
| 224 |
stop_duration = 2 / frame_rate
|
| 225 |
|
| 226 |
+
# Define output paths
|
| 227 |
output_file_with_extra_frames = input_file.with_name(f"{input_file.stem}_extra_frames.mp4")
|
| 228 |
output_file_upscaled = input_file.with_name(f"4k_{input_file.stem}.mp4")
|
| 229 |
|
| 230 |
+
# Step 1: Duplicate last frame
|
|
|
|
|
|
|
|
|
|
| 231 |
duplicate_last_frame_command = [
|
| 232 |
"ffmpeg",
|
| 233 |
"-i", str(input_file),
|
| 234 |
+
"-vf", f"tpad=stop_mode=clone:stop_duration={stop_duration}",
|
| 235 |
+
"-c:v", "libx264",
|
| 236 |
+
"-crf", "18",
|
| 237 |
+
"-preset", "fast",
|
| 238 |
+
str(output_file_with_extra_frames),
|
| 239 |
]
|
| 240 |
|
| 241 |
+
process = subprocess.run(duplicate_last_frame_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 242 |
+
if process.returncode != 0 or not output_file_with_extra_frames.exists():
|
| 243 |
+
raise HTTPException(status_code=500, detail="Failed to duplicate frames.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
# Step 2: Upscale video using video2x
|
|
|
|
|
|
|
| 246 |
video2x_command = [
|
| 247 |
"video2x",
|
| 248 |
"-i", str(output_file_with_extra_frames),
|
| 249 |
"-o", str(output_file_upscaled),
|
| 250 |
+
"-p", "realesrgan",
|
| 251 |
+
"-s", "2",
|
| 252 |
+
"-c", "libx264",
|
| 253 |
+
"-e", "preset=slow",
|
| 254 |
+
"-e", "crf=24",
|
| 255 |
]
|
| 256 |
+
|
| 257 |
+
process = subprocess.run(video2x_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 258 |
+
if process.returncode != 0 or not output_file_upscaled.exists():
|
| 259 |
+
raise HTTPException(status_code=500, detail="Upscaling failed.")
|
| 260 |
+
|
| 261 |
+
# Cleanup intermediate files
|
| 262 |
+
output_file_with_extra_frames.unlink(missing_ok=True)
|
| 263 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
return {"upscaled_video_path": str(output_file_upscaled)}
|
| 265 |
+
|
| 266 |
except Exception as e:
|
|
|
|
| 267 |
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
| 268 |
|
| 269 |
|
| 270 |
if __name__ == "__main__":
|
| 271 |
+
uvicorn.run(app, host=CONFIG.video_upscaler.host, port=CONFIG.video_upscaler.port)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
services/video_scheduler/video_utils.py
CHANGED
|
@@ -1,3 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
import os
|
| 3 |
import random
|
|
@@ -5,21 +186,39 @@ import time
|
|
| 5 |
from tqdm import tqdm
|
| 6 |
from moviepy.editor import VideoFileClip
|
| 7 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
| 8 |
|
|
|
|
| 9 |
load_dotenv()
|
| 10 |
|
| 11 |
-
def download_trim_downscale_video(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
-
|
| 19 |
api_key = os.getenv("PEXELS_API_KEY")
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
os.makedirs(output_dir, exist_ok=True)
|
| 22 |
-
|
| 23 |
headers = {"Authorization": api_key}
|
| 24 |
url = "https://api.pexels.com/videos/search"
|
| 25 |
params = {
|
|
@@ -27,51 +226,47 @@ def download_trim_downscale_video(clip_duration=1, min_video_len=10, max_video_l
|
|
| 27 |
"per_page": 80,
|
| 28 |
"size": "large"
|
| 29 |
}
|
| 30 |
-
|
| 31 |
try:
|
| 32 |
-
#
|
| 33 |
start_time = time.time()
|
| 34 |
response = requests.get(url, headers=headers, params=params)
|
| 35 |
-
data = response.json()
|
| 36 |
elapsed_time = time.time() - start_time
|
| 37 |
print(f"Time taken to fetch videos: {elapsed_time:.2f} seconds")
|
| 38 |
-
|
|
|
|
| 39 |
if "videos" not in data:
|
| 40 |
print("No videos found or API error")
|
| 41 |
-
return
|
| 42 |
-
|
| 43 |
-
#
|
| 44 |
-
dci4k_videos = [
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
if not dci4k_videos:
|
| 53 |
print("No suitable DCI 4K videos found")
|
| 54 |
-
return
|
| 55 |
-
|
| 56 |
-
#
|
| 57 |
video, video_file = random.choice(dci4k_videos)
|
| 58 |
video_url = video_file["link"]
|
| 59 |
-
|
| 60 |
-
temp_path = f"{output_dir}/{video['id']}_4k_original.mp4" # Downloaded DCI 4K file
|
| 61 |
-
clipped_path = f"{output_dir}/{video['id']}_4k.mp4" # Clipped DCI 4K file
|
| 62 |
-
hd_path = f"{output_dir}/{video['id']}_hd.mp4" # Downscaled HD file
|
| 63 |
-
hevc_path = f"{output_dir}/{video['id']}_hd.hevc" # HEVC file
|
| 64 |
video_id = video['id']
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
|
| 71 |
start_time = time.time()
|
| 72 |
response = requests.get(video_url, stream=True)
|
| 73 |
total_size = int(response.headers.get('content-length', 0))
|
| 74 |
-
|
| 75 |
with open(temp_path, 'wb') as f, tqdm(
|
| 76 |
desc="Downloading",
|
| 77 |
total=total_size,
|
|
@@ -79,87 +274,68 @@ def download_trim_downscale_video(clip_duration=1, min_video_len=10, max_video_l
|
|
| 79 |
unit_scale=True,
|
| 80 |
unit_divisor=1024,
|
| 81 |
) as pbar:
|
| 82 |
-
for
|
| 83 |
-
size = f.write(
|
| 84 |
pbar.update(size)
|
| 85 |
-
|
| 86 |
elapsed_time = time.time() - start_time
|
| 87 |
print(f"Time taken to download video: {elapsed_time:.2f} seconds")
|
| 88 |
-
|
| 89 |
-
#
|
| 90 |
print("\nTrimming video...")
|
| 91 |
start_time = time.time()
|
| 92 |
-
video_clip = VideoFileClip(temp_path)
|
| 93 |
-
|
| 94 |
-
if video_clip.duration <= clip_duration
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
else:
|
| 98 |
-
max_start = video_clip.duration - clip_duration
|
| 99 |
-
start_time_clip = random.uniform(0, max_start)
|
| 100 |
-
print(f"Trimming {clip_duration}s from position {start_time_clip:.1f}s")
|
| 101 |
-
|
| 102 |
-
# Create clipped video
|
| 103 |
clipped_clip = video_clip.subclip(start_time_clip, start_time_clip + min(clip_duration, video_clip.duration))
|
| 104 |
-
clipped_clip.write_videofile(clipped_path, codec='libx264')
|
| 105 |
-
|
| 106 |
elapsed_time = time.time() - start_time
|
| 107 |
print(f"Time taken to clip video: {elapsed_time:.2f} seconds")
|
| 108 |
-
|
| 109 |
-
#
|
| 110 |
print("\nSaving HD version...")
|
| 111 |
start_time = time.time()
|
| 112 |
-
hd_clip = clipped_clip.resize(height=1080)
|
| 113 |
-
hd_clip.write_videofile(hd_path, codec='libx264'
|
| 114 |
-
|
| 115 |
elapsed_time = time.time() - start_time
|
| 116 |
print(f"Time taken to save HD version: {elapsed_time:.2f} seconds")
|
| 117 |
-
|
| 118 |
-
# Step 7: Convert to HEVC
|
| 119 |
-
# print("\nConverting to HEVC...")
|
| 120 |
-
# start_time = time.time()
|
| 121 |
-
# hd_clip.write_videofile(hevc_path, codec='libx265') # Convert to HEVC
|
| 122 |
-
|
| 123 |
-
elapsed_time = time.time() - start_time
|
| 124 |
-
print(f"Time taken to convert to HEVC: {elapsed_time:.2f} seconds")
|
| 125 |
-
|
| 126 |
# Cleanup
|
| 127 |
video_clip.close()
|
| 128 |
clipped_clip.close()
|
| 129 |
hd_clip.close()
|
| 130 |
-
|
| 131 |
-
print(f"\nDone! Saved
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
except Exception as e:
|
| 137 |
print(f"Error: {str(e)}")
|
|
|
|
| 138 |
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
clipped_path = f"{dir_path}/{file_id}_4k.mp4"
|
| 144 |
-
|
| 145 |
-
return clipped_path
|
| 146 |
|
| 147 |
|
| 148 |
-
def delete_videos_with_fileid(file_id, dir_path="videos"):
|
| 149 |
-
|
| 150 |
-
temp_path = f"{dir_path}/{file_id}_4k_original.mp4" # Downloaded 4K file
|
| 151 |
-
clipped_path = f"{dir_path}/{file_id}_4k.mp4" # Clipped 4K file
|
| 152 |
-
hd_path = f"{dir_path}/{file_id}_hd.mp4" # Downscaled HD file
|
| 153 |
-
# hevc_path = f"{dir_path}/{file_id}_hd.hevc" # HEVC file
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
# Delete each file if it exists
|
| 159 |
for file_path in files_to_delete:
|
| 160 |
try:
|
| 161 |
-
if
|
| 162 |
-
|
| 163 |
print(f"Deleted: {file_path}")
|
| 164 |
else:
|
| 165 |
print(f"File not found: {file_path}")
|
|
@@ -168,10 +344,9 @@ def delete_videos_with_fileid(file_id, dir_path="videos"):
|
|
| 168 |
|
| 169 |
|
| 170 |
if __name__ == "__main__":
|
| 171 |
-
PEXELS_API_KEY
|
| 172 |
-
print(PEXELS_API_KEY)
|
| 173 |
CLIP_DURATION = 2
|
| 174 |
-
MIN_VIDEO_LEN = 10
|
| 175 |
-
MAX_VIDEO_LEN = 20
|
| 176 |
-
|
| 177 |
download_trim_downscale_video(CLIP_DURATION, MIN_VIDEO_LEN, MAX_VIDEO_LEN)
|
|
|
|
| 1 |
+
# import requests
|
| 2 |
+
# import os
|
| 3 |
+
# import random
|
| 4 |
+
# import time
|
| 5 |
+
# from tqdm import tqdm
|
| 6 |
+
# from moviepy.editor import VideoFileClip
|
| 7 |
+
# from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
# load_dotenv()
|
| 10 |
+
|
| 11 |
+
# def download_trim_downscale_video(clip_duration=1, min_video_len=10, max_video_len=20, output_dir="videos"):
|
| 12 |
+
# """
|
| 13 |
+
# Download a DCI 4K video and trim to specified duration from a random position.
|
| 14 |
+
# clip_duration: desired clip duration in seconds
|
| 15 |
+
# min_video_len: minimum video length in seconds
|
| 16 |
+
# max_video_len: maximum video length in seconds
|
| 17 |
+
# """
|
| 18 |
+
|
| 19 |
+
# api_key = os.getenv("PEXELS_API_KEY")
|
| 20 |
+
|
| 21 |
+
# os.makedirs(output_dir, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
# headers = {"Authorization": api_key}
|
| 24 |
+
# url = "https://api.pexels.com/videos/search"
|
| 25 |
+
# params = {
|
| 26 |
+
# "query": "nature",
|
| 27 |
+
# "per_page": 80,
|
| 28 |
+
# "size": "large"
|
| 29 |
+
# }
|
| 30 |
+
|
| 31 |
+
# try:
|
| 32 |
+
# # Step 1: Get video list
|
| 33 |
+
# start_time = time.time()
|
| 34 |
+
# response = requests.get(url, headers=headers, params=params)
|
| 35 |
+
# data = response.json()
|
| 36 |
+
# elapsed_time = time.time() - start_time
|
| 37 |
+
# print(f"Time taken to fetch videos: {elapsed_time:.2f} seconds")
|
| 38 |
+
|
| 39 |
+
# if "videos" not in data:
|
| 40 |
+
# print("No videos found or API error")
|
| 41 |
+
# return
|
| 42 |
+
|
| 43 |
+
# # Step 2: Filter DCI 4K videos based on length
|
| 44 |
+
# dci4k_videos = []
|
| 45 |
+
# for video in data["videos"]:
|
| 46 |
+
# video_length = video["duration"]
|
| 47 |
+
# # Filter for DCI 4K videos (4096x2160)
|
| 48 |
+
# dci4k_files = [f for f in video["video_files"] if f["width"] == 4096 and f["height"] == 2160]
|
| 49 |
+
# if dci4k_files and min_video_len <= video_length <= max_video_len:
|
| 50 |
+
# dci4k_videos.append((video, dci4k_files[0]))
|
| 51 |
+
|
| 52 |
+
# if not dci4k_videos:
|
| 53 |
+
# print("No suitable DCI 4K videos found")
|
| 54 |
+
# return
|
| 55 |
+
|
| 56 |
+
# # Step 3: Randomly select one video
|
| 57 |
+
# video, video_file = random.choice(dci4k_videos)
|
| 58 |
+
# video_url = video_file["link"]
|
| 59 |
+
|
| 60 |
+
# temp_path = f"{output_dir}/{video['id']}_4k_original.mp4" # Downloaded DCI 4K file
|
| 61 |
+
# clipped_path = f"{output_dir}/{video['id']}_4k.mp4" # Clipped DCI 4K file
|
| 62 |
+
# hd_path = f"{output_dir}/{video['id']}_hd.mp4" # Downscaled HD file
|
| 63 |
+
# hevc_path = f"{output_dir}/{video['id']}_hd.hevc" # HEVC file
|
| 64 |
+
# video_id = video['id']
|
| 65 |
+
|
| 66 |
+
# # Step 4: Download video
|
| 67 |
+
# print(f"\nDownloading DCI 4K video...")
|
| 68 |
+
# print(f"Resolution: {video_file['width']}x{video_file['height']}")
|
| 69 |
+
# print(f"Original duration: {video['duration']}s")
|
| 70 |
+
|
| 71 |
+
# start_time = time.time()
|
| 72 |
+
# response = requests.get(video_url, stream=True)
|
| 73 |
+
# total_size = int(response.headers.get('content-length', 0))
|
| 74 |
+
|
| 75 |
+
# with open(temp_path, 'wb') as f, tqdm(
|
| 76 |
+
# desc="Downloading",
|
| 77 |
+
# total=total_size,
|
| 78 |
+
# unit='iB',
|
| 79 |
+
# unit_scale=True,
|
| 80 |
+
# unit_divisor=1024,
|
| 81 |
+
# ) as pbar:
|
| 82 |
+
# for data in response.iter_content(chunk_size=1024):
|
| 83 |
+
# size = f.write(data)
|
| 84 |
+
# pbar.update(size)
|
| 85 |
+
|
| 86 |
+
# elapsed_time = time.time() - start_time
|
| 87 |
+
# print(f"Time taken to download video: {elapsed_time:.2f} seconds")
|
| 88 |
+
|
| 89 |
+
# # Step 5: Trim video
|
| 90 |
+
# print("\nTrimming video...")
|
| 91 |
+
# start_time = time.time()
|
| 92 |
+
# video_clip = VideoFileClip(temp_path)
|
| 93 |
+
|
| 94 |
+
# if video_clip.duration <= clip_duration:
|
| 95 |
+
# print(f"Video is shorter than {clip_duration}s, keeping full length")
|
| 96 |
+
# start_time_clip = 0
|
| 97 |
+
# else:
|
| 98 |
+
# max_start = video_clip.duration - clip_duration
|
| 99 |
+
# start_time_clip = random.uniform(0, max_start)
|
| 100 |
+
# print(f"Trimming {clip_duration}s from position {start_time_clip:.1f}s")
|
| 101 |
+
|
| 102 |
+
# # Create clipped video
|
| 103 |
+
# clipped_clip = video_clip.subclip(start_time_clip, start_time_clip + min(clip_duration, video_clip.duration))
|
| 104 |
+
# clipped_clip.write_videofile(clipped_path, codec='libx264')
|
| 105 |
+
|
| 106 |
+
# elapsed_time = time.time() - start_time
|
| 107 |
+
# print(f"Time taken to clip video: {elapsed_time:.2f} seconds")
|
| 108 |
+
|
| 109 |
+
# # Step 6: Downscale to HD and save as .mp4 using the clipped video
|
| 110 |
+
# print("\nSaving HD version...")
|
| 111 |
+
# start_time = time.time()
|
| 112 |
+
# hd_clip = clipped_clip.resize(height=1080) # Resize to HD (1080p) using the clipped video
|
| 113 |
+
# hd_clip.write_videofile(hd_path, codec='libx264') # Save as HD .mp4
|
| 114 |
+
|
| 115 |
+
# elapsed_time = time.time() - start_time
|
| 116 |
+
# print(f"Time taken to save HD version: {elapsed_time:.2f} seconds")
|
| 117 |
+
|
| 118 |
+
# # Step 7: Convert to HEVC
|
| 119 |
+
# # print("\nConverting to HEVC...")
|
| 120 |
+
# # start_time = time.time()
|
| 121 |
+
# # hd_clip.write_videofile(hevc_path, codec='libx265') # Convert to HEVC
|
| 122 |
+
|
| 123 |
+
# elapsed_time = time.time() - start_time
|
| 124 |
+
# print(f"Time taken to convert to HEVC: {elapsed_time:.2f} seconds")
|
| 125 |
+
|
| 126 |
+
# # Cleanup
|
| 127 |
+
# video_clip.close()
|
| 128 |
+
# clipped_clip.close()
|
| 129 |
+
# hd_clip.close()
|
| 130 |
+
|
| 131 |
+
# print(f"\nDone! Saved to: {temp_path}, {clipped_path}, {hd_path}, and {hevc_path}")
|
| 132 |
+
|
| 133 |
+
# # return hevc_path, video_id
|
| 134 |
+
# return hd_path, video_id
|
| 135 |
+
|
| 136 |
+
# except Exception as e:
|
| 137 |
+
# print(f"Error: {str(e)}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# def get_4k_vide_path(file_id, dir_path="videos"):
|
| 142 |
+
|
| 143 |
+
# clipped_path = f"{dir_path}/{file_id}_4k.mp4"
|
| 144 |
+
|
| 145 |
+
# return clipped_path
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# def delete_videos_with_fileid(file_id, dir_path="videos"):
|
| 149 |
+
# # Define file paths
|
| 150 |
+
# temp_path = f"{dir_path}/{file_id}_4k_original.mp4" # Downloaded 4K file
|
| 151 |
+
# clipped_path = f"{dir_path}/{file_id}_4k.mp4" # Clipped 4K file
|
| 152 |
+
# hd_path = f"{dir_path}/{file_id}_hd.mp4" # Downscaled HD file
|
| 153 |
+
# # hevc_path = f"{dir_path}/{file_id}_hd.hevc" # HEVC file
|
| 154 |
+
|
| 155 |
+
# # List of files to delete
|
| 156 |
+
# files_to_delete = [temp_path, clipped_path, hd_path]
|
| 157 |
+
|
| 158 |
+
# # Delete each file if it exists
|
| 159 |
+
# for file_path in files_to_delete:
|
| 160 |
+
# try:
|
| 161 |
+
# if os.path.exists(file_path):
|
| 162 |
+
# os.remove(file_path)
|
| 163 |
+
# print(f"Deleted: {file_path}")
|
| 164 |
+
# else:
|
| 165 |
+
# print(f"File not found: {file_path}")
|
| 166 |
+
# except Exception as e:
|
| 167 |
+
# print(f"Error deleting {file_path}: {e}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# if __name__ == "__main__":
|
| 171 |
+
# PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
| 172 |
+
# print(PEXELS_API_KEY)
|
| 173 |
+
# CLIP_DURATION = 2
|
| 174 |
+
# MIN_VIDEO_LEN = 10 # Set minimum video length in seconds
|
| 175 |
+
# MAX_VIDEO_LEN = 20 # Set maximum video length in seconds
|
| 176 |
+
|
| 177 |
+
# download_trim_downscale_video(CLIP_DURATION, MIN_VIDEO_LEN, MAX_VIDEO_LEN)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
|
| 182 |
import requests
|
| 183 |
import os
|
| 184 |
import random
|
|
|
|
| 186 |
from tqdm import tqdm
|
| 187 |
from moviepy.editor import VideoFileClip
|
| 188 |
from dotenv import load_dotenv
|
| 189 |
+
from pathlib import Path
|
| 190 |
+
from typing import Optional, Tuple
|
| 191 |
|
| 192 |
+
# Load environment variables
|
| 193 |
load_dotenv()
|
| 194 |
|
| 195 |
+
def download_trim_downscale_video(
|
| 196 |
+
clip_duration: int = 1,
|
| 197 |
+
min_video_len: int = 10,
|
| 198 |
+
max_video_len: int = 20,
|
| 199 |
+
output_dir: str = "videos"
|
| 200 |
+
) -> Optional[Tuple[str, int]]:
|
| 201 |
"""
|
| 202 |
+
Downloads a DCI 4K video from Pexels, trims it to the specified duration,
|
| 203 |
+
and downscales it to HD resolution.
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
clip_duration (int): Desired clip duration in seconds.
|
| 207 |
+
min_video_len (int): Minimum video length in seconds.
|
| 208 |
+
max_video_len (int): Maximum video length in seconds.
|
| 209 |
+
output_dir (str): Directory to save the processed videos.
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
Optional[Tuple[str, int]]: Path to the HD video and the video ID, or None on failure.
|
| 213 |
"""
|
| 214 |
+
|
| 215 |
api_key = os.getenv("PEXELS_API_KEY")
|
| 216 |
+
if not api_key:
|
| 217 |
+
print("PEXELS_API_KEY is missing in the environment variables.")
|
| 218 |
+
return None
|
| 219 |
+
|
| 220 |
os.makedirs(output_dir, exist_ok=True)
|
| 221 |
+
|
| 222 |
headers = {"Authorization": api_key}
|
| 223 |
url = "https://api.pexels.com/videos/search"
|
| 224 |
params = {
|
|
|
|
| 226 |
"per_page": 80,
|
| 227 |
"size": "large"
|
| 228 |
}
|
| 229 |
+
|
| 230 |
try:
|
| 231 |
+
# Fetch video list
|
| 232 |
start_time = time.time()
|
| 233 |
response = requests.get(url, headers=headers, params=params)
|
|
|
|
| 234 |
elapsed_time = time.time() - start_time
|
| 235 |
print(f"Time taken to fetch videos: {elapsed_time:.2f} seconds")
|
| 236 |
+
|
| 237 |
+
data = response.json()
|
| 238 |
if "videos" not in data:
|
| 239 |
print("No videos found or API error")
|
| 240 |
+
return None
|
| 241 |
+
|
| 242 |
+
# Filter DCI 4K videos based on length
|
| 243 |
+
dci4k_videos = [
|
| 244 |
+
(video, video_file)
|
| 245 |
+
for video in data["videos"]
|
| 246 |
+
for video_file in video["video_files"]
|
| 247 |
+
if video_file["width"] == 4096 and video_file["height"] == 2160 and min_video_len <= video["duration"] <= max_video_len
|
| 248 |
+
]
|
| 249 |
+
|
|
|
|
| 250 |
if not dci4k_videos:
|
| 251 |
print("No suitable DCI 4K videos found")
|
| 252 |
+
return None
|
| 253 |
+
|
| 254 |
+
# Select a random video
|
| 255 |
video, video_file = random.choice(dci4k_videos)
|
| 256 |
video_url = video_file["link"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
video_id = video['id']
|
| 258 |
+
|
| 259 |
+
temp_path = Path(output_dir) / f"{video_id}_4k_original.mp4"
|
| 260 |
+
clipped_path = Path(output_dir) / f"{video_id}_4k.mp4"
|
| 261 |
+
hd_path = Path(output_dir) / f"{video_id}_hd.mp4"
|
| 262 |
+
|
| 263 |
+
# Download video
|
| 264 |
+
print(f"\nDownloading DCI 4K video (Resolution: {video_file['width']}x{video_file['height']}, Duration: {video['duration']}s)")
|
| 265 |
|
| 266 |
start_time = time.time()
|
| 267 |
response = requests.get(video_url, stream=True)
|
| 268 |
total_size = int(response.headers.get('content-length', 0))
|
| 269 |
+
|
| 270 |
with open(temp_path, 'wb') as f, tqdm(
|
| 271 |
desc="Downloading",
|
| 272 |
total=total_size,
|
|
|
|
| 274 |
unit_scale=True,
|
| 275 |
unit_divisor=1024,
|
| 276 |
) as pbar:
|
| 277 |
+
for chunk in response.iter_content(chunk_size=1024):
|
| 278 |
+
size = f.write(chunk)
|
| 279 |
pbar.update(size)
|
| 280 |
+
|
| 281 |
elapsed_time = time.time() - start_time
|
| 282 |
print(f"Time taken to download video: {elapsed_time:.2f} seconds")
|
| 283 |
+
|
| 284 |
+
# Trim video
|
| 285 |
print("\nTrimming video...")
|
| 286 |
start_time = time.time()
|
| 287 |
+
video_clip = VideoFileClip(str(temp_path))
|
| 288 |
+
|
| 289 |
+
start_time_clip = 0 if video_clip.duration <= clip_duration else random.uniform(0, video_clip.duration - clip_duration)
|
| 290 |
+
print(f"Trimming {clip_duration}s from position {start_time_clip:.1f}s")
|
| 291 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
clipped_clip = video_clip.subclip(start_time_clip, start_time_clip + min(clip_duration, video_clip.duration))
|
| 293 |
+
clipped_clip.write_videofile(str(clipped_path), codec='libx264', verbose=False, logger=None)
|
| 294 |
+
|
| 295 |
elapsed_time = time.time() - start_time
|
| 296 |
print(f"Time taken to clip video: {elapsed_time:.2f} seconds")
|
| 297 |
+
|
| 298 |
+
# Downscale to HD
|
| 299 |
print("\nSaving HD version...")
|
| 300 |
start_time = time.time()
|
| 301 |
+
hd_clip = clipped_clip.resize(height=1080)
|
| 302 |
+
hd_clip.write_videofile(str(hd_path), codec='libx264', verbose=False, logger=None)
|
| 303 |
+
|
| 304 |
elapsed_time = time.time() - start_time
|
| 305 |
print(f"Time taken to save HD version: {elapsed_time:.2f} seconds")
|
| 306 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
# Cleanup
|
| 308 |
video_clip.close()
|
| 309 |
clipped_clip.close()
|
| 310 |
hd_clip.close()
|
| 311 |
+
|
| 312 |
+
print(f"\nDone! Saved files:\n- {clipped_path}\n- {hd_path}")
|
| 313 |
+
|
| 314 |
+
return str(hd_path), video_id
|
| 315 |
+
|
|
|
|
| 316 |
except Exception as e:
|
| 317 |
print(f"Error: {str(e)}")
|
| 318 |
+
return None
|
| 319 |
|
| 320 |
|
| 321 |
+
def get_4k_video_path(file_id: int, dir_path: str = "videos") -> str:
|
| 322 |
+
"""Returns the path of the clipped 4K video based on the file ID."""
|
| 323 |
+
return str(Path(dir_path) / f"{file_id}_4k.mp4")
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
|
| 326 |
+
def delete_videos_with_fileid(file_id: int, dir_path: str = "videos") -> None:
|
| 327 |
+
"""Deletes all video files associated with the given file ID."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
+
files_to_delete = [
|
| 330 |
+
Path(dir_path) / f"{file_id}_4k_original.mp4",
|
| 331 |
+
Path(dir_path) / f"{file_id}_4k.mp4",
|
| 332 |
+
Path(dir_path) / f"{file_id}_hd.mp4",
|
| 333 |
+
]
|
| 334 |
|
|
|
|
| 335 |
for file_path in files_to_delete:
|
| 336 |
try:
|
| 337 |
+
if file_path.exists():
|
| 338 |
+
file_path.unlink()
|
| 339 |
print(f"Deleted: {file_path}")
|
| 340 |
else:
|
| 341 |
print(f"File not found: {file_path}")
|
|
|
|
| 344 |
|
| 345 |
|
| 346 |
if __name__ == "__main__":
|
| 347 |
+
print(f"PEXELS_API_KEY: {os.getenv('PEXELS_API_KEY')}")
|
|
|
|
| 348 |
CLIP_DURATION = 2
|
| 349 |
+
MIN_VIDEO_LEN = 10
|
| 350 |
+
MAX_VIDEO_LEN = 20
|
| 351 |
+
|
| 352 |
download_trim_downscale_video(CLIP_DURATION, MIN_VIDEO_LEN, MAX_VIDEO_LEN)
|
services/video_scheduler/worker.py
CHANGED
|
@@ -1,9 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import time
|
| 2 |
import random
|
| 3 |
-
from typing import List, Dict, Optional
|
| 4 |
-
import httpx
|
| 5 |
import asyncio
|
| 6 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from redis_utils import (
|
| 8 |
get_redis_connection,
|
| 9 |
get_organic_queue_size,
|
|
@@ -13,93 +227,56 @@ from redis_utils import (
|
|
| 13 |
from video_utils import download_trim_downscale_video
|
| 14 |
from services.google_drive.google_drive_manager import GoogleDriveManager
|
| 15 |
from vidaio_subnet_core import CONFIG
|
| 16 |
-
from loguru import logger
|
| 17 |
-
import yaml
|
| 18 |
-
from dotenv import load_dotenv
|
| 19 |
from vidaio_subnet_core.utilities.minio_client import minio_client
|
| 20 |
-
|
| 21 |
-
|
| 22 |
load_dotenv()
|
| 23 |
|
| 24 |
-
def clear_queues(redis_conn):
|
| 25 |
"""Clear both organic and synthetic queues before starting."""
|
| 26 |
logger.info("Clearing queues")
|
| 27 |
redis_conn.delete(CONFIG.redis.organic_queue_key)
|
| 28 |
redis_conn.delete(CONFIG.redis.synthetic_queue_key)
|
| 29 |
|
| 30 |
-
def read_synthetic_urls(config_path: str) ->
|
|
|
|
| 31 |
with open(config_path, "r") as file:
|
| 32 |
config = yaml.safe_load(file)
|
| 33 |
return config.get("synthetic_urls", [])
|
| 34 |
|
| 35 |
-
async def get_synthetic_urls_with_retry(
|
| 36 |
-
|
| 37 |
-
max_retries: int = 2,
|
| 38 |
-
initial_delay: float = 5.0,
|
| 39 |
-
num_needed: int = 2
|
| 40 |
-
) -> Optional[List[str]]:
|
| 41 |
-
"""
|
| 42 |
-
Attempt to fetch synthetic request urls from the API with exponential backoff retry.
|
| 43 |
-
|
| 44 |
-
Args:
|
| 45 |
-
hotkey (str): The validator's hotkey
|
| 46 |
-
max_retries (int): Maximum number of retry attempts
|
| 47 |
-
initial_delay (float): Initial delay in seconds between retries
|
| 48 |
-
num_needed (int): Number of synthetic urls needed
|
| 49 |
-
|
| 50 |
-
Returns:
|
| 51 |
-
Optional[List[str]]: List of video urls if successful, None otherwise
|
| 52 |
-
"""
|
| 53 |
for attempt in range(max_retries + 1):
|
| 54 |
try:
|
| 55 |
-
logger.info(f"Fetching synthetic
|
| 56 |
fetched_urls = await get_synthetic_urls(hotkey, num_needed)
|
| 57 |
|
| 58 |
if fetched_urls and len(fetched_urls) == num_needed:
|
| 59 |
-
logger.info(f"Successfully fetched {len(fetched_urls)}
|
| 60 |
return fetched_urls
|
| 61 |
else:
|
| 62 |
-
logger.warning(f"Insufficient
|
| 63 |
-
|
| 64 |
except Exception as e:
|
| 65 |
-
logger.error(f"Error fetching synthetic
|
| 66 |
|
| 67 |
if attempt < max_retries:
|
| 68 |
-
delay = initial_delay * (2 ** attempt)
|
| 69 |
logger.info(f"Retrying in {delay:.2f} seconds...")
|
| 70 |
await asyncio.sleep(delay)
|
| 71 |
|
| 72 |
-
logger.error(
|
| 73 |
return None
|
| 74 |
|
| 75 |
async def get_synthetic_urls(hotkey: str, num_needed: int) -> Optional[List[str]]:
|
| 76 |
-
"""
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
Args:
|
| 80 |
-
hotkey (str): The validator's hotkey
|
| 81 |
-
num_needed (int): Number of synthetic urls needed
|
| 82 |
-
|
| 83 |
-
Returns:
|
| 84 |
-
Optional[List[str]]: List of video urls if successful, None otherwise
|
| 85 |
-
|
| 86 |
-
Raises:
|
| 87 |
-
httpx.HTTPError: If the API request fails
|
| 88 |
-
"""
|
| 89 |
-
vidaio_api_endpoint = os.getenv("VIDAIO_API_ENDPOINT")
|
| 90 |
-
api_url = f"{vidaio_api_endpoint}/api/synthetic_urls"
|
| 91 |
-
params = {
|
| 92 |
-
"validator_hotkey": hotkey,
|
| 93 |
-
"num_needed": num_needed
|
| 94 |
-
}
|
| 95 |
|
| 96 |
try:
|
| 97 |
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 98 |
response = await client.get(api_url, params=params)
|
| 99 |
response.raise_for_status()
|
| 100 |
-
|
| 101 |
data = response.json()
|
| 102 |
-
logger.debug(f"API response: {data}")
|
| 103 |
|
| 104 |
if not isinstance(data, dict) or "synthetic_urls" not in data:
|
| 105 |
logger.error(f"Unexpected API response format: {data}")
|
|
@@ -107,46 +284,31 @@ async def get_synthetic_urls(hotkey: str, num_needed: int) -> Optional[List[str]
|
|
| 107 |
|
| 108 |
urls = data["synthetic_urls"]
|
| 109 |
if not isinstance(urls, list):
|
| 110 |
-
logger.error(f"Invalid
|
| 111 |
return None
|
| 112 |
-
|
| 113 |
-
return urls
|
| 114 |
|
|
|
|
|
|
|
|
|
|
| 115 |
except httpx.TimeoutException:
|
| 116 |
logger.error("API request timed out")
|
| 117 |
-
return None
|
| 118 |
-
except httpx.HTTPError as e:
|
| 119 |
-
logger.error(f"HTTP Error {e.response.status_code}: {e.response.text if hasattr(e, 'response') else 'No response'}")
|
| 120 |
-
return None
|
| 121 |
except Exception as e:
|
| 122 |
-
logger.error(f"Unexpected error fetching synthetic
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
from typing import List, Dict
|
| 126 |
|
| 127 |
async def get_synthetic_requests_urls(num_needed: int) -> List[Dict[str, str]]:
|
| 128 |
-
"""
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
Args:
|
| 132 |
-
num_needed (int): The number of synthetic URLs needed.
|
| 133 |
-
|
| 134 |
-
Returns:
|
| 135 |
-
List[Dict[str, str]]: A list of dictionaries mapping file IDs to sharing links.
|
| 136 |
-
"""
|
| 137 |
-
uploaded_video_chunks: List[Dict[str, str]] = []
|
| 138 |
-
remaining_count: int = num_needed
|
| 139 |
|
| 140 |
while remaining_count > 0:
|
| 141 |
-
|
| 142 |
-
# Download and trim video
|
| 143 |
challenge_local_path, video_id = download_trim_downscale_video(
|
| 144 |
clip_duration=CONFIG.video_scheduler.clip_duration,
|
| 145 |
min_video_len=CONFIG.video_scheduler.min_video_len,
|
| 146 |
max_video_len=CONFIG.video_scheduler.max_video_len
|
| 147 |
)
|
| 148 |
|
| 149 |
-
if
|
| 150 |
logger.info("Failed to download and trim video. Retrying...")
|
| 151 |
continue
|
| 152 |
|
|
@@ -156,50 +318,43 @@ async def get_synthetic_requests_urls(num_needed: int) -> List[Dict[str, str]]:
|
|
| 156 |
await minio_client.upload_file(object_name, challenge_local_path)
|
| 157 |
sharing_link = await minio_client.get_presigned_url(object_name)
|
| 158 |
|
| 159 |
-
if
|
| 160 |
logger.info("Upload failed. Retrying...")
|
| 161 |
continue
|
| 162 |
|
| 163 |
-
# Append result to the list
|
| 164 |
uploaded_video_chunks.append({
|
| 165 |
"video_id": video_id,
|
| 166 |
"uploaded_object_name": object_name,
|
| 167 |
"sharing_link": sharing_link
|
| 168 |
})
|
| 169 |
-
|
| 170 |
remaining_count -= 1
|
| 171 |
|
| 172 |
return uploaded_video_chunks
|
| 173 |
|
| 174 |
-
|
| 175 |
async def main():
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
clear_queues(
|
| 180 |
|
| 181 |
while True:
|
| 182 |
-
organic_size = get_organic_queue_size(
|
| 183 |
-
synthetic_size = get_synthetic_queue_size(
|
| 184 |
total_size = organic_size + synthetic_size
|
| 185 |
-
|
| 186 |
-
logger.info(f"
|
| 187 |
-
|
| 188 |
-
|
| 189 |
threshold = CONFIG.video_scheduler.refill_threshold
|
| 190 |
fill_target = CONFIG.video_scheduler.refill_target
|
| 191 |
|
| 192 |
if total_size < threshold:
|
| 193 |
-
# Fill with synthetic chunks
|
| 194 |
needed = fill_target - total_size
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
push_synthetic_chunks(r, needed_urls)
|
| 199 |
-
|
| 200 |
-
# Sleep for some time, e.g. 5 seconds, then re-check
|
| 201 |
-
time.sleep(20)
|
| 202 |
|
|
|
|
| 203 |
|
| 204 |
if __name__ == "__main__":
|
| 205 |
asyncio.run(main())
|
|
|
|
| 1 |
+
# import time
|
| 2 |
+
# import random
|
| 3 |
+
# from typing import List, Dict, Optional
|
| 4 |
+
# import httpx
|
| 5 |
+
# import asyncio
|
| 6 |
+
# import os
|
| 7 |
+
# from redis_utils import (
|
| 8 |
+
# get_redis_connection,
|
| 9 |
+
# get_organic_queue_size,
|
| 10 |
+
# get_synthetic_queue_size,
|
| 11 |
+
# push_synthetic_chunks,
|
| 12 |
+
# )
|
| 13 |
+
# from video_utils import download_trim_downscale_video
|
| 14 |
+
# from services.google_drive.google_drive_manager import GoogleDriveManager
|
| 15 |
+
# from vidaio_subnet_core import CONFIG
|
| 16 |
+
# from loguru import logger
|
| 17 |
+
# import yaml
|
| 18 |
+
# from dotenv import load_dotenv
|
| 19 |
+
# from vidaio_subnet_core.utilities.minio_client import minio_client
|
| 20 |
+
# import uuid
|
| 21 |
+
# from loguru import logger
|
| 22 |
+
# load_dotenv()
|
| 23 |
+
|
| 24 |
+
# def clear_queues(redis_conn):
|
| 25 |
+
# """Clear both organic and synthetic queues before starting."""
|
| 26 |
+
# logger.info("Clearing queues")
|
| 27 |
+
# redis_conn.delete(CONFIG.redis.organic_queue_key)
|
| 28 |
+
# redis_conn.delete(CONFIG.redis.synthetic_queue_key)
|
| 29 |
+
|
| 30 |
+
# def read_synthetic_urls(config_path: str) -> list[str]:
|
| 31 |
+
# with open(config_path, "r") as file:
|
| 32 |
+
# config = yaml.safe_load(file)
|
| 33 |
+
# return config.get("synthetic_urls", [])
|
| 34 |
+
|
| 35 |
+
# async def get_synthetic_urls_with_retry(
|
| 36 |
+
# hotkey: str,
|
| 37 |
+
# max_retries: int = 2,
|
| 38 |
+
# initial_delay: float = 5.0,
|
| 39 |
+
# num_needed: int = 2
|
| 40 |
+
# ) -> Optional[List[str]]:
|
| 41 |
+
# """
|
| 42 |
+
# Attempt to fetch synthetic request urls from the API with exponential backoff retry.
|
| 43 |
+
|
| 44 |
+
# Args:
|
| 45 |
+
# hotkey (str): The validator's hotkey
|
| 46 |
+
# max_retries (int): Maximum number of retry attempts
|
| 47 |
+
# initial_delay (float): Initial delay in seconds between retries
|
| 48 |
+
# num_needed (int): Number of synthetic urls needed
|
| 49 |
+
|
| 50 |
+
# Returns:
|
| 51 |
+
# Optional[List[str]]: List of video urls if successful, None otherwise
|
| 52 |
+
# """
|
| 53 |
+
# for attempt in range(max_retries + 1):
|
| 54 |
+
# try:
|
| 55 |
+
# logger.info(f"Fetching synthetic urls from API (Attempt {attempt + 1}/{max_retries + 1})...")
|
| 56 |
+
# fetched_urls = await get_synthetic_urls(hotkey, num_needed)
|
| 57 |
+
|
| 58 |
+
# if fetched_urls and len(fetched_urls) == num_needed:
|
| 59 |
+
# logger.info(f"Successfully fetched {len(fetched_urls)} urls")
|
| 60 |
+
# return fetched_urls
|
| 61 |
+
# else:
|
| 62 |
+
# logger.warning(f"Insufficient urls returned: got {len(fetched_urls) if fetched_urls else 0}, needed {num_needed}")
|
| 63 |
+
|
| 64 |
+
# except Exception as e:
|
| 65 |
+
# logger.error(f"Error fetching synthetic urls: {str(e)}", exc_info=True)
|
| 66 |
+
|
| 67 |
+
# if attempt < max_retries:
|
| 68 |
+
# delay = initial_delay * (2 ** attempt) # Exponential backoff
|
| 69 |
+
# logger.info(f"Retrying in {delay:.2f} seconds...")
|
| 70 |
+
# await asyncio.sleep(delay)
|
| 71 |
+
|
| 72 |
+
# logger.error(f"Failed to fetch synthetic urls after {max_retries + 1} attempts")
|
| 73 |
+
# return None
|
| 74 |
+
|
| 75 |
+
# async def get_synthetic_urls(hotkey: str, num_needed: int) -> Optional[List[str]]:
|
| 76 |
+
# """
|
| 77 |
+
# Fetch synthetic request urls from the API.
|
| 78 |
+
|
| 79 |
+
# Args:
|
| 80 |
+
# hotkey (str): The validator's hotkey
|
| 81 |
+
# num_needed (int): Number of synthetic urls needed
|
| 82 |
+
|
| 83 |
+
# Returns:
|
| 84 |
+
# Optional[List[str]]: List of video urls if successful, None otherwise
|
| 85 |
+
|
| 86 |
+
# Raises:
|
| 87 |
+
# httpx.HTTPError: If the API request fails
|
| 88 |
+
# """
|
| 89 |
+
# vidaio_api_endpoint = os.getenv("VIDAIO_API_ENDPOINT")
|
| 90 |
+
# api_url = f"{vidaio_api_endpoint}/api/synthetic_urls"
|
| 91 |
+
# params = {
|
| 92 |
+
# "validator_hotkey": hotkey,
|
| 93 |
+
# "num_needed": num_needed
|
| 94 |
+
# }
|
| 95 |
+
|
| 96 |
+
# try:
|
| 97 |
+
# async with httpx.AsyncClient(timeout=30.0) as client:
|
| 98 |
+
# response = await client.get(api_url, params=params)
|
| 99 |
+
# response.raise_for_status()
|
| 100 |
+
|
| 101 |
+
# data = response.json()
|
| 102 |
+
# logger.debug(f"API response: {data}")
|
| 103 |
+
|
| 104 |
+
# if not isinstance(data, dict) or "synthetic_urls" not in data:
|
| 105 |
+
# logger.error(f"Unexpected API response format: {data}")
|
| 106 |
+
# return None
|
| 107 |
+
|
| 108 |
+
# urls = data["synthetic_urls"]
|
| 109 |
+
# if not isinstance(urls, list):
|
| 110 |
+
# logger.error(f"Invalid urls format in response: {urls}")
|
| 111 |
+
# return None
|
| 112 |
+
|
| 113 |
+
# return urls
|
| 114 |
+
|
| 115 |
+
# except httpx.TimeoutException:
|
| 116 |
+
# logger.error("API request timed out")
|
| 117 |
+
# return None
|
| 118 |
+
# except httpx.HTTPError as e:
|
| 119 |
+
# logger.error(f"HTTP Error {e.response.status_code}: {e.response.text if hasattr(e, 'response') else 'No response'}")
|
| 120 |
+
# return None
|
| 121 |
+
# except Exception as e:
|
| 122 |
+
# logger.error(f"Unexpected error fetching synthetic urls: {str(e)}", exc_info=True)
|
| 123 |
+
# return None
|
| 124 |
+
|
| 125 |
+
# from typing import List, Dict
|
| 126 |
+
|
| 127 |
+
# async def get_synthetic_requests_urls(num_needed: int) -> List[Dict[str, str]]:
|
| 128 |
+
# """
|
| 129 |
+
# Generate synthetic Google Drive URLs by uploading trimmed videos.
|
| 130 |
+
|
| 131 |
+
# Args:
|
| 132 |
+
# num_needed (int): The number of synthetic URLs needed.
|
| 133 |
+
|
| 134 |
+
# Returns:
|
| 135 |
+
# List[Dict[str, str]]: A list of dictionaries mapping file IDs to sharing links.
|
| 136 |
+
# """
|
| 137 |
+
# uploaded_video_chunks: List[Dict[str, str]] = []
|
| 138 |
+
# remaining_count: int = num_needed
|
| 139 |
+
|
| 140 |
+
# while remaining_count > 0:
|
| 141 |
+
|
| 142 |
+
# # Download and trim video
|
| 143 |
+
# challenge_local_path, video_id = download_trim_downscale_video(
|
| 144 |
+
# clip_duration=CONFIG.video_scheduler.clip_duration,
|
| 145 |
+
# min_video_len=CONFIG.video_scheduler.min_video_len,
|
| 146 |
+
# max_video_len=CONFIG.video_scheduler.max_video_len
|
| 147 |
+
# )
|
| 148 |
+
|
| 149 |
+
# if challenge_local_path is None:
|
| 150 |
+
# logger.info("Failed to download and trim video. Retrying...")
|
| 151 |
+
# continue
|
| 152 |
+
|
| 153 |
+
# uploaded_file_id = uuid.uuid4()
|
| 154 |
+
# object_name = f"{uploaded_file_id}.mp4"
|
| 155 |
+
|
| 156 |
+
# await minio_client.upload_file(object_name, challenge_local_path)
|
| 157 |
+
# sharing_link = await minio_client.get_presigned_url(object_name)
|
| 158 |
+
|
| 159 |
+
# if uploaded_file_id is None or sharing_link is None:
|
| 160 |
+
# logger.info("Upload failed. Retrying...")
|
| 161 |
+
# continue
|
| 162 |
+
|
| 163 |
+
# # Append result to the list
|
| 164 |
+
# uploaded_video_chunks.append({
|
| 165 |
+
# "video_id": video_id,
|
| 166 |
+
# "uploaded_object_name": object_name,
|
| 167 |
+
# "sharing_link": sharing_link
|
| 168 |
+
# })
|
| 169 |
+
|
| 170 |
+
# remaining_count -= 1
|
| 171 |
+
|
| 172 |
+
# return uploaded_video_chunks
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# async def main():
|
| 176 |
+
# logger.info("starting")
|
| 177 |
+
# r = get_redis_connection()
|
| 178 |
+
# logger.info("Starting worker")
|
| 179 |
+
# clear_queues(r)
|
| 180 |
+
|
| 181 |
+
# while True:
|
| 182 |
+
# organic_size = get_organic_queue_size(r)
|
| 183 |
+
# synthetic_size = get_synthetic_queue_size(r)
|
| 184 |
+
# total_size = organic_size + synthetic_size
|
| 185 |
+
# logger.info(f"The organic queue size is {organic_size}")
|
| 186 |
+
# logger.info(f"The synthetic queue size is {synthetic_size}")
|
| 187 |
+
# # If total queue is below some threshold, push synthetic chunks
|
| 188 |
+
# # Adjust threshold as needed. Example: If queue < 500, fill it up to 1000 with synthetic.
|
| 189 |
+
# threshold = CONFIG.video_scheduler.refill_threshold
|
| 190 |
+
# fill_target = CONFIG.video_scheduler.refill_target
|
| 191 |
+
|
| 192 |
+
# if total_size < threshold:
|
| 193 |
+
# # Fill with synthetic chunks
|
| 194 |
+
# needed = fill_target - total_size
|
| 195 |
+
# # needed_urls = asyncio.run(get_synthetic_urls_with_retry(hotkey = hotkey, num_needed = needed))
|
| 196 |
+
# logger.info(f"need {needed} chunks.....")
|
| 197 |
+
# needed_urls = await get_synthetic_requests_urls(num_needed = needed)
|
| 198 |
+
# push_synthetic_chunks(r, needed_urls)
|
| 199 |
+
|
| 200 |
+
# # Sleep for some time, e.g. 5 seconds, then re-check
|
| 201 |
+
# time.sleep(20)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# if __name__ == "__main__":
|
| 205 |
+
# asyncio.run(main())
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
|
| 209 |
import time
|
| 210 |
import random
|
|
|
|
|
|
|
| 211 |
import asyncio
|
| 212 |
import os
|
| 213 |
+
import uuid
|
| 214 |
+
import yaml
|
| 215 |
+
from typing import List, Dict, Optional
|
| 216 |
+
import httpx
|
| 217 |
+
from dotenv import load_dotenv
|
| 218 |
+
from loguru import logger
|
| 219 |
+
from pathlib import Path
|
| 220 |
+
|
| 221 |
from redis_utils import (
|
| 222 |
get_redis_connection,
|
| 223 |
get_organic_queue_size,
|
|
|
|
| 227 |
from video_utils import download_trim_downscale_video
|
| 228 |
from services.google_drive.google_drive_manager import GoogleDriveManager
|
| 229 |
from vidaio_subnet_core import CONFIG
|
|
|
|
|
|
|
|
|
|
| 230 |
from vidaio_subnet_core.utilities.minio_client import minio_client
|
| 231 |
+
|
| 232 |
+
# Load environment variables
|
| 233 |
load_dotenv()
|
| 234 |
|
| 235 |
+
def clear_queues(redis_conn) -> None:
|
| 236 |
"""Clear both organic and synthetic queues before starting."""
|
| 237 |
logger.info("Clearing queues")
|
| 238 |
redis_conn.delete(CONFIG.redis.organic_queue_key)
|
| 239 |
redis_conn.delete(CONFIG.redis.synthetic_queue_key)
|
| 240 |
|
| 241 |
+
def read_synthetic_urls(config_path: str) -> List[str]:
|
| 242 |
+
"""Read synthetic URLs from a YAML configuration file."""
|
| 243 |
with open(config_path, "r") as file:
|
| 244 |
config = yaml.safe_load(file)
|
| 245 |
return config.get("synthetic_urls", [])
|
| 246 |
|
| 247 |
+
async def get_synthetic_urls_with_retry(hotkey: str, max_retries: int = 2, initial_delay: float = 5.0, num_needed: int = 2) -> Optional[List[str]]:
|
| 248 |
+
"""Attempt to fetch synthetic request URLs with exponential backoff retry."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
for attempt in range(max_retries + 1):
|
| 250 |
try:
|
| 251 |
+
logger.info(f"Fetching synthetic URLs (Attempt {attempt + 1}/{max_retries + 1})...")
|
| 252 |
fetched_urls = await get_synthetic_urls(hotkey, num_needed)
|
| 253 |
|
| 254 |
if fetched_urls and len(fetched_urls) == num_needed:
|
| 255 |
+
logger.info(f"Successfully fetched {len(fetched_urls)} URLs")
|
| 256 |
return fetched_urls
|
| 257 |
else:
|
| 258 |
+
logger.warning(f"Insufficient URLs returned: got {len(fetched_urls) if fetched_urls else 0}, needed {num_needed}")
|
|
|
|
| 259 |
except Exception as e:
|
| 260 |
+
logger.error(f"Error fetching synthetic URLs: {str(e)}", exc_info=True)
|
| 261 |
|
| 262 |
if attempt < max_retries:
|
| 263 |
+
delay = initial_delay * (2 ** attempt)
|
| 264 |
logger.info(f"Retrying in {delay:.2f} seconds...")
|
| 265 |
await asyncio.sleep(delay)
|
| 266 |
|
| 267 |
+
logger.error("Failed to fetch synthetic URLs after retries.")
|
| 268 |
return None
|
| 269 |
|
| 270 |
async def get_synthetic_urls(hotkey: str, num_needed: int) -> Optional[List[str]]:
|
| 271 |
+
"""Fetch synthetic request URLs from the API."""
|
| 272 |
+
api_url = f"{os.getenv('VIDAIO_API_ENDPOINT')}/api/synthetic_urls"
|
| 273 |
+
params = {"validator_hotkey": hotkey, "num_needed": num_needed}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
try:
|
| 276 |
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 277 |
response = await client.get(api_url, params=params)
|
| 278 |
response.raise_for_status()
|
|
|
|
| 279 |
data = response.json()
|
|
|
|
| 280 |
|
| 281 |
if not isinstance(data, dict) or "synthetic_urls" not in data:
|
| 282 |
logger.error(f"Unexpected API response format: {data}")
|
|
|
|
| 284 |
|
| 285 |
urls = data["synthetic_urls"]
|
| 286 |
if not isinstance(urls, list):
|
| 287 |
+
logger.error(f"Invalid URL format in response: {urls}")
|
| 288 |
return None
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
return urls
|
| 291 |
+
except httpx.HTTPError as e:
|
| 292 |
+
logger.error(f"HTTP Error {e.response.status_code}: {e.response.text if e.response else 'No response'}")
|
| 293 |
except httpx.TimeoutException:
|
| 294 |
logger.error("API request timed out")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
except Exception as e:
|
| 296 |
+
logger.error(f"Unexpected error fetching synthetic URLs: {str(e)}", exc_info=True)
|
| 297 |
+
return None
|
|
|
|
|
|
|
| 298 |
|
| 299 |
async def get_synthetic_requests_urls(num_needed: int) -> List[Dict[str, str]]:
|
| 300 |
+
"""Generate synthetic Google Drive URLs by uploading trimmed videos."""
|
| 301 |
+
uploaded_video_chunks = []
|
| 302 |
+
remaining_count = num_needed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
while remaining_count > 0:
|
|
|
|
|
|
|
| 305 |
challenge_local_path, video_id = download_trim_downscale_video(
|
| 306 |
clip_duration=CONFIG.video_scheduler.clip_duration,
|
| 307 |
min_video_len=CONFIG.video_scheduler.min_video_len,
|
| 308 |
max_video_len=CONFIG.video_scheduler.max_video_len
|
| 309 |
)
|
| 310 |
|
| 311 |
+
if not challenge_local_path:
|
| 312 |
logger.info("Failed to download and trim video. Retrying...")
|
| 313 |
continue
|
| 314 |
|
|
|
|
| 318 |
await minio_client.upload_file(object_name, challenge_local_path)
|
| 319 |
sharing_link = await minio_client.get_presigned_url(object_name)
|
| 320 |
|
| 321 |
+
if not sharing_link:
|
| 322 |
logger.info("Upload failed. Retrying...")
|
| 323 |
continue
|
| 324 |
|
|
|
|
| 325 |
uploaded_video_chunks.append({
|
| 326 |
"video_id": video_id,
|
| 327 |
"uploaded_object_name": object_name,
|
| 328 |
"sharing_link": sharing_link
|
| 329 |
})
|
|
|
|
| 330 |
remaining_count -= 1
|
| 331 |
|
| 332 |
return uploaded_video_chunks
|
| 333 |
|
|
|
|
| 334 |
async def main():
|
| 335 |
+
"""Main function to manage video processing and synthetic queue handling."""
|
| 336 |
+
logger.info("Starting worker...")
|
| 337 |
+
redis_conn = get_redis_connection()
|
| 338 |
+
clear_queues(redis_conn)
|
| 339 |
|
| 340 |
while True:
|
| 341 |
+
organic_size = get_organic_queue_size(redis_conn)
|
| 342 |
+
synthetic_size = get_synthetic_queue_size(redis_conn)
|
| 343 |
total_size = organic_size + synthetic_size
|
| 344 |
+
|
| 345 |
+
logger.info(f"Organic queue size: {organic_size}")
|
| 346 |
+
logger.info(f"Synthetic queue size: {synthetic_size}")
|
| 347 |
+
|
| 348 |
threshold = CONFIG.video_scheduler.refill_threshold
|
| 349 |
fill_target = CONFIG.video_scheduler.refill_target
|
| 350 |
|
| 351 |
if total_size < threshold:
|
|
|
|
| 352 |
needed = fill_target - total_size
|
| 353 |
+
logger.info(f"Need {needed} chunks...")
|
| 354 |
+
needed_urls = await get_synthetic_requests_urls(num_needed=needed)
|
| 355 |
+
push_synthetic_chunks(redis_conn, needed_urls)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
+
await asyncio.sleep(20)
|
| 358 |
|
| 359 |
if __name__ == "__main__":
|
| 360 |
asyncio.run(main())
|
vidaio_subnet_core/global_config.py
CHANGED
|
@@ -26,4 +26,4 @@ class GlobalConfig(BaseSettings):
|
|
| 26 |
|
| 27 |
|
| 28 |
CONFIG = GlobalConfig()
|
| 29 |
-
logger.info(f"
|
|
|
|
| 26 |
|
| 27 |
|
| 28 |
CONFIG = GlobalConfig()
|
| 29 |
+
logger.info(f"Configuration loaded correctly")
|
vidaio_subnet_core/utilities/rate_limit.py
CHANGED
|
@@ -1,18 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
from ..global_config import CONFIG
|
| 3 |
|
| 4 |
-
|
| 5 |
def build_rate_limit(metagraph, uid: int) -> int:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
stake_array = metagraph.S
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
if uid not in
|
| 13 |
-
return 0
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import pandas as pd
|
| 2 |
+
# from ..global_config import CONFIG
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# def build_rate_limit(metagraph, uid: int) -> int:
|
| 6 |
+
# stake_array = metagraph.S
|
| 7 |
+
# w_uids = [
|
| 8 |
+
# i
|
| 9 |
+
# for i in range(len(stake_array))
|
| 10 |
+
# if stake_array[i] > CONFIG.bandwidth.min_stake
|
| 11 |
+
# ]
|
| 12 |
+
# if uid not in w_uids:
|
| 13 |
+
# return 0
|
| 14 |
+
# w_stakes = [stake_array[i] for i in w_uids]
|
| 15 |
+
# total_stake = sum(w_stakes)
|
| 16 |
+
# normalized_stakes = [stake / total_stake for stake in w_stakes]
|
| 17 |
+
# rate_limit = CONFIG.bandwidth.total_requests * normalized_stakes[w_uids.index(uid)]
|
| 18 |
+
# return rate_limit
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
import pandas as pd
|
| 23 |
from ..global_config import CONFIG
|
| 24 |
|
|
|
|
| 25 |
def build_rate_limit(metagraph, uid: int) -> int:
|
| 26 |
+
"""
|
| 27 |
+
Compute the rate limit for a given UID based on stake weight.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
metagraph: The metagraph object containing stake data.
|
| 31 |
+
uid (int): The user ID whose rate limit needs to be computed.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
int: The computed rate limit for the given UID.
|
| 35 |
+
"""
|
| 36 |
stake_array = metagraph.S
|
| 37 |
+
min_stake = CONFIG.bandwidth.min_stake
|
| 38 |
+
|
| 39 |
+
# Filter nodes with valid stakes
|
| 40 |
+
valid_uids_stakes = [(i, stake) for i, stake in enumerate(stake_array) if stake > min_stake]
|
| 41 |
+
|
| 42 |
+
if not valid_uids_stakes or uid not in [uid for uid, _ in valid_uids_stakes]:
|
| 43 |
+
return 0 # UID is not eligible for rate limiting
|
| 44 |
+
|
| 45 |
+
# Separate UID list and stakes
|
| 46 |
+
uids, stakes = zip(*valid_uids_stakes)
|
| 47 |
+
total_stake = sum(stakes)
|
| 48 |
+
|
| 49 |
+
if total_stake == 0:
|
| 50 |
+
return 0 # Avoid division by zero
|
| 51 |
+
|
| 52 |
+
# Compute normalized stake
|
| 53 |
+
normalized_stake = stakes[uids.index(uid)] / total_stake
|
| 54 |
+
return int(CONFIG.bandwidth.total_requests * normalized_stake)
|
vidaio_subnet_core/validating/managing/miner_manager.py
CHANGED
|
@@ -1,10 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import bittensor as bt
|
| 2 |
import redis
|
|
|
|
| 3 |
from sqlalchemy import create_engine
|
| 4 |
from sqlalchemy.orm import sessionmaker
|
| 5 |
from loguru import logger
|
| 6 |
-
|
| 7 |
-
import numpy as np
|
| 8 |
from .sql_schemas import MinerMetadata, Base
|
| 9 |
from .serving_counter import ServingCounter
|
| 10 |
from ...global_config import CONFIG
|
|
@@ -13,96 +125,175 @@ from ...utilities.rate_limit import build_rate_limit
|
|
| 13 |
|
| 14 |
class MinerManager:
|
| 15 |
def __init__(self, uid, wallet, metagraph):
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
self.uid = uid
|
| 18 |
self.wallet = wallet
|
| 19 |
self.dendrite = bt.dendrite(wallet=self.wallet)
|
| 20 |
self.metagraph = metagraph
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
self.
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
self.
|
| 30 |
-
|
| 31 |
-
self.initialize_serving_counter(self.metagraph.uids)
|
| 32 |
logger.success("MinerManager initialization complete")
|
| 33 |
-
|
| 34 |
-
def
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
uid=uid,
|
| 41 |
-
redis_client=self.redis_client,
|
| 42 |
)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
for uid in uids:
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
def step(self, scores: list[float], total_uids: list[int]):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
logger.info(f"Updating scores for {len(total_uids)} miners")
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
miner
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def consume(self, uids: list[int]) -> list[int]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
logger.info(f"Consuming {len(uids)} UIDs")
|
| 83 |
filtered_uids = [uid for uid in uids if self.serving_counters[uid].increment()]
|
| 84 |
-
logger.info(f"
|
| 85 |
return filtered_uids
|
| 86 |
|
| 87 |
@property
|
| 88 |
def weights(self):
|
| 89 |
-
|
| 90 |
-
scores
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
|
|
|
| 99 |
|
| 100 |
-
|
| 101 |
-
scores = scores / scores.sum()
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
scores = scores[sorted_indices] # Reorder scores to match sorted uids
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# import bittensor as bt
|
| 2 |
+
# import redis
|
| 3 |
+
# from sqlalchemy import create_engine
|
| 4 |
+
# from sqlalchemy.orm import sessionmaker
|
| 5 |
+
# from loguru import logger
|
| 6 |
+
# # from sqlalchemy.ext.declarative import declarative_base
|
| 7 |
+
# import numpy as np
|
| 8 |
+
# from .sql_schemas import MinerMetadata, Base
|
| 9 |
+
# from .serving_counter import ServingCounter
|
| 10 |
+
# from ...global_config import CONFIG
|
| 11 |
+
# from ...utilities.rate_limit import build_rate_limit
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# class MinerManager:
|
| 15 |
+
# def __init__(self, uid, wallet, metagraph):
|
| 16 |
+
# logger.info(f"Initializing MinerManager with uid: {uid}")
|
| 17 |
+
# self.uid = uid
|
| 18 |
+
# self.wallet = wallet
|
| 19 |
+
# self.dendrite = bt.dendrite(wallet=self.wallet)
|
| 20 |
+
# self.metagraph = metagraph
|
| 21 |
+
# logger.info(f"Connecting to Redis at {CONFIG.redis.host}:{CONFIG.redis.port}")
|
| 22 |
+
# self.redis_client = redis.Redis(
|
| 23 |
+
# host=CONFIG.redis.host, port=CONFIG.redis.port, db=CONFIG.redis.db
|
| 24 |
+
# )
|
| 25 |
+
# logger.info(f"Creating SQL engine with URL: {CONFIG.sql.url}")
|
| 26 |
+
# self.engine = create_engine(CONFIG.sql.url)
|
| 27 |
+
# Base.metadata.create_all(self.engine)
|
| 28 |
+
# Session = sessionmaker(bind=self.engine)
|
| 29 |
+
# self.session = Session()
|
| 30 |
+
# logger.info("Initializing serving counters")
|
| 31 |
+
# self.initialize_serving_counter(self.metagraph.uids)
|
| 32 |
+
# logger.success("MinerManager initialization complete")
|
| 33 |
+
|
| 34 |
+
# def initialize_serving_counter(self, uids: list[int]):
|
| 35 |
+
# rate_limit = build_rate_limit(self.metagraph, self.uid)
|
| 36 |
+
# logger.info(f"Creating serving counters for {len(uids)} UIDs with rate_limit {rate_limit}")
|
| 37 |
+
# self.serving_counters = {
|
| 38 |
+
# uid: ServingCounter(
|
| 39 |
+
# rate_limit=build_rate_limit(self.metagraph, uid), # Use uid here
|
| 40 |
+
# uid=uid,
|
| 41 |
+
# redis_client=self.redis_client,
|
| 42 |
+
# )
|
| 43 |
+
# for uid in uids
|
| 44 |
+
# }
|
| 45 |
+
# logger.debug("Serving counters initialized with rate limits") # Fixed closing brace
|
| 46 |
+
# for uid in uids:
|
| 47 |
+
# print(f"{uid}: {self.serving_counters[uid].rate_limit}")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# def query(self, uids: list[int] = []) -> dict[int, MinerMetadata]:
|
| 51 |
+
# logger.debug(f"Querying metadata for UIDs: {uids if uids else 'all'}")
|
| 52 |
+
# query = self.session.query(MinerMetadata)
|
| 53 |
+
# if uids:
|
| 54 |
+
# query = query.filter(MinerMetadata.uid.in_(uids))
|
| 55 |
+
# result = {miner.uid: miner for miner in query.all()}
|
| 56 |
+
# logger.debug(f"Found {len(result)} miner metadata records")
|
| 57 |
+
# return result
|
| 58 |
+
|
| 59 |
+
# def step(self, scores: list[float], total_uids: list[int]):
|
| 60 |
+
# logger.info(f"Updating scores for {len(total_uids)} miners")
|
| 61 |
+
# for uid, score in zip(total_uids, scores):
|
| 62 |
+
# logger.debug(f"Processing UID {uid} with score {score}")
|
| 63 |
+
# miner = self.query([uid]).get(uid, None)
|
| 64 |
+
# logger.info(f"Miner: {miner}")
|
| 65 |
+
# if miner is None:
|
| 66 |
+
# logger.info(f"Creating new metadata record for UID {uid}")
|
| 67 |
+
# miner = MinerMetadata(uid=uid)
|
| 68 |
+
# self.session.add(miner)
|
| 69 |
+
# # EMA with decay factor
|
| 70 |
+
# miner.accumulate_score = (
|
| 71 |
+
# miner.accumulate_score * CONFIG.score.decay_factor
|
| 72 |
+
# + score * (1 - CONFIG.score.decay_factor)
|
| 73 |
+
# )
|
| 74 |
+
# miner.accumulate_score = max(0, miner.accumulate_score)
|
| 75 |
+
# logger.debug(
|
| 76 |
+
# f"Updated accumulate_score for UID {uid}: {miner.accumulate_score}"
|
| 77 |
+
# )
|
| 78 |
+
# self.session.commit()
|
| 79 |
+
# logger.success(f"Updated metadata for {len(total_uids)} uids")
|
| 80 |
+
|
| 81 |
+
# def consume(self, uids: list[int]) -> list[int]:
|
| 82 |
+
# logger.info(f"Consuming {len(uids)} UIDs")
|
| 83 |
+
# filtered_uids = [uid for uid in uids if self.serving_counters[uid].increment()]
|
| 84 |
+
# logger.info(f"Filtered to {len(filtered_uids)} UIDs after rate limiting")
|
| 85 |
+
# return filtered_uids
|
| 86 |
+
|
| 87 |
+
# @property
|
| 88 |
+
# def weights(self):
|
| 89 |
+
# uids = []
|
| 90 |
+
# scores = []
|
| 91 |
+
|
| 92 |
+
# # Collect uids and scores
|
| 93 |
+
# for uid, miner in self.query().items():
|
| 94 |
+
# uids.append(uid)
|
| 95 |
+
# scores.append(miner.accumulate_score)
|
| 96 |
+
|
| 97 |
+
# # Convert to NumPy array
|
| 98 |
+
# scores = np.array(scores)
|
| 99 |
+
|
| 100 |
+
# # Normalize scores
|
| 101 |
+
# scores = scores / scores.sum()
|
| 102 |
+
|
| 103 |
+
# # Sort uids and rearrange scores accordingly
|
| 104 |
+
# sorted_indices = np.argsort(uids) # Get sorting indices for uids
|
| 105 |
+
# uids = np.array(uids)[sorted_indices] # Apply sorting to uids
|
| 106 |
+
# scores = scores[sorted_indices] # Reorder scores to match sorted uids
|
| 107 |
+
|
| 108 |
+
# return uids, scores
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
import bittensor as bt
|
| 114 |
import redis
|
| 115 |
+
import numpy as np
|
| 116 |
from sqlalchemy import create_engine
|
| 117 |
from sqlalchemy.orm import sessionmaker
|
| 118 |
from loguru import logger
|
| 119 |
+
|
|
|
|
| 120 |
from .sql_schemas import MinerMetadata, Base
|
| 121 |
from .serving_counter import ServingCounter
|
| 122 |
from ...global_config import CONFIG
|
|
|
|
| 125 |
|
| 126 |
class MinerManager:
|
| 127 |
def __init__(self, uid, wallet, metagraph):
|
| 128 |
+
"""
|
| 129 |
+
Initializes the MinerManager, handling Redis, SQL, and serving counters.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
uid (int): Unique identifier of the miner.
|
| 133 |
+
wallet (bt.wallet): Wallet instance for transactions.
|
| 134 |
+
metagraph: Metagraph containing stake data.
|
| 135 |
+
"""
|
| 136 |
+
logger.info(f"Initializing MinerManager for UID: {uid}")
|
| 137 |
+
|
| 138 |
self.uid = uid
|
| 139 |
self.wallet = wallet
|
| 140 |
self.dendrite = bt.dendrite(wallet=self.wallet)
|
| 141 |
self.metagraph = metagraph
|
| 142 |
+
|
| 143 |
+
# Connect to Redis
|
| 144 |
+
self._initialize_redis()
|
| 145 |
+
|
| 146 |
+
# Connect to SQL
|
| 147 |
+
self._initialize_sql()
|
| 148 |
+
|
| 149 |
+
# Initialize serving counters
|
| 150 |
+
self.initialize_serving_counter(metagraph.uids)
|
| 151 |
+
|
|
|
|
| 152 |
logger.success("MinerManager initialization complete")
|
| 153 |
+
|
| 154 |
+
def _initialize_redis(self):
|
| 155 |
+
"""Connect to Redis and handle errors gracefully."""
|
| 156 |
+
try:
|
| 157 |
+
logger.info(f"Connecting to Redis at {CONFIG.redis.host}:{CONFIG.redis.port}")
|
| 158 |
+
self.redis_client = redis.Redis(
|
| 159 |
+
host=CONFIG.redis.host, port=CONFIG.redis.port, db=CONFIG.redis.db
|
|
|
|
|
|
|
| 160 |
)
|
| 161 |
+
except Exception as e:
|
| 162 |
+
logger.error(f"Failed to connect to Redis: {e}")
|
| 163 |
+
raise
|
| 164 |
+
|
| 165 |
+
def _initialize_sql(self):
|
| 166 |
+
"""Set up the SQL database connection and session."""
|
| 167 |
+
try:
|
| 168 |
+
logger.info(f"Creating SQL engine with URL: {CONFIG.sql.url}")
|
| 169 |
+
self.engine = create_engine(CONFIG.sql.url)
|
| 170 |
+
Base.metadata.create_all(self.engine)
|
| 171 |
+
self.session = sessionmaker(bind=self.engine)()
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logger.error(f"Failed to connect to the database: {e}")
|
| 174 |
+
raise
|
| 175 |
+
|
| 176 |
+
def initialize_serving_counter(self, uids: list[int]):
|
| 177 |
+
"""
|
| 178 |
+
Initializes the serving counter for each UID based on stake-weighted rate limits.
|
| 179 |
+
|
| 180 |
+
Args:
|
| 181 |
+
uids (list[int]): List of UIDs for which serving counters should be created.
|
| 182 |
+
"""
|
| 183 |
+
logger.info(f"Initializing serving counters for {len(uids)} UIDs")
|
| 184 |
+
|
| 185 |
+
self.serving_counters = {}
|
| 186 |
for uid in uids:
|
| 187 |
+
rate_limit = build_rate_limit(self.metagraph, uid)
|
| 188 |
+
self.serving_counters[uid] = ServingCounter(
|
| 189 |
+
rate_limit=rate_limit, uid=uid, redis_client=self.redis_client
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
logger.debug("Serving counters initialized successfully")
|
| 193 |
+
|
| 194 |
+
def query(self, uids: list[int] = None) -> dict[int, MinerMetadata]:
|
| 195 |
+
"""
|
| 196 |
+
Fetch miner metadata from the database.
|
| 197 |
|
| 198 |
+
Args:
|
| 199 |
+
uids (list[int], optional): List of UIDs to query. If None, queries all.
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
dict[int, MinerMetadata]: A dictionary of miner metadata objects keyed by UID.
|
| 203 |
+
"""
|
| 204 |
+
try:
|
| 205 |
+
logger.debug(f"Querying miner metadata for: {uids if uids else 'all UIDs'}")
|
| 206 |
+
query = self.session.query(MinerMetadata)
|
| 207 |
+
if uids:
|
| 208 |
+
query = query.filter(MinerMetadata.uid.in_(uids))
|
| 209 |
+
result = {miner.uid: miner for miner in query.all()}
|
| 210 |
+
logger.debug(f"Retrieved {len(result)} miner records")
|
| 211 |
+
return result
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.error(f"Database query failed: {e}")
|
| 214 |
+
return {}
|
| 215 |
|
| 216 |
def step(self, scores: list[float], total_uids: list[int]):
|
| 217 |
+
"""
|
| 218 |
+
Updates miner scores using Exponential Moving Average (EMA).
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
scores (list[float]): List of updated scores.
|
| 222 |
+
total_uids (list[int]): Corresponding UIDs.
|
| 223 |
+
"""
|
| 224 |
logger.info(f"Updating scores for {len(total_uids)} miners")
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
miners = self.query(total_uids)
|
| 228 |
+
|
| 229 |
+
for uid, score in zip(total_uids, scores):
|
| 230 |
+
miner = miners.get(uid)
|
| 231 |
+
if miner is None:
|
| 232 |
+
logger.info(f"Creating new metadata record for UID {uid}")
|
| 233 |
+
miner = MinerMetadata(uid=uid)
|
| 234 |
+
self.session.add(miner)
|
| 235 |
+
|
| 236 |
+
# Apply EMA update
|
| 237 |
+
decay_factor = CONFIG.score.decay_factor
|
| 238 |
+
miner.accumulate_score = (
|
| 239 |
+
miner.accumulate_score * decay_factor + score * (1 - decay_factor)
|
| 240 |
+
)
|
| 241 |
+
miner.accumulate_score = max(0, miner.accumulate_score)
|
| 242 |
+
|
| 243 |
+
logger.debug(f"Updated UID {uid} score to {miner.accumulate_score}")
|
| 244 |
+
|
| 245 |
+
self.session.commit()
|
| 246 |
+
logger.success(f"Scores updated for {len(total_uids)} UIDs")
|
| 247 |
+
except Exception as e:
|
| 248 |
+
logger.error(f"Error updating miner scores: {e}")
|
| 249 |
+
self.session.rollback()
|
| 250 |
|
| 251 |
def consume(self, uids: list[int]) -> list[int]:
|
| 252 |
+
"""
|
| 253 |
+
Filters UIDs based on their rate limit consumption.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
uids (list[int]): List of UIDs requesting consumption.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
list[int]: List of UIDs that passed the rate limit check.
|
| 260 |
+
"""
|
| 261 |
logger.info(f"Consuming {len(uids)} UIDs")
|
| 262 |
filtered_uids = [uid for uid in uids if self.serving_counters[uid].increment()]
|
| 263 |
+
logger.info(f"{len(filtered_uids)} UIDs allowed after rate limiting")
|
| 264 |
return filtered_uids
|
| 265 |
|
| 266 |
@property
|
| 267 |
def weights(self):
|
| 268 |
+
"""
|
| 269 |
+
Computes and normalizes miner scores, returning sorted UIDs and corresponding weights.
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
tuple: (uids, scores) where both are sorted numpy arrays.
|
| 273 |
+
"""
|
| 274 |
+
try:
|
| 275 |
+
miners = self.query()
|
| 276 |
+
|
| 277 |
+
if not miners:
|
| 278 |
+
logger.warning("No miner data available for weight calculation")
|
| 279 |
+
return np.array([]), np.array([])
|
| 280 |
+
|
| 281 |
+
uids, scores = zip(*[(uid, miner.accumulate_score) for uid, miner in miners.items()])
|
| 282 |
+
|
| 283 |
+
# Convert scores to NumPy array and normalize
|
| 284 |
+
scores = np.array(scores, dtype=np.float64)
|
| 285 |
+
total_score = scores.sum()
|
| 286 |
|
| 287 |
+
if total_score == 0:
|
| 288 |
+
logger.warning("Total score is zero, returning uniform distribution")
|
| 289 |
+
return np.array(uids), np.ones_like(scores) / len(scores)
|
| 290 |
|
| 291 |
+
scores /= total_score # Normalize scores
|
|
|
|
| 292 |
|
| 293 |
+
# Sort UIDs and apply sorting to scores
|
| 294 |
+
sorted_indices = np.argsort(uids)
|
| 295 |
+
return np.array(uids)[sorted_indices], scores[sorted_indices]
|
|
|
|
| 296 |
|
| 297 |
+
except Exception as e:
|
| 298 |
+
logger.error(f"Error computing weights: {e}")
|
| 299 |
+
return np.array([]), np.array([])
|