feat: search suggestions

This commit is contained in:
2025-09-07 05:05:11 +02:00
parent 15d2de5228
commit 37e932956d
2 changed files with 36 additions and 2 deletions

View File

@@ -343,3 +343,36 @@ def WEBextractSearchResults(search_query: str) -> list:
results = safeTraverse(results, ["contents", "twoColumnSearchResultsRenderer", "primaryContents", "sectionListRenderer", "contents", 0, "itemSectionRenderer", "contents"], default=[])
return results
def WEBgetSearchSuggestions(query: str, previous_query: str = '') -> list:
# Takes in a search query and returns relevant suggestions.
# Can optionally take the previous query but that's rather novel and
# not supported across players nor invidious API itself.
params = {
'ds': 'yt',
'hl': 'en', # host language
'gl': 'us', # geolocation
'client': 'youtube',
'gs_ri': 'youtube',
'q': str(query), # query
'pq': str(previous_query) if previous_query is not None else '' # previous query
}
response = requests.get(
'https://suggestqueries-clients6.youtube.com/complete/search',
params=params,
headers=stage2_headers
)
# can break anytime but hopefully the tiny speed gain will make up for it
results = response.text[23 + len(query):]
results = results[:results.rfind("{") - 1]
results = json.loads(results)
suggestions = []
for result in results:
suggestions.append(result[0])
return {
"query": query,
"suggestions": suggestions
}

View File

@@ -642,8 +642,9 @@ def search(data, req):
if (data[-2].lower() != "search" or data[-1].lower() != "") and data[-1].lower() != "search":
print(f"'{data[-2]}', '{data[-1]}'")
print("search suggestions are not yet supported")
return send(501, {"status": "error", "msg": "search suggestions not supported in this version of ythdd", "data": []})
previous_query = req.args.get('pq')
suggestions = ythdd_extractor.WEBgetSearchSuggestions(search_query, previous_query)
return send(200, suggestions)
results = ythdd_extractor.WEBextractSearchResults(search_query)
results_list = []