I want to create a faceless youtube channel for current affairs which uses news from one site ( AIR News) and scraps that from the site and saves it in the excel in the convenient format, then the excel file is sent to local AI model through ollama which condenses it into bite sized news which keeps the important points and numbers and makes it ready for TTS. I want these from you : 1. Should it be multiple 2 min videos or one longer video for the whole day ? 2.Give me python script only for scraping 3.Give me python script for the other things 4.I already have TTS setup so no need to add anything about it
Assistant
Creating a faceless YouTube channel focused on current affairs is a great idea. Below are the detailed answers and Python scripts to help you achieve your goals:
1. Video Format: Multiple 2-Minute Videos vs. One Longer Video
Recommendation: Multiple 2-Minute Videos
Reasons:
Engagement: Shorter videos tend to retain viewer attention better. Viewers are more likely to watch multiple short videos throughout the day compared to a longer one.
Algorithm Favorability: YouTube's algorithm often favors channels that consistently upload content. Multiple uploads can increase your channel's visibility and subscriber growth.
Flexible Consumption: Viewers can choose to watch news snippets as they come, fitting into their schedules more conveniently.
SEO Benefits: Each video can target specific keywords, increasing the chances of appearing in search results.
Implementation Tip:
Organize your daily news into themed segments (e.g., Politics, Economy, International) and release them at regular intervals throughout the day to maximize reach and engagement.
2. Python Script for Scraping AIR News and Saving to Excel
Below is a Python script that scrapes news from the AIR News website and saves it into an Excel file. This script uses the requests and BeautifulSoup libraries for web scraping and pandas for handling Excel operations.
import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
def scrape_air_news(url):
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
except requests.exceptions.RequestException as e:
print(f"Error fetching the URL: {e}")
return []
soup = BeautifulSoup(response.text, 'html.parser')
# This section depends on the actual HTML structure of AIR News.
# You need to inspect the AIR News website and update the selectors accordingly.
articles = []
news_section = soup.find('div', class_='news-list') # Example selector
if not news_section:
print("Could not find the news section on the page.")
return articles
news_items = news_section.find_all('div', class_='news-item') # Example selector
for item in news_items:
title = item.find('h2').get_text(strip=True) if item.find('h2') else 'No Title'
date_str = item.find('span', class_='date').get_text(strip=True) if item.find('span', class_='date') else 'No Date'
content = item.find('p').get_text(strip=True) if item.find('p') else 'No Content'
# Parse date
try:
date = datetime.datetime.strptime(date_str, '%d %b %Y').date()
except ValueError:
date = 'Unknown Date'
articles.append({
'Title': title,
'Date': date,
'Content': content
})
return articles
def save_to_excel(articles, filename):
if not articles:
print("No articles to save.")
return
df = pd.DataFrame(articles)
try:
df.to_excel(filename, index=False)
print(f"Successfully saved {len(df)} articles to {filename}")
except Exception as e:
print(f"Error saving to Excel: {e}")
if __name__ == "__main__":
AIR_NEWS_URL = 'https://www.airnews.in/' # Replace with the actual AIR News URL
OUTPUT_FILE = 'air_news.xlsx'
news_articles = scrape_air_news(AIR_NEWS_URL)
save_to_excel(news_articles, OUTPUT_FILE)
Notes:
HTML Structure: The selectors ('div', class_='news-list' and 'div', class_='news-item') are placeholders. You must inspect the actual AIR News website to identify the correct HTML elements and classes.
Error Handling: The script includes basic error handling for network requests and missing HTML elements.
Date Parsing: Adjust the date_str format in strptime based on how dates are formatted on the AIR News site.
3. Python Script for Processing News with Ollama and Preparing for TTS
This script will:
Read the Excel file containing the scraped news.
Send each article to the local Ollama AI model to condense it into bite-sized summaries.
Save the condensed summaries back to a new Excel file or any preferred format ready for TTS.
Prerequisites:
Ensure Ollama is installed and running locally.
Install necessary libraries:
bash
pip install pandas requests openpyxl
Assumptions:
Ollama API Endpoint: Assuming Ollama provides an HTTP API at http://localhost:11434/v1/ (update based on actual configuration).
Authentication: If Ollama requires authentication, include necessary headers or tokens.
Model Details: Replace 'your-model-name' with the actual model deployed on Ollama.
Script:
python
import pandas as pd
import requests
import time
def read_excel(file_path):
try:
df = pd.read_excel(file_path)
return df
except Exception as e:
print(f"Error reading Excel file: {e}")
return None
def send_to_ollama(prompt, model_name='your-model-name', timeout=60):
api_url = 'http://localhost:11434/v1/engines/{}/completions'.format(model_name)
headers = {'Content-Type': 'application/json'}
payload = {
'prompt': prompt,
'max_tokens': 150, # Adjust based on desired summary length
'temperature': 0.5,
'top_p': 1,
'n': 1,
'stream': False,
'stop': None
}
try:
response = requests.post(api_url, json=payload, headers=headers, timeout=timeout)
response.raise_for_status()
data = response.json()
return data.get('choices')[0].get('text').strip()
except requests.exceptions.RequestException as e:
print(f"Error communicating with Ollama: {e}")
return None
def process_articles(df):
summaries = []
for index, row in df.iterrows():
title = row.get('Title', 'No Title')
content = row.get('Content', 'No Content')
prompt = f"Condense the following news article into a concise summary, retaining important points and numbers:\n\nTitle: {title}\nContent: {content}"
print(f"Processing article {index + 1}/{len(df)}: {title}")
summary = send_to_ollama(prompt)
if summary:
summaries.append(summary)
else:
summaries.append('Summary not available.')
time.sleep(1) # To avoid overwhelming the API; adjust as needed
df['Summary'] = summaries
return df
def save_summary(df, output_file):
try:
df.to_excel(output_file, index=False)
print(f"Successfully saved summaries to {output_file}")
except Exception as e:
print(f"Error saving summaries to Excel: {e}")
if __name__ == "__main__":
INPUT_FILE = 'air_news.xlsx' # The Excel file from the scraping script
OUTPUT_FILE = 'air_news_summaries.xlsx'
MODEL_NAME = 'your-model-name' # Replace with your actual Ollama model name
news_df = read_excel(INPUT_FILE)
if news_df is not None:
processed_df = process_articles(news_df)
save_summary(processed_df, OUTPUT_FILE)
Notes:
Ollama Configuration: Ensure that Ollama's API endpoint, port, and model name are correctly specified. Replace 'your-model-name' with the actual model you're using.
Prompt Design: The prompt is crafted to instruct the AI to condense the article while retaining important information. You may need to refine the prompt based on the AI's performance.
Rate Limiting: The time.sleep(1) is included to prevent sending too many requests in a short period. Adjust the delay based on Ollama's capacity and response times.
Error Handling: The script includes basic error handling for API communication and file operations.
Output: The script adds a new column 'Summary' to the Excel file containing the condensed news ready for TTS.
Additional Recommendations
Automation: Consider scheduling these scripts to run at specific intervals (e.g., using cron jobs on Unix/Linux or Task Scheduler on Windows) to automate the entire workflow daily.
Logging: Implement logging to monitor the scraping and processing activities, which can help in troubleshooting issues.
Data Storage: Instead of Excel, you might want to use a database (like SQLite) for better scalability and data management, especially as your channel grows.
Content Verification: Always verify the accuracy of the AI-generated summaries to maintain credibility in your channel.
Compliance: Ensure that you have the right to scrape and use content from AIR News. Respect the website’s robots.txt and terms of service to avoid legal issues.
By following the above steps and scripts, you should be well on your way to creating an efficient workflow for your faceless YouTube channel focused on current affairs.