Spaces:
Runtime error
Runtime error
Commit ·
1256bd3
0
Parent(s):
Init
Browse filesFiles changed (9)
- .gitignoreAdded+2
- DockerfileAdded+20
- app/config.pyAdded+9
- app/main.pyAdded+28
- app/routes/auth.pyAdded+64
- app/routes/youtube.pyAdded+77
- app/templates/index.htmlAdded+10
- app/templates/success.htmlAdded+11
- requirements.txtAdded
12venv__pycache__1234567891011121314151617181920# Use a lightweight Python imageFROM python:3.9-slim
# Create working directoryWORKDIR /app
# Copy requirements first for cachingCOPY requirements.txt /app/
# Install dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the applicationCOPY app /app/app
# Expose port (Hugging Face Spaces typically uses 7860 by default, but you can adjust if needed)EXPOSE 7860
# Start the app with uvicornCMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]123456789import os
# In a real environment, you would secure these properly.GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "50786072753-s9nq1ma3nv44k382b5mcnvmeggt1cvha.apps.googleusercontent.com")GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", "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")GOOGLE_REDIRECT_URI = os.environ.get("GOOGLE_REDIRECT_URI", "http://localhost:8000/auth/callback")
# For YouTube Data API. The user must consent to at least read their channel info and videos.YOUTUBE_SCOPES = ["https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtube.force-ssl"]12345678910111213141516171819202122232425262728from fastapi import FastAPI, Requestfrom fastapi.templating import Jinja2Templatesfrom fastapi.responses import HTMLResponsefrom starlette.middleware.sessions import SessionMiddlewareimport os
# Routersfrom app.routes import auth, youtube
# For rendering HTML templatestemplates = Jinja2Templates(directory="app/templates")
app = FastAPI()
# Set a secret key for session cookies (Use a strong key in production!)app.add_middleware(SessionMiddleware, secret_key="CHANGE_THIS_SECRET")
# Include our routersapp.include_router(auth.router)app.include_router(youtube.router)
@app.get("/", response_class=HTMLResponse)async def read_root(request: Request): return templates.TemplateResponse("index.html", {"request": request})
@app.get("/success", response_class=HTMLResponse)async def read_success(request: Request): return templates.TemplateResponse("success.html", {"request": request})12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from fastapi import APIRouter, Request, Response, statusfrom fastapi.responses import RedirectResponse, HTMLResponsefrom starlette.middleware.sessions import SessionMiddlewarefrom google_auth_oauthlib.flow import Flowimport os
from app.config import GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI, YOUTUBE_SCOPES
router = APIRouter()
def create_flow(): return Flow.from_client_config( { "web": { "client_id": GOOGLE_CLIENT_ID, "project_id": "youtube-fastapi-sample", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "client_secret": GOOGLE_CLIENT_SECRET, } }, scopes=YOUTUBE_SCOPES, )
@router.get("/login")async def login(request: Request): flow = create_flow() flow.redirect_uri = GOOGLE_REDIRECT_URI # must set the redirect_uri separately authorization_url, state = flow.authorization_url( access_type="offline", include_granted_scopes="true", prompt="select_account" ) request.session["state"] = state return RedirectResponse(authorization_url)
@router.get("/auth/callback")async def auth_callback(request: Request): """Handle OAuth callback from Google with ?code= and ?state=.""" state = request.session.get("state") if not state: return HTMLResponse("<h1>Session state not found. Please /login again.</h1>", status_code=400)
flow = create_flow() flow.fetch_token(authorization_response=str(request.url))
# Get the credentials object credentials = flow.credentials if not credentials or not credentials.valid: return HTMLResponse("<h1>Invalid credentials. Please /login again.</h1>", status_code=400)
# Store credentials in session. In production, store securely (e.g. in DB, encrypted). request.session["credentials"] = { "token": credentials.token, "refresh_token": credentials.refresh_token, "token_uri": credentials.token_uri, "client_id": credentials.client_id, "client_secret": credentials.client_secret, "scopes": credentials.scopes }
return RedirectResponse(url="/success", status_code=status.HTTP_302_FOUND)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from fastapi import APIRouter, Request, HTTPExceptionfrom google.oauth2.credentials import Credentialsfrom googleapiclient.discovery import build
router = APIRouter()
def get_credentials_from_session(session) -> Credentials: """Utility to build a Credentials object from stored session data.""" creds_data = session.get("credentials") if not creds_data: return None return Credentials( token=creds_data["token"], refresh_token=creds_data["refresh_token"], token_uri=creds_data["token_uri"], client_id=creds_data["client_id"], client_secret=creds_data["client_secret"], scopes=creds_data["scopes"] )
@router.get("/list-channels")async def list_channels(request: Request): """Return the user’s list of YouTube channels.""" creds = get_credentials_from_session(request.session) if not creds or not creds.valid: raise HTTPException(status_code=401, detail="Unauthorized. Please /login first.")
youtube = build("youtube", "v3", credentials=creds) response = youtube.channels().list( part="id,snippet", mine=True ).execute()
channels = [] for item in response.get("items", []): channels.append({ "channelId": item["id"], "title": item["snippet"]["title"] })
return {"channels": channels}
@router.get("/list-videos")async def list_videos(request: Request, channel_id: str): """List videos for the specified channel.""" creds = get_credentials_from_session(request.session) if not creds or not creds.valid: raise HTTPException(status_code=401, detail="Unauthorized. Please /login first.")
youtube = build("youtube", "v3", credentials=creds)
# Example: listing videos from a channel’s "uploads" playlist # 1) Retrieve the uploads playlist from channel channel_response = youtube.channels().list( part="contentDetails", id=channel_id ).execute()
uploads_playlist_id = channel_response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
# 2) Retrieve items from the uploads playlist playlist_items_response = youtube.playlistItems().list( part="snippet", playlistId=uploads_playlist_id, maxResults=10 ).execute()
videos = [] for item in playlist_items_response.get("items", []): snippet = item["snippet"] videos.append({ "videoId": snippet["resourceId"]["videoId"], "title": snippet["title"] })
return {"videos": videos}12345678910<!DOCTYPE html><html><head> <title>FastAPI + Google OAuth2 Example</title></head><body> <h1>Welcome to the FastAPI + Google OAuth2 Example</h1> <p>Please <a href="/login">Login with Google</a> to see your YouTube channels.</p></body></html>1234567891011<!DOCTYPE html><html><head> <title>Login Successful</title></head><body> <h1>Login Successful!</h1> <p>You can now view your <a href="/list-channels" target="_blank">YouTube Channels (JSON)</a>.</p> <p>After you get a channel ID, you can try <code>/list-videos?channel_id=XYZ</code> to see its videos.</p></body></html>.gitignoreAdded+2
DockerfileAdded+20
app/config.pyAdded+9
app/main.pyAdded+28
app/routes/auth.pyAdded+64
app/routes/youtube.pyAdded+77
app/templates/index.htmlAdded+10
app/templates/success.htmlAdded+11
requirements.txtAdded