webscout 1.2.5__tar.gz → 1.2.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (40) hide show
  1. {webscout-1.2.5 → webscout-1.2.6}/PKG-INFO +52 -4
  2. {webscout-1.2.5 → webscout-1.2.6}/README.md +50 -2
  3. {webscout-1.2.5 → webscout-1.2.6}/setup.py +2 -2
  4. {webscout-1.2.5 → webscout-1.2.6}/webscout/AI.py +1 -1
  5. {webscout-1.2.5 → webscout-1.2.6}/webscout/__init__.py +2 -0
  6. webscout-1.2.6/webscout/transcriber.py +498 -0
  7. webscout-1.2.6/webscout/version.py +2 -0
  8. {webscout-1.2.5 → webscout-1.2.6}/webscout.egg-info/PKG-INFO +52 -4
  9. {webscout-1.2.5 → webscout-1.2.6}/webscout.egg-info/SOURCES.txt +1 -0
  10. webscout-1.2.5/webscout/version.py +0 -2
  11. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/__init__.py +0 -0
  12. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/documents/__init__.py +0 -0
  13. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/documents/query_results_extractor.py +0 -0
  14. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/documents/webpage_content_extractor.py +0 -0
  15. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/networks/__init__.py +0 -0
  16. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/networks/filepath_converter.py +0 -0
  17. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/networks/google_searcher.py +0 -0
  18. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/networks/network_configs.py +0 -0
  19. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/networks/webpage_fetcher.py +0 -0
  20. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/utilsdw/__init__.py +0 -0
  21. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/utilsdw/enver.py +0 -0
  22. {webscout-1.2.5 → webscout-1.2.6}/DeepWEBS/utilsdw/logger.py +0 -0
  23. {webscout-1.2.5 → webscout-1.2.6}/LICENSE.md +0 -0
  24. {webscout-1.2.5 → webscout-1.2.6}/setup.cfg +0 -0
  25. {webscout-1.2.5 → webscout-1.2.6}/webscout/AIbase.py +0 -0
  26. {webscout-1.2.5 → webscout-1.2.6}/webscout/AIutel.py +0 -0
  27. {webscout-1.2.5 → webscout-1.2.6}/webscout/DWEBS.py +0 -0
  28. {webscout-1.2.5 → webscout-1.2.6}/webscout/HelpingAI.py +0 -0
  29. {webscout-1.2.5 → webscout-1.2.6}/webscout/LLM.py +0 -0
  30. {webscout-1.2.5 → webscout-1.2.6}/webscout/__main__.py +0 -0
  31. {webscout-1.2.5 → webscout-1.2.6}/webscout/cli.py +0 -0
  32. {webscout-1.2.5 → webscout-1.2.6}/webscout/exceptions.py +0 -0
  33. {webscout-1.2.5 → webscout-1.2.6}/webscout/models.py +0 -0
  34. {webscout-1.2.5 → webscout-1.2.6}/webscout/utils.py +0 -0
  35. {webscout-1.2.5 → webscout-1.2.6}/webscout/webscout_search.py +0 -0
  36. {webscout-1.2.5 → webscout-1.2.6}/webscout/webscout_search_async.py +0 -0
  37. {webscout-1.2.5 → webscout-1.2.6}/webscout.egg-info/dependency_links.txt +0 -0
  38. {webscout-1.2.5 → webscout-1.2.6}/webscout.egg-info/entry_points.txt +0 -0
  39. {webscout-1.2.5 → webscout-1.2.6}/webscout.egg-info/requires.txt +0 -0
  40. {webscout-1.2.5 → webscout-1.2.6}/webscout.egg-info/top_level.txt +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: webscout
3
- Version: 1.2.5
4
- Summary: Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
3
+ Version: 1.2.6
4
+ Summary: Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
5
5
  Author: OEvortex
6
6
  Author-email: helpingai5@gmail.com
7
7
  License: HelpingAI Simplified Universal License
@@ -56,8 +56,7 @@ Requires-Dist: pytest>=7.4.2; extra == "dev"
56
56
  <a href="#"><img alt="Python version" src="https://img.shields.io/pypi/pyversions/webscout"/></a>
57
57
  <a href="https://pepy.tech/project/webscout"><img alt="Downloads" src="https://static.pepy.tech/badge/webscout"></a>
58
58
 
59
- Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
60
- Also containes AI models that you can use
59
+ Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
61
60
 
62
61
 
63
62
  ## Table of Contents
@@ -68,6 +67,7 @@ Also containes AI models that you can use
68
67
  - [CLI version of webscout.AI](#cli-version-of-webscoutai)
69
68
  - [CLI to use LLM](#cli-to-use-llm)
70
69
  - [Regions](#regions)
70
+ - [Transcriber](#transcriber)
71
71
  - [DeepWEBS: Advanced Web Searches](#deepwebs-advanced-web-searches)
72
72
  - [Activating DeepWEBS](#activating-deepwebs)
73
73
  - [Point to remember before using `DeepWEBS`](#point-to-remember-before-using-deepwebs)
@@ -218,7 +218,55 @@ ___
218
218
  [Go To TOP](#TOP)
219
219
 
220
220
 
221
+ ## Transcriber
222
+ The transcriber function in webscout is a handy tool that transcribes YouTube videos. Here's an example code demonstrating its usage:
223
+ ```python
224
+ import sys
225
+ from webscout import transcriber
226
+
227
+ def extract_transcript(video_id):
228
+ """Extracts the transcript from a YouTube video."""
229
+ try:
230
+ transcript_list = transcriber.list_transcripts(video_id)
231
+ for transcript in transcript_list:
232
+ transcript_text_list = transcript.fetch()
233
+ lang = transcript.language
234
+ transcript_text = ""
235
+ if transcript.language_code == 'en':
236
+ for line in transcript_text_list:
237
+ transcript_text += " " + line["text"]
238
+ return transcript_text
239
+ elif transcript.is_translatable:
240
+ english_transcript_list = transcript.translate('en').fetch()
241
+ for line in english_transcript_list:
242
+ transcript_text += " " + line["text"]
243
+ return transcript_text
244
+ print("Transcript extraction failed. Please check the video URL.")
245
+ except Exception as e:
246
+ print(f"Error: {e}")
221
247
 
248
+ def main():
249
+ video_url = input("Enter the video link: ")
250
+
251
+ if video_url:
252
+ video_id = video_url.split("=")[1]
253
+ print("Video URL:", video_url)
254
+ submit = input("Press 'Enter' to get the transcript or type 'exit' to quit: ")
255
+ if submit == '':
256
+ print("Extracting Transcript...")
257
+ transcript = extract_transcript(video_id)
258
+ print('Transcript:')
259
+ print(transcript)
260
+ print("__________________________________________________________________________________")
261
+ elif submit.lower() == 'exit':
262
+ print("Exiting...")
263
+ sys.exit()
264
+ else:
265
+ print("Invalid input. Please try again.")
266
+
267
+ if __name__ == "__main__":
268
+ main()
269
+ ```
222
270
  ## DeepWEBS: Advanced Web Searches
223
271
 
224
272
  `DeepWEBS` is a standalone feature designed to perform advanced web searches with enhanced capabilities. It is particularly powerful in extracting relevant information directly from webpages and Search engine, focusing exclusively on text (web) searches. Unlike the `WEBS` , which provides a broader range of search functionalities, `DeepWEBS` is specifically tailored for in-depth web searches.
@@ -4,8 +4,7 @@
4
4
  <a href="#"><img alt="Python version" src="https://img.shields.io/pypi/pyversions/webscout"/></a>
5
5
  <a href="https://pepy.tech/project/webscout"><img alt="Downloads" src="https://static.pepy.tech/badge/webscout"></a>
6
6
 
7
- Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
8
- Also containes AI models that you can use
7
+ Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
9
8
 
10
9
 
11
10
  ## Table of Contents
@@ -16,6 +15,7 @@ Also containes AI models that you can use
16
15
  - [CLI version of webscout.AI](#cli-version-of-webscoutai)
17
16
  - [CLI to use LLM](#cli-to-use-llm)
18
17
  - [Regions](#regions)
18
+ - [Transcriber](#transcriber)
19
19
  - [DeepWEBS: Advanced Web Searches](#deepwebs-advanced-web-searches)
20
20
  - [Activating DeepWEBS](#activating-deepwebs)
21
21
  - [Point to remember before using `DeepWEBS`](#point-to-remember-before-using-deepwebs)
@@ -166,7 +166,55 @@ ___
166
166
  [Go To TOP](#TOP)
167
167
 
168
168
 
169
+ ## Transcriber
170
+ The transcriber function in webscout is a handy tool that transcribes YouTube videos. Here's an example code demonstrating its usage:
171
+ ```python
172
+ import sys
173
+ from webscout import transcriber
174
+
175
+ def extract_transcript(video_id):
176
+ """Extracts the transcript from a YouTube video."""
177
+ try:
178
+ transcript_list = transcriber.list_transcripts(video_id)
179
+ for transcript in transcript_list:
180
+ transcript_text_list = transcript.fetch()
181
+ lang = transcript.language
182
+ transcript_text = ""
183
+ if transcript.language_code == 'en':
184
+ for line in transcript_text_list:
185
+ transcript_text += " " + line["text"]
186
+ return transcript_text
187
+ elif transcript.is_translatable:
188
+ english_transcript_list = transcript.translate('en').fetch()
189
+ for line in english_transcript_list:
190
+ transcript_text += " " + line["text"]
191
+ return transcript_text
192
+ print("Transcript extraction failed. Please check the video URL.")
193
+ except Exception as e:
194
+ print(f"Error: {e}")
169
195
 
196
+ def main():
197
+ video_url = input("Enter the video link: ")
198
+
199
+ if video_url:
200
+ video_id = video_url.split("=")[1]
201
+ print("Video URL:", video_url)
202
+ submit = input("Press 'Enter' to get the transcript or type 'exit' to quit: ")
203
+ if submit == '':
204
+ print("Extracting Transcript...")
205
+ transcript = extract_transcript(video_id)
206
+ print('Transcript:')
207
+ print(transcript)
208
+ print("__________________________________________________________________________________")
209
+ elif submit.lower() == 'exit':
210
+ print("Exiting...")
211
+ sys.exit()
212
+ else:
213
+ print("Invalid input. Please try again.")
214
+
215
+ if __name__ == "__main__":
216
+ main()
217
+ ```
170
218
  ## DeepWEBS: Advanced Web Searches
171
219
 
172
220
  `DeepWEBS` is a standalone feature designed to perform advanced web searches with enhanced capabilities. It is particularly powerful in extracting relevant information directly from webpages and Search engine, focusing exclusively on text (web) searches. Unlike the `WEBS` , which provides a broader range of search functionalities, `DeepWEBS` is specifically tailored for in-depth web searches.
@@ -9,8 +9,8 @@ with open("README.md", encoding="utf-8") as f:
9
9
 
10
10
  setup(
11
11
  name="webscout",
12
- version="1.2.5",
13
- description="Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models",
12
+ version="1.2.6",
13
+ description="Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos",
14
14
  long_description=README,
15
15
  long_description_content_type="text/markdown",
16
16
  author="OEvortex",
@@ -25,7 +25,7 @@ from webscout.AIbase import Provider
25
25
  from Helpingai_T2 import Perplexity
26
26
  from typing import Any
27
27
  import logging
28
- #------------------------------------------------------OpenGPT-----------------------------------------------------------
28
+ #------------------------------------------------------KOBOLDAI-----------------------------------------------------------
29
29
  class KOBOLDAI(Provider):
30
30
  def __init__(
31
31
  self,
@@ -10,6 +10,8 @@ from .webscout_search_async import AsyncWEBS
10
10
  from .version import __version__
11
11
  from .DWEBS import DeepWEBS
12
12
  from .AIutel import appdir
13
+ from .transcriber import transcriber
14
+
13
15
 
14
16
  __all__ = ["WEBS", "AsyncWEBS", "__version__", "cli"]
15
17
 
@@ -0,0 +1,498 @@
1
+ import requests
2
+ import http.cookiejar as cookiejar
3
+ import sys
4
+ import json
5
+ from xml.etree import ElementTree
6
+ import re
7
+ from requests import HTTPError
8
+ import html.parser
9
+
10
+ html_parser = html.parser.HTMLParser()
11
+ import html
12
+
13
+ def unescape(string):
14
+ return html.unescape(string)
15
+ WATCH_URL = 'https://www.youtube.com/watch?v={video_id}'
16
+
17
+ class TranscriptRetrievalError(Exception):
18
+ """
19
+ Base class for exceptions raised when a transcript cannot be retrieved.
20
+ """
21
+ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!'
22
+ CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}'
23
+ CAUSE_MESSAGE = ''
24
+ GITHUB_REFERRAL = (
25
+ '\n\nIf you are sure that the described cause is not responsible for this error '
26
+ 'and that a transcript should be retrievable, please create an issue at '
27
+ 'https://github.com/OE-LUCIFER/Webscout/issues. '
28
+ 'Please add which version of youtube_transcript_api you are using '
29
+ 'and provide the information needed to replicate the error. '
30
+ 'Also make sure that there are no open issues which already describe your problem!'
31
+ )
32
+
33
+ def __init__(self, video_id):
34
+ self.video_id = video_id
35
+ super(TranscriptRetrievalError, self).__init__(self._build_error_message())
36
+
37
+ def _build_error_message(self):
38
+ cause = self.cause
39
+ error_message = self.ERROR_MESSAGE.format(video_url=WATCH_URL.format(video_id=self.video_id))
40
+
41
+ if cause:
42
+ error_message += self.CAUSE_MESSAGE_INTRO.format(cause=cause) + self.GITHUB_REFERRAL
43
+
44
+ return error_message
45
+
46
+ @property
47
+ def cause(self):
48
+ return self.CAUSE_MESSAGE
49
+
50
+ class YouTubeRequestFailedError(TranscriptRetrievalError):
51
+ CAUSE_MESSAGE = 'Request to YouTube failed: {reason}'
52
+
53
+ def __init__(self, video_id, http_error):
54
+ self.reason = str(http_error)
55
+ super(YouTubeRequestFailedError, self).__init__(video_id)
56
+
57
+ @property
58
+ def cause(self):
59
+ return self.CAUSE_MESSAGE.format(reason=self.reason)
60
+
61
+ class VideoUnavailableError(TranscriptRetrievalError):
62
+ CAUSE_MESSAGE = 'The video is no longer available'
63
+
64
+ class InvalidVideoIdError(TranscriptRetrievalError):
65
+ CAUSE_MESSAGE = (
66
+ 'You provided an invalid video id. Make sure you are using the video id and NOT the url!\n\n'
67
+ 'Do NOT run: `YouTubeTranscriptApi.get_transcript("https://www.youtube.com/watch?v=1234")`\n'
68
+ 'Instead run: `YouTubeTranscriptApi.get_transcript("1234")`'
69
+ )
70
+
71
+ class TooManyRequestsError(TranscriptRetrievalError):
72
+ CAUSE_MESSAGE = (
73
+ 'YouTube is receiving too many requests from this IP and now requires solving a captcha to continue. '
74
+ 'One of the following things can be done to work around this:\n\
75
+ - Manually solve the captcha in a browser and export the cookie. '
76
+ 'Read here how to use that cookie with '
77
+ 'youtube-transcript-api: https://github.com/jdepoix/youtube-transcript-api#cookies\n\
78
+ - Use a different IP address\n\
79
+ - Wait until the ban on your IP has been lifted'
80
+ )
81
+
82
+ class TranscriptsDisabledError(TranscriptRetrievalError):
83
+ CAUSE_MESSAGE = 'Subtitles are disabled for this video'
84
+
85
+ class NoTranscriptAvailableError(TranscriptRetrievalError):
86
+ CAUSE_MESSAGE = 'No transcripts are available for this video'
87
+
88
+ class NotTranslatableError(TranscriptRetrievalError):
89
+ CAUSE_MESSAGE = 'The requested language is not translatable'
90
+
91
+ class TranslationLanguageNotAvailableError(TranscriptRetrievalError):
92
+ CAUSE_MESSAGE = 'The requested translation language is not available'
93
+
94
+ class CookiePathInvalidError(TranscriptRetrievalError):
95
+ CAUSE_MESSAGE = 'The provided cookie file was unable to be loaded'
96
+
97
+ class CookiesInvalidError(TranscriptRetrievalError):
98
+ CAUSE_MESSAGE = 'The cookies provided are not valid (may have expired)'
99
+
100
+ class FailedToCreateConsentCookieError(TranscriptRetrievalError):
101
+ CAUSE_MESSAGE = 'Failed to automatically give consent to saving cookies'
102
+
103
+ class NoTranscriptFoundError(TranscriptRetrievalError):
104
+ CAUSE_MESSAGE = (
105
+ 'No transcripts were found for any of the requested language codes: {requested_language_codes}\n\n'
106
+ '{transcript_data}'
107
+ )
108
+
109
+ def __init__(self, video_id, requested_language_codes, transcript_data):
110
+ self._requested_language_codes = requested_language_codes
111
+ self._transcript_data = transcript_data
112
+ super(NoTranscriptFoundError, self).__init__(video_id)
113
+
114
+ @property
115
+ def cause(self):
116
+ return self.CAUSE_MESSAGE.format(
117
+ requested_language_codes=self._requested_language_codes,
118
+ transcript_data=str(self._transcript_data),
119
+ )
120
+
121
+
122
+
123
+ def _raise_http_errors(response, video_id):
124
+ try:
125
+ response.raise_for_status()
126
+ return response
127
+ except HTTPError as error:
128
+ raise YouTubeRequestFailedError(error, video_id)
129
+
130
+
131
+ class TranscriptListFetcher(object):
132
+ def __init__(self, http_client):
133
+ self._http_client = http_client
134
+
135
+ def fetch(self, video_id):
136
+ return TranscriptList.build(
137
+ self._http_client,
138
+ video_id,
139
+ self._extract_captions_json(self._fetch_video_html(video_id), video_id),
140
+ )
141
+
142
+ def _extract_captions_json(self, html, video_id):
143
+ splitted_html = html.split('"captions":')
144
+
145
+ if len(splitted_html) <= 1:
146
+ if video_id.startswith('http://') or video_id.startswith('https://'):
147
+ raise InvalidVideoIdError(video_id)
148
+ if 'class="g-recaptcha"' in html:
149
+ raise TooManyRequestsError(video_id)
150
+ if '"playabilityStatus":' not in html:
151
+ raise VideoUnavailableError(video_id)
152
+
153
+ raise TranscriptsDisabledError(video_id)
154
+
155
+ captions_json = json.loads(
156
+ splitted_html[1].split(',"videoDetails')[0].replace('\n', '')
157
+ ).get('playerCaptionsTracklistRenderer')
158
+ if captions_json is None:
159
+ raise TranscriptsDisabledError(video_id)
160
+
161
+ if 'captionTracks' not in captions_json:
162
+ raise TranscriptsDisabledError(video_id)
163
+
164
+ return captions_json
165
+
166
+ def _create_consent_cookie(self, html, video_id):
167
+ match = re.search('name="v" value="(.*?)"', html)
168
+ if match is None:
169
+ raise FailedToCreateConsentCookieError(video_id)
170
+ self._http_client.cookies.set('CONSENT', 'YES+' + match.group(1), domain='.youtube.com')
171
+
172
+ def _fetch_video_html(self, video_id):
173
+ html = self._fetch_html(video_id)
174
+ if 'action="https://consent.youtube.com/s"' in html:
175
+ self._create_consent_cookie(html, video_id)
176
+ html = self._fetch_html(video_id)
177
+ if 'action="https://consent.youtube.com/s"' in html:
178
+ raise FailedToCreateConsentCookieError(video_id)
179
+ return html
180
+
181
+ def _fetch_html(self, video_id):
182
+ response = self._http_client.get(WATCH_URL.format(video_id=video_id), headers={'Accept-Language': 'en-US'})
183
+ return unescape(_raise_http_errors(response, video_id).text)
184
+
185
+
186
+ class TranscriptList(object):
187
+ """
188
+ This object represents a list of transcripts. It can be iterated over to list all transcripts which are available
189
+ for a given YouTube video. Also it provides functionality to search for a transcript in a given language.
190
+ """
191
+
192
+ def __init__(self, video_id, manually_created_transcripts, generated_transcripts, translation_languages):
193
+ """
194
+ The constructor is only for internal use. Use the static build method instead.
195
+
196
+ :param video_id: the id of the video this TranscriptList is for
197
+ :type video_id: str
198
+ :param manually_created_transcripts: dict mapping language codes to the manually created transcripts
199
+ :type manually_created_transcripts: dict[str, Transcript]
200
+ :param generated_transcripts: dict mapping language codes to the generated transcripts
201
+ :type generated_transcripts: dict[str, Transcript]
202
+ :param translation_languages: list of languages which can be used for translatable languages
203
+ :type translation_languages: list[dict[str, str]]
204
+ """
205
+ self.video_id = video_id
206
+ self._manually_created_transcripts = manually_created_transcripts
207
+ self._generated_transcripts = generated_transcripts
208
+ self._translation_languages = translation_languages
209
+
210
+ @staticmethod
211
+ def build(http_client, video_id, captions_json):
212
+ """
213
+ Factory method for TranscriptList.
214
+
215
+ :param http_client: http client which is used to make the transcript retrieving http calls
216
+ :type http_client: requests.Session
217
+ :param video_id: the id of the video this TranscriptList is for
218
+ :type video_id: str
219
+ :param captions_json: the JSON parsed from the YouTube pages static HTML
220
+ :type captions_json: dict
221
+ :return: the created TranscriptList
222
+ :rtype TranscriptList:
223
+ """
224
+ translation_languages = [
225
+ {
226
+ 'language': translation_language['languageName']['simpleText'],
227
+ 'language_code': translation_language['languageCode'],
228
+ } for translation_language in captions_json.get('translationLanguages', [])
229
+ ]
230
+
231
+ manually_created_transcripts = {}
232
+ generated_transcripts = {}
233
+
234
+ for caption in captions_json['captionTracks']:
235
+ if caption.get('kind', '') == 'asr':
236
+ transcript_dict = generated_transcripts
237
+ else:
238
+ transcript_dict = manually_created_transcripts
239
+
240
+ transcript_dict[caption['languageCode']] = Transcript(
241
+ http_client,
242
+ video_id,
243
+ caption['baseUrl'],
244
+ caption['name']['simpleText'],
245
+ caption['languageCode'],
246
+ caption.get('kind', '') == 'asr',
247
+ translation_languages if caption.get('isTranslatable', False) else [],
248
+ )
249
+
250
+ return TranscriptList(
251
+ video_id,
252
+ manually_created_transcripts,
253
+ generated_transcripts,
254
+ translation_languages,
255
+ )
256
+
257
+ def __iter__(self):
258
+ return iter(list(self._manually_created_transcripts.values()) + list(self._generated_transcripts.values()))
259
+
260
+ def find_transcript(self, language_codes):
261
+ """
262
+ Finds a transcript for a given language code. Manually created transcripts are returned first and only if none
263
+ are found, generated transcripts are used. If you only want generated transcripts use
264
+ `find_manually_created_transcript` instead.
265
+
266
+ :param language_codes: A list of language codes in a descending priority. For example, if this is set to
267
+ ['de', 'en'] it will first try to fetch the german transcript (de) and then fetch the english transcript (en) if
268
+ it fails to do so.
269
+ :type languages: list[str]
270
+ :return: the found Transcript
271
+ :rtype Transcript:
272
+ :raises: NoTranscriptFound
273
+ """
274
+ return self._find_transcript(language_codes, [self._manually_created_transcripts, self._generated_transcripts])
275
+
276
+ def find_generated_transcript(self, language_codes):
277
+ """
278
+ Finds an automatically generated transcript for a given language code.
279
+
280
+ :param language_codes: A list of language codes in a descending priority. For example, if this is set to
281
+ ['de', 'en'] it will first try to fetch the german transcript (de) and then fetch the english transcript (en) if
282
+ it fails to do so.
283
+ :type languages: list[str]
284
+ :return: the found Transcript
285
+ :rtype Transcript:
286
+ :raises: NoTranscriptFound
287
+ """
288
+ return self._find_transcript(language_codes, [self._generated_transcripts])
289
+
290
+ def find_manually_created_transcript(self, language_codes):
291
+ """
292
+ Finds a manually created transcript for a given language code.
293
+
294
+ :param language_codes: A list of language codes in a descending priority. For example, if this is set to
295
+ ['de', 'en'] it will first try to fetch the german transcript (de) and then fetch the english transcript (en) if
296
+ it fails to do so.
297
+ :type languages: list[str]
298
+ :return: the found Transcript
299
+ :rtype Transcript:
300
+ :raises: NoTranscriptFound
301
+ """
302
+ return self._find_transcript(language_codes, [self._manually_created_transcripts])
303
+
304
+ def _find_transcript(self, language_codes, transcript_dicts):
305
+ for language_code in language_codes:
306
+ for transcript_dict in transcript_dicts:
307
+ if language_code in transcript_dict:
308
+ return transcript_dict[language_code]
309
+
310
+ raise NoTranscriptFoundError(
311
+ self.video_id,
312
+ language_codes,
313
+ self
314
+ )
315
+
316
+ def __str__(self):
317
+ return (
318
+ 'For this video ({video_id}) transcripts are available in the following languages:\n\n'
319
+ '(MANUALLY CREATED)\n'
320
+ '{available_manually_created_transcript_languages}\n\n'
321
+ '(GENERATED)\n'
322
+ '{available_generated_transcripts}\n\n'
323
+ '(TRANSLATION LANGUAGES)\n'
324
+ '{available_translation_languages}'
325
+ ).format(
326
+ video_id=self.video_id,
327
+ available_manually_created_transcript_languages=self._get_language_description(
328
+ str(transcript) for transcript in self._manually_created_transcripts.values()
329
+ ),
330
+ available_generated_transcripts=self._get_language_description(
331
+ str(transcript) for transcript in self._generated_transcripts.values()
332
+ ),
333
+ available_translation_languages=self._get_language_description(
334
+ '{language_code} ("{language}")'.format(
335
+ language=translation_language['language'],
336
+ language_code=translation_language['language_code'],
337
+ ) for translation_language in self._translation_languages
338
+ )
339
+ )
340
+
341
+ def _get_language_description(self, transcript_strings):
342
+ description = '\n'.join(' - {transcript}'.format(transcript=transcript) for transcript in transcript_strings)
343
+ return description if description else 'None'
344
+
345
+
346
+ class Transcript(object):
347
+ def __init__(self, http_client, video_id, url, language, language_code, is_generated, translation_languages):
348
+ """
349
+ You probably don't want to initialize this directly. Usually you'll access Transcript objects using a
350
+ TranscriptList.
351
+
352
+ :param http_client: http client which is used to make the transcript retrieving http calls
353
+ :type http_client: requests.Session
354
+ :param video_id: the id of the video this TranscriptList is for
355
+ :type video_id: str
356
+ :param url: the url which needs to be called to fetch the transcript
357
+ :param language: the name of the language this transcript uses
358
+ :param language_code:
359
+ :param is_generated:
360
+ :param translation_languages:
361
+ """
362
+ self._http_client = http_client
363
+ self.video_id = video_id
364
+ self._url = url
365
+ self.language = language
366
+ self.language_code = language_code
367
+ self.is_generated = is_generated
368
+ self.translation_languages = translation_languages
369
+ self._translation_languages_dict = {
370
+ translation_language['language_code']: translation_language['language']
371
+ for translation_language in translation_languages
372
+ }
373
+
374
+ def fetch(self, preserve_formatting=False):
375
+ """
376
+ Loads the actual transcript data.
377
+ :param preserve_formatting: whether to keep select HTML text formatting
378
+ :type preserve_formatting: bool
379
+ :return: a list of dictionaries containing the 'text', 'start' and 'duration' keys
380
+ :rtype [{'text': str, 'start': float, 'end': float}]:
381
+ """
382
+ response = self._http_client.get(self._url, headers={'Accept-Language': 'en-US'})
383
+ return _TranscriptParser(preserve_formatting=preserve_formatting).parse(
384
+ _raise_http_errors(response, self.video_id).text,
385
+ )
386
+
387
+ def __str__(self):
388
+ return '{language_code} ("{language}"){translation_description}'.format(
389
+ language=self.language,
390
+ language_code=self.language_code,
391
+ translation_description='[TRANSLATABLE]' if self.is_translatable else ''
392
+ )
393
+
394
+ @property
395
+ def is_translatable(self):
396
+ return len(self.translation_languages) > 0
397
+
398
+ def translate(self, language_code):
399
+ if not self.is_translatable:
400
+ raise NotTranslatableError(self.video_id)
401
+
402
+ if language_code not in self._translation_languages_dict:
403
+ raise TranslationLanguageNotAvailableError(self.video_id)
404
+
405
+ return Transcript(
406
+ self._http_client,
407
+ self.video_id,
408
+ '{url}&tlang={language_code}'.format(url=self._url, language_code=language_code),
409
+ self._translation_languages_dict[language_code],
410
+ language_code,
411
+ True,
412
+ [],
413
+ )
414
+
415
+
416
+ class _TranscriptParser(object):
417
+ _FORMATTING_TAGS = [
418
+ 'strong', # important
419
+ 'em', # emphasized
420
+ 'b', # bold
421
+ 'i', # italic
422
+ 'mark', # marked
423
+ 'small', # smaller
424
+ 'del', # deleted
425
+ 'ins', # inserted
426
+ 'sub', # subscript
427
+ 'sup', # superscript
428
+ ]
429
+
430
+ def __init__(self, preserve_formatting=False):
431
+ self._html_regex = self._get_html_regex(preserve_formatting)
432
+
433
+ def _get_html_regex(self, preserve_formatting):
434
+ if preserve_formatting:
435
+ formats_regex = '|'.join(self._FORMATTING_TAGS)
436
+ formats_regex = r'<\/?(?!\/?(' + formats_regex + r')\b).*?\b>'
437
+ html_regex = re.compile(formats_regex, re.IGNORECASE)
438
+ else:
439
+ html_regex = re.compile(r'<[^>]*>', re.IGNORECASE)
440
+ return html_regex
441
+
442
+ def parse(self, plain_data):
443
+ return [
444
+ {
445
+ 'text': re.sub(self._html_regex, '', unescape(xml_element.text)),
446
+ 'start': float(xml_element.attrib['start']),
447
+ 'duration': float(xml_element.attrib.get('dur', '0.0')),
448
+ }
449
+ for xml_element in ElementTree.fromstring(plain_data)
450
+ if xml_element.text is not None
451
+ ]
452
+
453
+ WATCH_URL = 'https://www.youtube.com/watch?v={video_id}'
454
+
455
+ class transcriber(object):
456
+ @classmethod
457
+ def list_transcripts(cls, video_id, proxies=None, cookies=None):
458
+ with requests.Session() as http_client:
459
+ if cookies:
460
+ http_client.cookies = cls._load_cookies(cookies, video_id)
461
+ http_client.proxies = proxies if proxies else {}
462
+ return TranscriptListFetcher(http_client).fetch(video_id)
463
+
464
+ @classmethod
465
+ def get_transcripts(cls, video_ids, languages=('en',), continue_after_error=False, proxies=None,
466
+ cookies=None, preserve_formatting=False):
467
+
468
+ assert isinstance(video_ids, list), "`video_ids` must be a list of strings"
469
+
470
+ data = {}
471
+ unretrievable_videos = []
472
+
473
+ for video_id in video_ids:
474
+ try:
475
+ data[video_id] = cls.get_transcript(video_id, languages, proxies, cookies, preserve_formatting)
476
+ except Exception as exception:
477
+ if not continue_after_error:
478
+ raise exception
479
+
480
+ unretrievable_videos.append(video_id)
481
+
482
+ return data, unretrievable_videos
483
+
484
+ @classmethod
485
+ def get_transcript(cls, video_id, languages=('en',), proxies=None, cookies=None, preserve_formatting=False):
486
+ assert isinstance(video_id, str), "`video_id` must be a string"
487
+ return cls.list_transcripts(video_id, proxies, cookies).find_transcript(languages).fetch(preserve_formatting=preserve_formatting)
488
+
489
+ @classmethod
490
+ def _load_cookies(cls, cookies, video_id):
491
+ try:
492
+ cookie_jar = cookiejar.MozillaCookieJar()
493
+ cookie_jar.load(cookies)
494
+ if not cookie_jar:
495
+ raise CookiesInvalidError(video_id)
496
+ return cookie_jar
497
+ except:
498
+ raise CookiePathInvalidError(video_id)
@@ -0,0 +1,2 @@
1
+ __version__ = "1.2.7"
2
+
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: webscout
3
- Version: 1.2.5
4
- Summary: Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
3
+ Version: 1.2.6
4
+ Summary: Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
5
5
  Author: OEvortex
6
6
  Author-email: helpingai5@gmail.com
7
7
  License: HelpingAI Simplified Universal License
@@ -56,8 +56,7 @@ Requires-Dist: pytest>=7.4.2; extra == "dev"
56
56
  <a href="#"><img alt="Python version" src="https://img.shields.io/pypi/pyversions/webscout"/></a>
57
57
  <a href="https://pepy.tech/project/webscout"><img alt="Downloads" src="https://static.pepy.tech/badge/webscout"></a>
58
58
 
59
- Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models
60
- Also containes AI models that you can use
59
+ Search for words, documents, images, videos, news, maps and text translation using the Google, DuckDuckGo.com, yep.com, phind.com, you.com, etc Also containes AI models and now can transcribe yt videos
61
60
 
62
61
 
63
62
  ## Table of Contents
@@ -68,6 +67,7 @@ Also containes AI models that you can use
68
67
  - [CLI version of webscout.AI](#cli-version-of-webscoutai)
69
68
  - [CLI to use LLM](#cli-to-use-llm)
70
69
  - [Regions](#regions)
70
+ - [Transcriber](#transcriber)
71
71
  - [DeepWEBS: Advanced Web Searches](#deepwebs-advanced-web-searches)
72
72
  - [Activating DeepWEBS](#activating-deepwebs)
73
73
  - [Point to remember before using `DeepWEBS`](#point-to-remember-before-using-deepwebs)
@@ -218,7 +218,55 @@ ___
218
218
  [Go To TOP](#TOP)
219
219
 
220
220
 
221
+ ## Transcriber
222
+ The transcriber function in webscout is a handy tool that transcribes YouTube videos. Here's an example code demonstrating its usage:
223
+ ```python
224
+ import sys
225
+ from webscout import transcriber
226
+
227
+ def extract_transcript(video_id):
228
+ """Extracts the transcript from a YouTube video."""
229
+ try:
230
+ transcript_list = transcriber.list_transcripts(video_id)
231
+ for transcript in transcript_list:
232
+ transcript_text_list = transcript.fetch()
233
+ lang = transcript.language
234
+ transcript_text = ""
235
+ if transcript.language_code == 'en':
236
+ for line in transcript_text_list:
237
+ transcript_text += " " + line["text"]
238
+ return transcript_text
239
+ elif transcript.is_translatable:
240
+ english_transcript_list = transcript.translate('en').fetch()
241
+ for line in english_transcript_list:
242
+ transcript_text += " " + line["text"]
243
+ return transcript_text
244
+ print("Transcript extraction failed. Please check the video URL.")
245
+ except Exception as e:
246
+ print(f"Error: {e}")
221
247
 
248
+ def main():
249
+ video_url = input("Enter the video link: ")
250
+
251
+ if video_url:
252
+ video_id = video_url.split("=")[1]
253
+ print("Video URL:", video_url)
254
+ submit = input("Press 'Enter' to get the transcript or type 'exit' to quit: ")
255
+ if submit == '':
256
+ print("Extracting Transcript...")
257
+ transcript = extract_transcript(video_id)
258
+ print('Transcript:')
259
+ print(transcript)
260
+ print("__________________________________________________________________________________")
261
+ elif submit.lower() == 'exit':
262
+ print("Exiting...")
263
+ sys.exit()
264
+ else:
265
+ print("Invalid input. Please try again.")
266
+
267
+ if __name__ == "__main__":
268
+ main()
269
+ ```
222
270
  ## DeepWEBS: Advanced Web Searches
223
271
 
224
272
  `DeepWEBS` is a standalone feature designed to perform advanced web searches with enhanced capabilities. It is particularly powerful in extracting relevant information directly from webpages and Search engine, focusing exclusively on text (web) searches. Unlike the `WEBS` , which provides a broader range of search functionalities, `DeepWEBS` is specifically tailored for in-depth web searches.
@@ -24,6 +24,7 @@ webscout/__main__.py
24
24
  webscout/cli.py
25
25
  webscout/exceptions.py
26
26
  webscout/models.py
27
+ webscout/transcriber.py
27
28
  webscout/utils.py
28
29
  webscout/version.py
29
30
  webscout/webscout_search.py
@@ -1,2 +0,0 @@
1
- __version__ = "1.2.5"
2
-
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes