Spaces:
Sleeping
Sleeping
Commit ·
7bb63b8
1
Parent(s): 6b7b0ee
fix tvdb
Browse files75 unmodified lines767778798081828375 unmodified lines# Return combined resultsreturn JSONResponse(content={'recent_films': limited_films,'recent_series': limited_series})@app.get("/api/get/film/metadata/{title}")75 unmodified lines767778798081828375 unmodified lines# Return combined resultsreturn JSONResponse(content={'films': limited_films,'series': limited_series})@app.get("/api/get/film/metadata/{title}")
24 unmodified lines25262728293031323334356 unmodified lines42434445464748495051525354555657585960616263646566673 unmodified lines7172737475767778791 unmodified line818283848586872 unmodified lines909192939495969798991001011021031041051061071081091101112 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216324 unmodified lines"apikey": THETVDB_API_KEY}try:response = requests.post(auth_url, json=auth_data)response.raise_for_status()response_data = response.json()THETVDB_TOKEN = response_data['data']['token']TOKEN_EXPIRY = datetime.now() + timedelta(days=30)except requests.RequestException as e:print(f"Authentication failed: {e}")THETVDB_TOKEN = None6 unmodified linesreturn THETVDB_TOKENdef clean_data(data):fields_to_keep = {"data": {'id': None,'name': None,'image': None,'score': None,'runtime': None,'releases': None,'year': None,'contentRatings': None,'originalCountry': None,'originalLanguage': None,'translations': {},'artworks': [],'characters': [],'spoken_languages': [],'translations': {}}}"""Clean up the data to retain only necessary fields."""cleaned_data = {}for key, value in fields_to_keep.items():3 unmodified linesif field in data[key]:cleaned_data[key][field] = data[key][field]return cleaned_dataasync def fetch_and_cache_json(original_title, title, media_type, year=None):if year:search_url = f"{THETVDB_API_URL}/search?query={urllib.parse.quote(title)}&type={media_type}&year={year}"else:1 unmodified linetoken = get_thetvdb_token()if not token:print("Authentication failed")returnheaders = {2 unmodified lines}try:# Fetch initial search resultsresponse = requests.get(search_url, headers=headers)response.raise_for_status()data = response.json()if 'data' in data and data['data']:# Extract the TVDB ID and type from the first resultfirst_result = data['data'][0]tvdb_id = first_result.get('tvdb_id')media_type = first_result.get('type')if not tvdb_id:print("TVDB ID not found in the search results")return# Determine the correct extended URL based on media typeif media_type == 'movie':extended_url = f"{THETVDB_API_URL}/movies/{tvdb_id}/extended?meta=translations"elif media_type == 'series':2 unmodified lineselse:print(f"Unsupported media type: {media_type}")return# Request the extended information using the TVDB IDresponse = requests.get(extended_url, headers=headers)response.raise_for_status()extended_data = response.json()cleaned_data = clean_data(extended_data)# Extract the English descriptiondescription = Noneif cleaned_data['data']['translations'] and cleaned_data['data']['translations']['overviewTranslations']:for overview in cleaned_data['data']['translations']['overviewTranslations']:if overview['language'] == 'eng' and overview['isPrimary']:description = overview['overview']break# Extract the artwork type 15 linkimage_link = Noneif cleaned_data['data']['artworks']:for artwork in cleaned_data['data']['artworks']:if artwork['type'] == 15:image_link = artwork['image']break# Add the entry to the RecentList with description and image_linkif media_type == 'movie':recent_list.add_entry(original_title, cleaned_data['data']['year'], description, image_link, 'film')elif media_type == 'series':recent_list.add_entry(original_title, cleaned_data['data']['year'], description, image_link, 'series')# Cache the extended JSON responsejson_cache_path = os.path.join(CACHE_DIR, f"{urllib.parse.quote(original_title)}.json")await save_to_json(cleaned_data, json_cache_path)except requests.RequestException as e:print(f"Error fetching data: {e}")def main():# Replace with your series ID and other parametersoriginal_title = "The Listner (2009)"title = "The Listner"media_type = "series" # or "movie"year = 2009asyncio.run(fetch_and_cache_json(original_title, title, media_type, year))if __name__ == "__main__":main()24 unmodified lines252627282930313233343536376 unmodified lines44454647484950515253545556575859606162636465666768693 unmodified lines73747576777879808182831 unmodified line858687888990912 unmodified lines9495969798991001011021031041051061071081091101111121131141152 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817924 unmodified lines"apikey": THETVDB_API_KEY}try:print("Authenticating with TheTVDB API...")response = requests.post(auth_url, json=auth_data)response.raise_for_status()response_data = response.json()THETVDB_TOKEN = response_data['data']['token']TOKEN_EXPIRY = datetime.now() + timedelta(days=30)print("Authentication successful.")except requests.RequestException as e:print(f"Authentication failed: {e}")THETVDB_TOKEN = None6 unmodified linesreturn THETVDB_TOKENdef clean_data(data):print("Cleaning data...")fields_to_keep = {"data": {'id': None,'name': None,'image': None,'score': None,'runtime': None,'releases': None,'year': None,'contentRatings': None,'originalCountry': None,'originalLanguage': None,'translations': {},'artworks': [],'characters': [],'spoken_languages': [],'translations': {}}}cleaned_data = {}for key, value in fields_to_keep.items():3 unmodified linesif field in data[key]:cleaned_data[key][field] = data[key][field]print("Data cleaned successfully.")return cleaned_dataasync def fetch_and_cache_json(original_title, title, media_type, year=None):print(f"Fetching data for: {original_title}")if year:search_url = f"{THETVDB_API_URL}/search?query={urllib.parse.quote(title)}&type={media_type}&year={year}"else:1 unmodified linetoken = get_thetvdb_token()if not token:print("Authentication token not available.")returnheaders = {2 unmodified lines}try:print(f"Sending search request to: {search_url}")response = requests.get(search_url, headers=headers)print(f"Search response status code: {response.status_code}")response.raise_for_status()data = response.json()if 'data' in data and data['data']:first_result = data['data'][0]tvdb_id = first_result.get('tvdb_id')media_type = first_result.get('type')print(f"Found TVDB ID: {tvdb_id} with media type: {media_type}")if not tvdb_id:print("TVDB ID not found in the search results")returnif media_type == 'movie':extended_url = f"{THETVDB_API_URL}/movies/{tvdb_id}/extended?meta=translations"elif media_type == 'series':2 unmodified lineselse:print(f"Unsupported media type: {media_type}")returnresponse = requests.get(extended_url, headers=headers)print(f"Extended data response status code: {response.status_code}")response.raise_for_status()extended_data = response.json()cleaned_data = clean_data(extended_data)print(f"cleaning.. {original_title}")description = Noneif cleaned_data['data'].get('translations') and cleaned_data['data']['translations'].get('overviewTranslations'):for overview in cleaned_data['data']['translations']['overviewTranslations']:if overview['language'] == 'eng' and overview.get('isPrimary'):description = overview.get('overview')breakprint(f"Description extracted: {description}")image_link = Noneif cleaned_data['data'].get('artworks'):for artwork in cleaned_data['data']['artworks']:if artwork['type'] in [15, 3]:image_link = artwork.get('image')breakprint(f"Image link extracted: {image_link}")if media_type == 'movie':recent_list.add_entry(original_title, cleaned_data['data']['year'], description, image_link, 'film')elif media_type == 'series':recent_list.add_entry(original_title, cleaned_data['data']['year'], description, image_link, 'series')print(f"adding.. {original_title}")json_cache_path = os.path.join(CACHE_DIR, f"{urllib.parse.quote(original_title)}.json")await save_to_json(cleaned_data, json_cache_path)print(f"Data saved to JSON at: {json_cache_path}")else:print(f"No data found for {original_title} in search results.")except requests.RequestException as e:print(f"Error fetching data: {e}")except Exception as e:print(f"An unexpected error occurred: {e}")def main():entries = [{"original_title": "Funky Monkey (2004)", "title": "Funky Monkey", "media_type": "movie", "year": 2004},{"original_title": "My Spy (2020)", "title": "My Spy", "media_type": "movie", "year": 2020},{"original_title": "My Spy (2024)", "title": "My Spy", "media_type": "movie", "year": 2024},{"original_title": "Yaariayan (2014)", "title": "Yaariayan", "media_type": "movie", "year": 2014},{"original_title": "Yaariyan 2 (2023)", "title": "Yaariyan 2", "media_type": "movie", "year": 2023},]asyncio.run(process_entries(entries))async def process_entries(entries):for entry in entries:await fetch_and_cache_json(entry['original_title'], entry['title'], entry['media_type'], entry['year'])if __name__ == "__main__":main()
app.py+2-2
tvdb.py+61-45