Mbonea commited on
Commit
0978387
·
1 Parent(s): fa7dd75

yt_router (untested)

Browse files
Files changed (4) hide show
  1. App/Youtube/Schema.py +31 -0
  2. App/Youtube/youtubeRouter.py +110 -0
  3. App/app.py +2 -1
  4. Dockerfile +7 -0
App/Youtube/Schema.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field, HttpUrl
2
+
3
+
4
+ class YouTubeUploadTask(BaseModel):
5
+ filename: HttpUrl = Field(..., description="URL of the video file to upload")
6
+ title: str = Field(
7
+ ...,
8
+ min_length=100,
9
+ max_length=500,
10
+ description="A good title for the video",
11
+ )
12
+ description: str = Field(
13
+ ...,
14
+ min_length=100,
15
+ max_length=500,
16
+ description="A brief summary of the video's content",
17
+ )
18
+ category_id: str = "22" # Default to a generic category, update as needed
19
+ privacy: str = "private"
20
+ tags: str = Field(
21
+ ...,
22
+ min_length=100,
23
+ max_length=500,
24
+ description="Best seo tags for youtube based on the story",
25
+ )
26
+ thumbnail: str = Field(
27
+ ...,
28
+ min_length=100,
29
+ max_length=500,
30
+ description="""Best image prompt based on the image description: here is an """,
31
+ )
App/Youtube/youtubeRouter.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException, BackgroundTasks
2
+ from subprocess import run
3
+ import tempfile
4
+ import os
5
+ import logging
6
+ import aiohttp
7
+ import asyncio
8
+ from .Schema import YouTubeUploadTask
9
+
10
+ # Configure logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ router = APIRouter(prefix="/youtube", tags=["youtube"])
15
+
16
+
17
+ async def download_file(url: str) -> str:
18
+ """Download file from URL and save to temp directory."""
19
+ try:
20
+ async with aiohttp.ClientSession() as session:
21
+ async with session.get(url) as response:
22
+ if response.status != 200:
23
+ raise HTTPException(
24
+ status_code=400,
25
+ detail=f"Failed to download file: HTTP {response.status}",
26
+ )
27
+
28
+ # Create temp file with appropriate extension
29
+ content_type = response.headers.get("content-type", "")
30
+ ext = ".mp4" if "video" in content_type else ".tmp"
31
+
32
+ fd, temp_path = tempfile.mkstemp(suffix=ext)
33
+
34
+ # Write content to temp file
35
+ with os.fdopen(fd, "wb") as tmp:
36
+ while chunk := await response.content.read(8192):
37
+ tmp.write(chunk)
38
+
39
+ return temp_path
40
+ except Exception as e:
41
+ logger.error(f"Error downloading file: {str(e)}")
42
+ raise HTTPException(status_code=500, detail=f"File download failed: {str(e)}")
43
+
44
+
45
+ async def upload_video_background(task: YouTubeUploadTask):
46
+ """Background task to handle video upload."""
47
+ temp_file = None
48
+ try:
49
+ logger.info(f"Starting download for video: {task.filename}")
50
+ temp_file = await download_file(task.filename)
51
+ logger.info(f"Download complete. Saved to: {temp_file}")
52
+
53
+ # Build the command
54
+ command = [
55
+ "/srv/youtube/youtubeuploader",
56
+ "-filename",
57
+ temp_file,
58
+ "-title",
59
+ task.title,
60
+ "-description",
61
+ task.description,
62
+ "-categoryId",
63
+ task.category_id,
64
+ "-privacy",
65
+ task.privacy,
66
+ "-tags",
67
+ task.tags,
68
+ ]
69
+
70
+ if task.thumbnail:
71
+ command.extend(["-thumbnail", task.thumbnail])
72
+
73
+ logger.info("Executing upload command")
74
+ result = run(command, capture_output=True, text=True)
75
+
76
+ if result.returncode != 0:
77
+ logger.error(f"Upload failed: {result.stderr}")
78
+ raise Exception(f"Upload failed: {result.stderr}")
79
+
80
+ logger.info("Upload completed successfully")
81
+ logger.debug(f"Upload output: {result.stdout}")
82
+
83
+ except Exception as e:
84
+ logger.error(f"Error in upload process: {str(e)}")
85
+ raise
86
+ finally:
87
+ # Clean up temp file
88
+ if temp_file and os.path.exists(temp_file):
89
+ try:
90
+ os.remove(temp_file)
91
+ logger.info(f"Cleaned up temporary file: {temp_file}")
92
+ except Exception as e:
93
+ logger.error(f"Failed to clean up temp file: {str(e)}")
94
+
95
+
96
+ @router.post("/upload")
97
+ async def upload_video_to_youtube(
98
+ task: YouTubeUploadTask, background_tasks: BackgroundTasks
99
+ ):
100
+ """
101
+ Endpoint to handle YouTube video upload requests.
102
+ The actual upload is performed as a background task.
103
+ """
104
+ try:
105
+ background_tasks.add_task(upload_video_background, task)
106
+ return {"message": "Upload task started", "status": "processing"}
107
+
108
+ except Exception as e:
109
+ logger.error(f"Error initiating upload task: {str(e)}")
110
+ raise HTTPException(status_code=500, detail=str(e))
App/app.py CHANGED
@@ -5,7 +5,7 @@ from fastapi.middleware.gzip import GZipMiddleware
5
  from .TTS.TTSRoutes import tts_router
6
  from .Embedding.EmbeddingRoutes import embeddigs_router
7
  from .OCR.Tesseract import tessaract_ocr_router
8
-
9
  from fastapi.middleware.cors import CORSMiddleware
10
 
11
  from fastapi_cache import FastAPICache
@@ -48,4 +48,5 @@ async def landing_page():
48
  app.include_router(embeddigs_router)
49
  app.include_router(tessaract_ocr_router)
50
  app.include_router(tts_router)
 
51
  # app.include_router(shader_router)
 
5
  from .TTS.TTSRoutes import tts_router
6
  from .Embedding.EmbeddingRoutes import embeddigs_router
7
  from .OCR.Tesseract import tessaract_ocr_router
8
+ from .Youtube.youtubeRouter import router as yt_router
9
  from fastapi.middleware.cors import CORSMiddleware
10
 
11
  from fastapi_cache import FastAPICache
 
48
  app.include_router(embeddigs_router)
49
  app.include_router(tessaract_ocr_router)
50
  app.include_router(tts_router)
51
+ app.include_router(yt_router)
52
  # app.include_router(shader_router)
Dockerfile CHANGED
@@ -40,6 +40,13 @@ USER admin
40
 
41
  COPY --chown=admin . /srv
42
 
 
 
 
 
 
 
 
43
  # Command to run the application
44
  CMD uvicorn App.app:app --host 0.0.0.0 --port 7860 --workers 1
45
  # Expose the server port
 
40
 
41
  COPY --chown=admin . /srv
42
 
43
+ # Install youtubeuploader
44
+ ADD https://github.com/porjo/youtubeuploader/releases/download/23.06/youtubeuploader_23.06_Linux_x86_64.tar.gz youtubeuploader.tar.gz
45
+ RUN mkdir -p /srv/youtube && \
46
+ tar -zxvf youtubeuploader.tar.gz -C /srv/youtube && \
47
+ rm youtubeuploader.tar.gz && \
48
+ chmod +x /srv/youtube/youtubeuploader
49
+
50
  # Command to run the application
51
  CMD uvicorn App.app:app --host 0.0.0.0 --port 7860 --workers 1
52
  # Expose the server port