NitinBot001 commited on
Commit
c221a38
·
verified ·
1 Parent(s): 216d657

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -177
app.py CHANGED
@@ -1,217 +1,142 @@
1
- import os
2
- import io
3
- import json
4
- import uuid
5
- import wave
6
- import tempfile
7
- from datetime import datetime
8
- from typing import Optional, Dict, Any
9
- from pathlib import Path
10
-
11
- from fastapi import FastAPI, File, UploadFile, HTTPException
12
- from fastapi.middleware.cors import CORSMiddleware
13
  from fastapi.responses import JSONResponse
14
  from pydantic import BaseModel
 
 
15
  import uvicorn
16
- import requests
17
- import numpy as np
18
- from groq import Groq
19
- import dotenv
20
-
21
- # Load environment variables
22
- dotenv.load_dotenv()
23
-
24
- app = FastAPI(title="Voice AI Backend")
25
 
26
- # CORS configuration
27
- app.add_middleware(
28
- CORSMiddleware,
29
- allow_origins=["*"], # Configure appropriately for production
30
- allow_credentials=True,
31
- allow_methods=["*"],
32
- allow_headers=["*"],
33
  )
34
 
35
- # Configuration
36
- GROQ_MODEL = "whisper-large-v3-turbo"
37
- AI_API_ENDPOINT = "https://nitinbot001-crop-rag-api.hf.space/api/query"
38
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
39
-
40
- # Initialize Groq client
41
- groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
42
-
43
- # Store conversation history (in production, use a database)
44
- conversation_history = []
45
 
46
- class TranscriptionResponse(BaseModel):
47
- success: bool
48
- user_query: str
49
- ai_response: str
50
- metadata: Dict[str, Any]
51
- session_id: str
52
- timestamp: str
53
- error: Optional[str] = None
54
-
55
- class ConversationHistory(BaseModel):
56
- sessions: list
57
 
58
  @app.get("/")
59
  async def root():
60
- return {"message": "Voice AI Backend API", "status": "online"}
 
 
 
 
 
 
 
 
61
 
62
- @app.post("/api/process-audio", response_model=TranscriptionResponse)
63
- async def process_audio(audio: UploadFile = File(...)):
64
- """
65
- Process audio file: transcribe and get AI response
66
  """
67
- session_id = str(uuid.uuid4())
68
- timestamp = datetime.now().isoformat()
69
 
 
 
 
 
 
 
 
70
  try:
71
- # Validate file type
72
- if not audio.filename.endswith(('.wav', '.webm', '.mp3', '.m4a', '.ogg')):
73
- raise HTTPException(status_code=400, detail="Invalid audio format")
74
 
75
- # Read audio data
76
- audio_data = await audio.read()
77
 
78
- # Save temporary file for processing
79
- with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
80
- # If it's webm (from browser), we need to save it as-is
81
- # Groq can handle webm directly
82
- if audio.filename.endswith('.webm'):
83
- tmp_file.write(audio_data)
84
- tmp_path = tmp_file.name
85
- else:
86
- # For wav files, write directly
87
- tmp_file.write(audio_data)
88
- tmp_path = tmp_file.name
89
-
90
- # Transcribe with Groq
91
- user_query = await transcribe_audio(tmp_path, audio.filename)
92
-
93
- # Get AI response
94
- ai_response = await get_ai_response(user_query)
95
-
96
- # Create metadata
97
- metadata = {
98
- "audio_size": len(audio_data),
99
- "audio_format": audio.filename.split('.')[-1],
100
- "transcription_model": GROQ_MODEL,
101
- "ai_endpoint": AI_API_ENDPOINT,
102
- "processing_time": datetime.now().isoformat(),
103
- }
104
-
105
- # Store in history
106
- conversation_history.append({
107
- "session_id": session_id,
108
- "timestamp": timestamp,
109
- "user_query": user_query,
110
- "ai_response": ai_response,
111
- "metadata": metadata
112
- })
113
 
114
- # Clean up
115
- os.unlink(tmp_path)
116
 
117
- return TranscriptionResponse(
118
- success=True,
119
- user_query=user_query,
120
- ai_response=ai_response,
121
- metadata=metadata,
122
- session_id=session_id,
123
- timestamp=timestamp
124
  )
125
-
126
  except Exception as e:
127
- return TranscriptionResponse(
128
- success=False,
129
- user_query="",
130
- ai_response="",
131
- metadata={},
132
- session_id=session_id,
133
- timestamp=timestamp,
134
- error=str(e)
135
  )
136
 
137
- async def transcribe_audio(file_path: str, original_filename: str) -> str:
138
- """
139
- Transcribe audio using Groq Whisper
140
  """
141
- if not groq_client:
142
- raise HTTPException(status_code=500, detail="GROQ_API_KEY not configured")
143
 
 
 
 
 
 
 
144
  try:
145
- with open(file_path, "rb") as audio_file:
146
- transcription = groq_client.audio.transcriptions.create(
147
- file=(original_filename, audio_file.read()),
148
- model=GROQ_MODEL,
149
- response_format="text"
 
 
 
 
 
 
150
  )
151
 
152
- # Handle different response formats
153
- if hasattr(transcription, 'text'):
154
- text = transcription.text
155
- elif isinstance(transcription, dict):
156
- text = transcription.get('text', '')
157
- else:
158
- text = str(transcription)
159
 
160
- return text.strip()
 
 
 
 
161
 
162
  except Exception as e:
163
- raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
 
 
 
164
 
165
- async def get_ai_response(query: str) -> str:
 
166
  """
167
- Get response from AI API
 
 
 
 
 
 
 
168
  """
169
  try:
170
- headers = {"Content-Type": "application/json"}
171
- payload = {"query": query}
172
-
173
- response = requests.post(
174
- AI_API_ENDPOINT,
175
- json=payload,
176
- headers=headers,
177
- timeout=30
178
- )
179
- response.raise_for_status()
180
-
181
- result = response.json()
182
 
183
- # Extract text from response (adjust based on actual API response format)
184
- if isinstance(result, dict):
185
- # Try different possible response keys
186
- ai_text = result.get('response',
187
- result.get('answer',
188
- result.get('text',
189
- result.get('message', str(result)))))
190
- else:
191
- ai_text = str(result)
192
 
193
- return ai_text
194
 
195
- except requests.exceptions.Timeout:
196
- return "I'm sorry, the AI service is taking too long to respond. Please try again."
197
  except Exception as e:
198
- return f"I encountered an error while processing your request: {str(e)}"
199
-
200
- @app.get("/api/history", response_model=ConversationHistory)
201
- async def get_history():
202
- """
203
- Get conversation history
204
- """
205
- return ConversationHistory(sessions=conversation_history[-20:]) # Last 20 conversations
206
-
207
- @app.delete("/api/history")
208
- async def clear_history():
209
- """
210
- Clear conversation history
211
- """
212
- global conversation_history
213
- conversation_history = []
214
- return {"message": "History cleared"}
215
 
216
  if __name__ == "__main__":
217
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI, HTTPException
 
 
 
 
 
 
 
 
 
 
 
2
  from fastapi.responses import JSONResponse
3
  from pydantic import BaseModel
4
+ from innertube import InnerTube
5
+ from typing import Optional, List, Dict, Any
6
  import uvicorn
 
 
 
 
 
 
 
 
 
7
 
8
+ app = FastAPI(
9
+ title="YouTube Streaming Data API",
10
+ description="API to fetch YouTube video streaming data",
11
+ version="1.0.0"
 
 
 
12
  )
13
 
14
+ class VideoRequest(BaseModel):
15
+ video_id: str
16
+ client_type: Optional[str] = "IOS"
 
 
 
 
 
 
 
17
 
18
+ class StreamingDataResponse(BaseModel):
19
+ video_id: str
20
+ streams: List[Dict[str, Any]]
21
+ status: str
 
 
 
 
 
 
 
22
 
23
  @app.get("/")
24
  async def root():
25
+ """Root endpoint with API information"""
26
+ return {
27
+ "message": "YouTube Streaming Data API",
28
+ "endpoints": {
29
+ "/streams/{video_id}": "GET - Fetch streaming data for a video",
30
+ "/streams": "POST - Fetch streaming data with custom client type",
31
+ "/docs": "API documentation"
32
+ }
33
+ }
34
 
35
+ @app.get("/streams/{video_id}")
36
+ async def get_streams_by_id(video_id: str, client_type: str = "IOS"):
 
 
37
  """
38
+ Fetch streaming data for a YouTube video by video ID
 
39
 
40
+ Args:
41
+ video_id: YouTube video ID (e.g., dQw4w9WgXcQ)
42
+ client_type: Client type to use (default: IOS)
43
+
44
+ Returns:
45
+ Streaming data including adaptive formats
46
+ """
47
  try:
48
+ # Create InnerTube client
49
+ client = InnerTube(client_type)
 
50
 
51
+ # Fetch player data
52
+ data = client.player(video_id)
53
 
54
+ # Extract streaming data
55
+ if "streamingData" not in data:
56
+ raise HTTPException(
57
+ status_code=404,
58
+ detail="No streaming data found for this video"
59
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ streams = data["streamingData"].get("adaptiveFormats", [])
 
62
 
63
+ return StreamingDataResponse(
64
+ video_id=video_id,
65
+ streams=streams,
66
+ status="success"
 
 
 
67
  )
68
+
69
  except Exception as e:
70
+ raise HTTPException(
71
+ status_code=500,
72
+ detail=f"Error fetching streaming data: {str(e)}"
 
 
 
 
 
73
  )
74
 
75
+ @app.post("/streams")
76
+ async def get_streams(request: VideoRequest):
 
77
  """
78
+ Fetch streaming data for a YouTube video with custom client type
 
79
 
80
+ Args:
81
+ request: VideoRequest object containing video_id and optional client_type
82
+
83
+ Returns:
84
+ Streaming data including adaptive formats
85
+ """
86
  try:
87
+ # Create InnerTube client
88
+ client = InnerTube(request.client_type)
89
+
90
+ # Fetch player data
91
+ data = client.player(request.video_id)
92
+
93
+ # Extract streaming data
94
+ if "streamingData" not in data:
95
+ raise HTTPException(
96
+ status_code=404,
97
+ detail="No streaming data found for this video"
98
  )
99
 
100
+ streams = data["streamingData"].get("adaptiveFormats", [])
 
 
 
 
 
 
101
 
102
+ return StreamingDataResponse(
103
+ video_id=request.video_id,
104
+ streams=streams,
105
+ status="success"
106
+ )
107
 
108
  except Exception as e:
109
+ raise HTTPException(
110
+ status_code=500,
111
+ detail=f"Error fetching streaming data: {str(e)}"
112
+ )
113
 
114
+ @app.get("/streams/{video_id}/full")
115
+ async def get_full_player_data(video_id: str, client_type: str = "IOS"):
116
  """
117
+ Fetch full player data for a YouTube video
118
+
119
+ Args:
120
+ video_id: YouTube video ID
121
+ client_type: Client type to use (default: IOS)
122
+
123
+ Returns:
124
+ Complete player data response
125
  """
126
  try:
127
+ # Create InnerTube client
128
+ client = InnerTube(client_type)
 
 
 
 
 
 
 
 
 
 
129
 
130
+ # Fetch player data
131
+ data = client.player(video_id)
 
 
 
 
 
 
 
132
 
133
+ return JSONResponse(content=data)
134
 
 
 
135
  except Exception as e:
136
+ raise HTTPException(
137
+ status_code=500,
138
+ detail=f"Error fetching player data: {str(e)}"
139
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  if __name__ == "__main__":
142
+ uvicorn.run(app, host="0.0.0.0", port=8000)