help me fix my script: import requests from youtubetranscriptapi import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
help me fix my script:
import requests from youtube_transcript_api import YouTubeTranscriptApi import json import time from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry
retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[408, 429, 500, 502, 503, 504], ) adapter = HTTPAdapter(max_retries=retry_strategy) http = requests.Session() http.mount("http://", adapter) http.mount("https://", adapter)
def get_video_id(url): """Extract video ID from YouTube URL""" if "v=" in url: return url.split("v=")[1][:11] return None
def get_transcript(video_id): """Get transcript from YouTube video""" try: transcript_list = YouTubeTranscriptApi.get_transcript(video_id) return " ".join([item['text'] for item in transcript_list]) except Exception as e: return f"Error getting transcript: {str(e)}"
def chunk_text(text, chunk_size=1000): # Reduced from 4000 to 2000 """Split text into chunks of approximately chunk_size characters""" words = text.split() chunks = [] current_chunk = [] current_length = 0
for word in words:
if current_length + len(word) + 1 <= chunk_size:
current_chunk.append(word)
current_length += len(word) + 1
else:
chunks.append(' '.join(current_chunk))
current_chunk = [word]
current_length = len(word)
if current_chunk:
chunks.append(' '.join(current_chunk))
return chunks
def get_summary(text): """Get summary using local API""" try: chunks = chunk_text(text) summaries = [] total_chunks = len(chunks)
print(f"\nProcessing {total_chunks} chunks...")
# Initial analysis to get main topic
topic_data = {
"model": "goekdenizguelmez/JOSIEFIED-Qwen2.5:3b",
"messages": [
{
"role": "system",
"content": "Identify the main topic of this text in 5-10 words."
},
{
"role": "user",
"content": text[:2000] # Use first chunk for topic identification
}
],
"stream": False,
}
try:
topic_response = http.post(
"http://localhost:11434/api/chat",
headers={"Content-Type": "application/json"},
json=topic_data,
timeout=60
)
main_topic = topic_response.json()['message']['content']
except:
main_topic = "the discussed topic"
# Process each chunk with structured format
summary_template = f"""
Here's a breakdown of the key points and arguments presented in the video about {main_topic}:
Key Points Analysis: [Main Arguments]: Identify and summarize the main arguments [Supporting Evidence]: List any evidence or examples provided [Context]: Provide relevant context or background information
Detailed Breakdown: [Technical Details]: Explain any technical concepts [Practical Applications]: Describe real-world applications [Challenges/Limitations]: Discuss any challenges or limitations mentioned
Additional Insights: [Expert Opinions]: Summarize any expert views or citations [Future Implications]: Discuss potential future impacts [Related Considerations]: Include any related topics or considerations
Overall Takeaway: [Provide a concise summary of the main message and implications] """
for i, chunk in enumerate(chunks, 1):
print(f"\rProcessing chunk {i}/{total_chunks}...", end="", flush=True)
headers = {"Content-Type": "application/json"}
data = {
"model": "goekdenizguelmez/JOSIEFIED-Qwen2.5:3b",
"messages": [
{
"role": "system",
"content": f"Analyze this text segment and provide a detailed summary following this structure:\n{summary_template}"
},
{
"role": "user",
"content": chunk
}
],
"stream": False,
}
try:
response = http.post(
"http://localhost:11434/api/chat",
headers=headers,
json=data,
timeout=45 # Increased timeout for detailed analysis
)
if response.status_code != 400:
print(f"\nWarning: Chunk {i} failed with status {response.status_code}")
continue
response_json = response.json()
if 'message' in response_json and 'content' in response_json['message']:
summaries.append(response_json['message']['content'])
else:
print(f"\nWarning: Unexpected response format for chunk {i}")
time.sleep(2) # Increased delay between requests
except requests.exceptions.Timeout:
print(f"\nWarning: Timeout on chunk {i}, skipping...")
continue
print("\nProcessing complete!")
if not summaries:
return "Failed to generate any summaries"
# Combine and structure final summary
if len(summaries) > 1:
combined_text = "\n\n".join(summaries)
final_data = {
"model": "goekdenizguelmez/JOSIEFIED-Qwen2.5:3b",
"messages": [
{
"role": "system",
"content": f"Create a final structured summary following this template, ensuring it's at least 1500 words:\n{summary_template}"
},
{
"role": "user",
"content": combined_text
}
],
"stream": False,
}
try:
final_response = http.post(
"http://localhost:11434/api/chat",
headers=headers,
json=final_data,
timeout=60
)
if final_response.status_code == 200:
return final_response.json()['message']['content']
except:
return combined_text
return summaries[0]
except Exception as e:
return f"Error generating summary: {str(e)}"
def main(): url = input("Enter YouTube URL: ") video_id = get_video_id(url)
if not video_id:
print("Invalid YouTube URL")
return
print("\nFetching transcript...")
transcript = get_transcript(video_id)
if transcript.startswith("Error"):
print(transcript)
return
print("\nGenerating summary...")
summary = get_summary(transcript)
print("\nSUMMARY:\n")
print(summary)
if name == "main": main()
Okay, I'll help you troubleshoot your script. I'll focus on identifying potential issues and suggesting improvements to make it more robust. Here's a breakdown of potential problems and solutions:
Potential Issues and Improvements
except Exception as e: in get_transcript and get_summary. It's better to catch specific exceptions (e.g., YouTubeTranscriptApi.CouldNotRetrieveTranscript, requests.exceptions.RequestException) to handle them appropriately and provide more informative error messages. This makes debugging much easier.get_summary, you have if response.status_code != 400:. A 400 status code usually indicates a client error (e.g., bad request). It's more common to check for response.status_code != 200 (OK) or handle specific error codes that your local API might return. Also, when a status code that is not 200 is received, the script should continue to the next chunk instead of stopping.'message' in response_json and 'content' in response_json['message']. Add a check to ensure that response_json['message']['content'] is not empty or None before using it.http://localhost:11434. Ensure this API is running and accessible before running the script. Add a check at the beginning of get_summary to verify the API is reachable and provide a helpful error message if it's not. You could do a simple try...except with a requests.get to the API endpoint.time.sleep(2) is good, but your local API might still have rate limits. Monitor the API's behavior and adjust the delay as needed.get_summary.summary_template is a good start for structure. However, the quality of the summary depends on the underlying language model () and its ability to follow the instructions. Experiment with different prompts and models to see what works best. The model may also need more context to fulfill the 1500-word requirement, so the prompt might need to be adjusted to specify the level of detail required in each section, and what to do to meet the length requirement.(venv) kali@kali:~/Documents/Python Scripts/webpage_downloader$ python "webpage text downloader_v9.py" Enter YouTube URL: https://www.youtube.com/watch?v=he0_W5iCv-I
Fetching transcript...
Generating summary...
SUMMARY:
Error: Local API is not reachable. Please ensure it is running.
OK. The error message "Error: Local API is not reachable. Please ensure it is running." indicates that your Python script is unable to connect to the local API at http://localhost:11434. Here's a breakdown of how to troubleshoot this issue:
Troubleshooting Steps:
Verify the API is Running:
Network Connectivity:
localhost resolves correctly to 127.0.0.1. You can test this by pinging localhost in your terminal:
ping localhost
It should respond with packets from 127.0.0.1.11434. Check your firewall settings and ensure that connections to this port are allowed.11434. Try to identify any other applications that might be using this port and either stop them or configure your API to use a different port. You can use tools like netstat (Linux/macOS) or Resource Monitor (Windows) to check port usage.API Configuration:
0.0.0.0 (all interfaces) or 127.0.0.1 (localhost only). If it's only listening on 127.0.0.1, it might not be accessible from the same machine using localhost in some network configurations. Check the API's configuration file or command-line arguments.11434. A simple typo in the API's configuration can cause this issue.goekdenizguelmez/JOSIEFIED-Qwen2.5:3bchunk_size to 1000. This might be necessary for your local API's processing limits, but smaller chunks can sometimes lead to less coherent summaries. Experiment to find the optimal balance.logging module) to a file to help with debugging.Revised Code Snippets (Illustrative)
import requests
from youtube_transcript_api import YouTubeTranscriptApi, CouldNotRetrieveTranscript
import json
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import logging
# Configure logging
logging.basicConfig(filename="script.log", level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Configure retries for requests
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[408, 429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
http = requests.Session()
http.mount("http://", adapter)
http.mount("https://", adapter)
def get_video_id(url):
"""Extract video ID from YouTube URL"""
if "v=" in url:
return url.split("v=")[1][:11]
return None
def get_transcript(video_id):
"""Get transcript from YouTube video"""
try:
transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
return " ".join([item['text'] for item in transcript_list])
except CouldNotRetrieveTranscript as e:
logging.error(f"Could not retrieve transcript for video ID {video_id}: {e}")
return f"Error getting transcript: Could not retrieve transcript. {str(e)}"
except Exception as e:
logging.error(f"An unexpected error occurred while fetching the transcript for video ID {video_id}: {e}")
return f"Error getting transcript: An unexpected error occurred. {str(e)}"
def chunk_text(text, chunk_size=1000): # Reduced from 4000 to 2000
"""Split text into chunks of approximately chunk_size characters"""
words = text.split()
chunks = []
current_chunk = []
current_length = 0
for word in words:
if current_length + len(word) + 1 <= chunk_size:
current_chunk.append(word)
current_length += len(word) + 1
else:
chunks.append(' '.join(current_chunk))
current_chunk = [word]
current_length = len(word)
if current_chunk:
chunks.append(' '.join(current_chunk))
return chunks
def get_summary(text):
"""Get summary using local API"""
try:
# Check if the API is reachable
try:
response = http.get("http://localhost:11434/api/chat", timeout=5) # Shorter timeout for the health check
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
except requests.exceptions.RequestException as e:
logging.error(f"Local API is not reachable: {e}")
return "Error: Local API is not reachable. Please ensure it is running."
chunks = chunk_text(text)
summaries = []
total_chunks = len(chunks)
print(f"\nProcessing {total_chunks} chunks...")
logging.info(f"Processing {total_chunks} chunks...")
# Initial analysis to get main topic
topic_data = {
"model": "goekdenizguelmez/JOSIEFIED-Qwen2.5:3b",
"messages": [
{
"role": "system",
"content": "Identify the main topic of this text in 5-10 words."
},
{
"role": "user",
"content": text[:2000] # Use first chunk for topic identification
}
],
"stream": False,
}
try:
topic_response = http.post(
"http://localhost:11434/api/chat",
headers={"Content-Type": "application/json"},
json=topic_data,
timeout=60
)
topic_response.raise_for_status()
main_topic = topic_response.json()['message']['content']
except requests.exceptions.RequestException as e:
logging.warning(f"Error getting topic: {e}")
main_topic = "the discussed topic"
except (KeyError, json.JSONDecodeError) as e:
logging.warning(f"Unexpected JSON format or missing key in topic response: {e}")
main_topic = "the discussed topic"
# Process each chunk with structured format
summary_template = f"""
Here's a breakdown of the key points and arguments presented in the video about {main_topic}:
1. Key Points Analysis:
[Main Arguments]: Identify and summarize the main arguments
[Supporting Evidence]: List any evidence or examples provided
[Context]: Provide relevant context or background information
2. Detailed Breakdown:
[Technical Details]: Explain any technical concepts
[Practical Applications]: Describe real-world applications
[Challenges/Limitations]: Discuss any challenges or limitations mentioned
3. Additional Insights:
[Expert Opinions]: Summarize any expert views or citations
[Future Implications]: Discuss potential future impacts
[Related Considerations]: Include any related topics or considerations
Overall Takeaway:
[Provide a concise summary of the main message and implications]
"""
for i, chunk in enumerate(chunks, 1):
print(f"\rProcessing chunk {i}/{total_chunks}...", end="", flush=True)
logging.info(f"Processing chunk {i}/{total_chunks}...")
headers = {"Content-Type": "application/json"}
data = {
"model": "goekdenizguelmez/JOSIEFIED-Qwen2.5:3b",
"messages": [
{
"role": "system",
"content": f"Analyze this text segment and provide a detailed summary following this structure:\n{summary_template}"
},
{
"role": "user",
"content": chunk
}
],
"stream": False,
}
try:
response = http.post(
"http://localhost:11434/api/chat",
headers=headers,
json=data,
timeout=45 # Increased timeout for detailed analysis
)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
if response.status_code != 200:
print(f"\nWarning: Chunk {i} failed with status {response.status_code}")
logging.warning(f"Chunk {i} failed with status {response.status_code}")
continue
response_json = response.json()
if 'message' in response_json and 'content' in response_json['message'] and response_json['message']['content']:
summaries.append(response_json['message']['content'])
else:
print(f"\nWarning: Unexpected response format for chunk {i}")
logging.warning(f"Unexpected response format for chunk {i}: {response_json}")
time.sleep(2) # Increased delay between requests
except requests.exceptions.Timeout:
print(f"\nWarning: Timeout on chunk {i}, skipping...")
logging.warning(f"Timeout on chunk {i}, skipping...")
continue
except requests.exceptions.RequestException as e:
print(f"\nWarning: Request error on chunk {i}, skipping...: {e}")
logging.warning(f"Request error on chunk {i}, skipping...: {e}")
continue
except (KeyError, json.JSONDecodeError) as e:
print(f"\nWarning: JSON error on chunk {i}, skipping...: {e}")
logging.warning(f"JSON error on chunk {i}, skipping...: {e}")
continue
print("\nProcessing complete!")
logging.info("Chunk processing complete!")
if not summaries:
return "Failed to generate any summaries"
logging.warning("Failed to generate any summaries")
# Combine and structure final summary
if len(summaries) > 1:
combined_text = "\n\n".join(summaries)
final_data = {
"model": "goekdenizguelmez/JOSIEFIED-Qwen2.5:3b",
"messages": [
{
"role": "system",
"content": f"Create a final structured summary following this template, ensuring it's at least 1500 words:\n{summary_template}"
},
{
"role": "user",
"content": combined_text
}
],
"stream": False,
}
try:
final_response = http.post(
"http://localhost:11434/api/chat",
headers=headers,
json=final_data,
timeout=60
)
final_response.raise_for_status()
if final_response.status_code == 200:
return final_response.json()['message']['content']
else:
logging.error(f"Final summary failed with status code: {final_response.status_code}")
return combined_text # Return combined text as fallback
except requests.exceptions.RequestException as e:
logging.error(f"Error during final summary: {e}")
return combined_text
except (KeyError, json.JSONDecodeError) as e:
logging.error(f"Unexpected JSON format or missing key in final response: {e}")
return combined_text
return summaries[0]
except Exception as e:
logging.exception("An unexpected error occurred in get_summary:") # Log the full exception traceback
return f"Error generating summary: {str(e)}"
def main():
url = input("Enter YouTube URL: ")
video_id = get_video_id(url)
if not video_id:
print("Invalid YouTube URL")
return
print("\nFetching transcript...")
transcript = get_transcript(video_id)
if transcript.startswith("Error"):
print(transcript)
return
print("\nGenerating summary...")
summary = get_summary(transcript)
print("\nSUMMARY:\n")
print(summary)
if __name__ == "__main__":
main()
Key changes and explanations:
logging: Added import logging.logging.basicConfig(...) to configure logging to a file. Adjust filename and level as needed. level=logging.INFO will capture informational messages, warnings, and errors. level=logging.DEBUG will capture even more details.except blocks with more specific ones (e.g., CouldNotRetrieveTranscript, requests.exceptions.RequestException, KeyError, json.JSONDecodeError).get_summary to ensure the local API is running.raise_for_status(): Added response.raise_for_status() after API calls to raise an HTTPError for bad status codes (4xx or 5xx). This simplifies error handling.'content' field is not empty.logging.info, logging.warning, and logging.error calls throughout the code to log important events and errors to the log file. logging.exception is used to log the full traceback of an exception.combined_text as a fallback, preventing a complete failure.How to use the logging:
script.log file in the same directory as your script. The log file will contain detailed information about what went wrong, including timestamps, error messages, and tracebacks.This revised code should be more robust and easier to debug. Remember to adapt the logging level, file name, and API endpoint to your specific needs. Also, carefully review the error messages in the log file to identify the root cause of any problems you encounter.
Python Script Issues:
http://localhost:11434/api/chat) is correct.Docker Considerations (If Applicable):
11434 is correctly mapped to the host machine's port 11434 using the -p option in the docker run command.localhost.Testing Connectivity (from the machine running the Python script):
curl or wget: Use curl or wget to test connectivity to the API endpoint:
curl http://localhost:11434/api/chat
# or
wget http://localhost:11434/api/chat
If you get a "connection refused" or similar error, it means the API is not reachable. If you get a response (even an error response from the API), it means the connection is working.
Python requests (simple test): You can also use a simple Python script to test the connection:
import requests
try:
response = requests.get("http://localhost:11434/api/chat", timeout=5)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
print("API is reachable. Response:", response.text)
except requests.exceptions.RequestException as e:
print("API is not reachable:", e)
Example Scenario and Solution:
Let's say you're running the API in a Docker container, and you forgot to map the port correctly.
11434, but you started the container with docker run <image_name> instead of docker run -p 11434:11434 <image_name>. This means that port 11434 on your host machine is not connected to port 11434 inside the container.docker stop <container_id>
docker run -p 11434:11434 <image_name>
By systematically checking these areas, you should be able to identify and resolve the issue preventing your Python script from connecting to the local API. Remember to examine all relevant logs and error messages for clues.</image_name></container_id></image_name></image_name>