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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import asyncio
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from typing import Dict, List, Any
|
| 6 |
+
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
from helper import ChatBot, current_year, save_to_audio, invoke_duckduckgo_news_search
|
| 10 |
+
|
| 11 |
+
# Set Streamlit layout to wide mode
|
| 12 |
+
st.set_page_config(layout="wide")
|
| 13 |
+
st.title("SearchBot 🤖") # App title
|
| 14 |
+
|
| 15 |
+
# Sidebar for user inputs and instructions
|
| 16 |
+
with st.sidebar:
|
| 17 |
+
with st.expander("📖 Instruction Manual"):
|
| 18 |
+
st.markdown(
|
| 19 |
+
"""
|
| 20 |
+
## 🧠 SearchBot 🤖 - Your AI-Powered Research Assistant
|
| 21 |
+
Welcome to **SearchBot**, an advanced AI assistant that helps you find the latest news, trends, and information
|
| 22 |
+
across various sources.
|
| 23 |
+
|
| 24 |
+
### 🔹 How to Use:
|
| 25 |
+
1. **📌 Choose Search Source**
|
| 26 |
+
- Select the type of search (News, Research Papers, Web Articles).
|
| 27 |
+
2. **📊 Choose Number of Results**
|
| 28 |
+
- Decide how many results you want (1 to 10).
|
| 29 |
+
3. **🌍 Set Location**
|
| 30 |
+
- Customize search results based on location.
|
| 31 |
+
*(e.g., "us-en" for USA, "in-en" for India)*
|
| 32 |
+
4. **⏳ Filter by Time**
|
| 33 |
+
- Search for the most recent news or past articles:
|
| 34 |
+
- **Past Day** 🕐 (Breaking News)
|
| 35 |
+
- **Past Week** 🗓 (Trending Topics)
|
| 36 |
+
- **Past Month** 📅 (Major Stories)
|
| 37 |
+
- **Past Year** 📆 (Deep Research)
|
| 38 |
+
5. **💬 Review Search Results & Chat History**
|
| 39 |
+
- View results in an interactive table.
|
| 40 |
+
- Chatbot provides summarized responses with references.
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
### 🔹 Live Examples You Can Try:
|
| 45 |
+
**📰 Find Latest News**
|
| 46 |
+
- *"What are the latest AI breakthroughs?"*
|
| 47 |
+
- *"Recent developments in space exploration."*
|
| 48 |
+
|
| 49 |
+
**📖 Research Papers & Analysis**
|
| 50 |
+
- *"Most cited papers on quantum computing."*
|
| 51 |
+
- *"Deep learning advancements in 2024."*
|
| 52 |
+
|
| 53 |
+
**🌍 Location-Based Information**
|
| 54 |
+
- *"Tech news in Silicon Valley."*
|
| 55 |
+
- *"Political updates in the UK."*
|
| 56 |
+
|
| 57 |
+
**⚡ AI-Powered Chatbot Insights**
|
| 58 |
+
- *"Summarize recent news on cryptocurrency."*
|
| 59 |
+
- *"Give me top AI news from last week with analysis."*
|
| 60 |
+
"""
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# User inputs for search customization
|
| 64 |
+
num: int = st.number_input("📊 Number of results", value=3, step=1, min_value=1, max_value=10)
|
| 65 |
+
location: str = st.text_input("🌍 Location (e.g., us-en, in-en)", value="us-en")
|
| 66 |
+
time_filter: str = st.selectbox(
|
| 67 |
+
"⏳ Time filter",
|
| 68 |
+
["Past Day", "Past Week", "Past Month", "Past Year"],
|
| 69 |
+
index=1
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Convert time filter to DuckDuckGo-compatible format
|
| 73 |
+
time_mapping: Dict[str, str] = {"Past Day": "d", "Past Week": "w", "Past Month": "m", "Past Year": "y"}
|
| 74 |
+
time_filter = time_mapping[time_filter]
|
| 75 |
+
|
| 76 |
+
only_use_chatbot: bool = st.checkbox("💬 Only use chatbot (Disable Search)")
|
| 77 |
+
|
| 78 |
+
# Clear chat history button
|
| 79 |
+
if st.button("🧹 Clear Session"):
|
| 80 |
+
st.session_state.messages = []
|
| 81 |
+
st.rerun()
|
| 82 |
+
|
| 83 |
+
# Footer with dynamic year
|
| 84 |
+
st.markdown(f"<h6>📅 Copyright © 2010-{current_year()} Present</h6>", unsafe_allow_html=True)
|
| 85 |
+
|
| 86 |
+
# Initialize chat history
|
| 87 |
+
if "messages" not in st.session_state:
|
| 88 |
+
st.session_state.messages: List[Dict[str, str]] = []
|
| 89 |
+
|
| 90 |
+
# Ensure messages are always a list of dictionaries
|
| 91 |
+
if not isinstance(st.session_state.messages, list) or not all(isinstance(msg, dict) for msg in st.session_state.messages):
|
| 92 |
+
st.session_state.messages = []
|
| 93 |
+
|
| 94 |
+
# Display past chat history in Streamlit chat UI
|
| 95 |
+
for message in st.session_state.messages:
|
| 96 |
+
with st.chat_message(message["role"]):
|
| 97 |
+
st.markdown(message["content"])
|
| 98 |
+
|
| 99 |
+
# Process user input in the chatbox
|
| 100 |
+
if prompt := st.chat_input("Ask anything!"):
|
| 101 |
+
st.chat_message("user").markdown(prompt)
|
| 102 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 103 |
+
|
| 104 |
+
# Initialize ref_table_string to hold search results
|
| 105 |
+
ref_table_string: str = "**No references found.**"
|
| 106 |
+
search_results: Dict[str, Any] = {"status": "failure", "results": []} # Initialize search_results
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
with st.spinner("Searching..."): # Show loading spinner
|
| 110 |
+
if only_use_chatbot:
|
| 111 |
+
response: str = "<empty>"
|
| 112 |
+
else:
|
| 113 |
+
# Call async search function using `asyncio.run()`
|
| 114 |
+
search_results = asyncio.run(
|
| 115 |
+
invoke_duckduckgo_news_search(query=prompt, location=location, num=num, time_filter=time_filter)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if search_results["status"] == "success":
|
| 119 |
+
md_data: List[Dict[str, Any]] = search_results["results"]
|
| 120 |
+
response = f"Here are your search results:\n{md_data}"
|
| 121 |
+
|
| 122 |
+
def clean_title(title: str) -> str:
|
| 123 |
+
"""
|
| 124 |
+
Cleans the title by replacing '|' with '-' to ensure proper formatting.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
title (str): The original title.
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
str: The cleaned title with '|' replaced by '-'.
|
| 131 |
+
"""
|
| 132 |
+
return title.replace("|", " - ").strip() # Replace '|' with ' - ' and remove leading/trailing spaces
|
| 133 |
+
|
| 134 |
+
def generate_star_rating(rating: str) -> str:
|
| 135 |
+
"""
|
| 136 |
+
Converts a numeric rating into a star representation (supports half-stars).
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
rating (str): The rating value as a string.
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
str: A string representation of the rating using stars (⭐) and half-stars (⭐½).
|
| 143 |
+
"""
|
| 144 |
+
try:
|
| 145 |
+
rating_float: float = float(rating) # Convert rating to float
|
| 146 |
+
full_stars: int = int(rating_float) # Extract full stars
|
| 147 |
+
half_star: str = "⭐½" if (rating_float - full_stars) >= 0.5 else "" # Add half-star if needed
|
| 148 |
+
return "⭐" * full_stars + half_star # Construct final star rating
|
| 149 |
+
except ValueError:
|
| 150 |
+
return "N/A" # Fallback for non-numeric ratings
|
| 151 |
+
|
| 152 |
+
# Start building reference table with proper Markdown formatting
|
| 153 |
+
ref_table_string = "| Num | Title | Rating | Context |\n|---|------|--------|---------|\n"
|
| 154 |
+
|
| 155 |
+
for idx, res in enumerate(md_data, start=1):
|
| 156 |
+
# Clean the title by replacing '|' with '-'
|
| 157 |
+
title_cleaned = clean_title(res['title'])
|
| 158 |
+
|
| 159 |
+
# Ensure the rating is always numeric before converting to stars
|
| 160 |
+
raw_rating = str(res.get('rating', 'N/A')).strip() # Get rating and strip whitespace
|
| 161 |
+
|
| 162 |
+
# Only convert rating if it’s a valid number
|
| 163 |
+
if raw_rating.replace('.', '', 1).isdigit(): # Check if it’s a valid float
|
| 164 |
+
stars = generate_star_rating(raw_rating)
|
| 165 |
+
else:
|
| 166 |
+
stars = "N/A" # If it's text (like "MIT News"), default to "N/A"
|
| 167 |
+
|
| 168 |
+
# Ensure proper clickable links in the Title column
|
| 169 |
+
if res.get('link', '').startswith("http"): # Ensure link exists and is valid
|
| 170 |
+
title = f"[{title_cleaned}]({res['link']})"
|
| 171 |
+
else:
|
| 172 |
+
title = title_cleaned # Fallback to text-only title
|
| 173 |
+
|
| 174 |
+
# Properly format Context column (limit to 100 chars)
|
| 175 |
+
context_summary = res.get('summary', '').strip() # Ensure it's a string and strip spaces
|
| 176 |
+
summary = context_summary[:100] + "..." if len(context_summary) > 100 else context_summary
|
| 177 |
+
|
| 178 |
+
# Final row construction
|
| 179 |
+
ref_table_string += f"| {idx} | {title} | {stars} | {summary} |\n"
|
| 180 |
+
|
| 181 |
+
# Generate chatbot response based on search results or chat history
|
| 182 |
+
bot = ChatBot()
|
| 183 |
+
bot.history = st.session_state.messages.copy()
|
| 184 |
+
response = bot.generate_response(
|
| 185 |
+
f"""
|
| 186 |
+
User prompt: {prompt}
|
| 187 |
+
Previous response: {response}
|
| 188 |
+
Context: {', '.join(res.get('summary', '').strip() for res in md_data)}
|
| 189 |
+
|
| 190 |
+
Instructions:
|
| 191 |
+
1) Ensure the response is **directly relevant** to the User prompt and aligns with the Context.
|
| 192 |
+
2) Do **NOT** include unrelated or speculative information that is **not present in the Context**.
|
| 193 |
+
3) If Context provides relevant details, base the response **strictly on those details**.
|
| 194 |
+
4) If Context is **empty**, use Previous response **only if** it aligns with the User prompt.
|
| 195 |
+
5) If there is **insufficient information** in Context or Previous response,
|
| 196 |
+
acknowledge it rather than generating unrelated details.
|
| 197 |
+
6) Keep the response **concise, accurate, and logically structured**.
|
| 198 |
+
"""
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
st.warning(f"Error fetching data: {e}")
|
| 203 |
+
response = "We encountered an issue. Please try again later."
|
| 204 |
+
|
| 205 |
+
# Convert response to audio
|
| 206 |
+
save_to_audio(response)
|
| 207 |
+
|
| 208 |
+
# Display assistant response in chat UI
|
| 209 |
+
with st.chat_message("assistant"):
|
| 210 |
+
st.markdown(response, unsafe_allow_html=True)
|
| 211 |
+
st.audio("output.mp3", format="audio/mpeg", loop=True)
|
| 212 |
+
with st.expander("References:", expanded=True):
|
| 213 |
+
st.markdown(ref_table_string, unsafe_allow_html=True)
|
| 214 |
+
|
| 215 |
+
# Update chat history with final response
|
| 216 |
+
final_response: str = f"{response}\n\n{ref_table_string}"
|
| 217 |
+
st.session_state.messages.append({"role": "assistant", "content": final_response})
|
helper.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import pickle
|
| 5 |
+
import subprocess
|
| 6 |
+
import time
|
| 7 |
+
import urllib.parse
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from typing import Dict, List, Any, Optional
|
| 10 |
+
import httpx
|
| 11 |
+
import keras
|
| 12 |
+
import numpy as np
|
| 13 |
+
import requests
|
| 14 |
+
import re
|
| 15 |
+
from bs4 import BeautifulSoup
|
| 16 |
+
from gtts import gTTS
|
| 17 |
+
from huggingface_hub import hf_hub_download
|
| 18 |
+
from keras.utils import pad_sequences
|
| 19 |
+
from transformers import BertTokenizer
|
| 20 |
+
|
| 21 |
+
from logger.app_logger import app_logger
|
| 22 |
+
from selenium import webdriver
|
| 23 |
+
from selenium.webdriver.chrome.options import Options
|
| 24 |
+
import concurrent.futures
|
| 25 |
+
|
| 26 |
+
class ChatBot:
|
| 27 |
+
"""
|
| 28 |
+
A chatbot class that interacts with a local Llama model using Ollama.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self) -> None:
|
| 32 |
+
"""Initialize the ChatBot instance with a conversation history."""
|
| 33 |
+
self.history: List[Dict[str, str]] = [{"role": "system", "content": "You are a helpful assistant."}]
|
| 34 |
+
app_logger.log_info("ChatBot instance initialized", level="INFO")
|
| 35 |
+
|
| 36 |
+
def generate_response(self, prompt: str) -> str:
|
| 37 |
+
"""
|
| 38 |
+
Generate a response from the chatbot based on the user's prompt.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
prompt (str): The input message from the user.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
str: The chatbot's response to the provided prompt.
|
| 45 |
+
"""
|
| 46 |
+
self.history.append({"role": "user", "content": prompt})
|
| 47 |
+
app_logger.log_info("User prompt added to history", level="INFO")
|
| 48 |
+
|
| 49 |
+
# Convert chat history into a string for subprocess input
|
| 50 |
+
conversation: str = "\n".join(f"{msg['role']}: {msg['content']}" for msg in self.history)
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
# Run the Llama model using Ollama
|
| 54 |
+
completion: subprocess.CompletedProcess = subprocess.run(
|
| 55 |
+
["ollama", "run", "llama3.2:latest"],
|
| 56 |
+
input=conversation,
|
| 57 |
+
capture_output=True,
|
| 58 |
+
text=True,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
if completion.returncode != 0:
|
| 62 |
+
app_logger.log_error(f"Error running subprocess: {completion.stderr}")
|
| 63 |
+
return "I'm sorry, I encountered an issue processing your request."
|
| 64 |
+
|
| 65 |
+
response: str = completion.stdout.strip()
|
| 66 |
+
self.history.append({"role": "assistant", "content": response})
|
| 67 |
+
app_logger.log_info("Assistant response generated", level="INFO")
|
| 68 |
+
|
| 69 |
+
return response
|
| 70 |
+
|
| 71 |
+
except Exception as e:
|
| 72 |
+
app_logger.log_error(f"Error sending query to the model: {e}")
|
| 73 |
+
return "I'm sorry, an error occurred while processing your request."
|
| 74 |
+
|
| 75 |
+
async def rate_body_of_article(self, article_title: str, article_content: str) -> str:
|
| 76 |
+
"""
|
| 77 |
+
Rate the quality of an article's content based on its title.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
article_title (str): The title of the article.
|
| 81 |
+
article_content (str): The full content of the article.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
str: A rating between 1 and 5 based on relevance and quality.
|
| 85 |
+
"""
|
| 86 |
+
prompt: str = f"""
|
| 87 |
+
Given the following article title and content, provide a rating between 1 and 5
|
| 88 |
+
based on how well the content aligns with the title and its overall quality.
|
| 89 |
+
|
| 90 |
+
- **Article Title**: {article_title}
|
| 91 |
+
- **Article Content**: {article_content[:1000]} # Limit to first 1000 chars
|
| 92 |
+
|
| 93 |
+
**Instructions:**
|
| 94 |
+
- The rating should be a whole number between 1 and 5.
|
| 95 |
+
- Base your score on accuracy, clarity, and relevance.
|
| 96 |
+
- Only return a single numeric value (1-5) with no extra text.
|
| 97 |
+
|
| 98 |
+
**Example Output:**
|
| 99 |
+
`4` or `2` or `3.5` or `1.5`
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
try:
|
| 103 |
+
# Run the Llama model using Ollama
|
| 104 |
+
completion: subprocess.CompletedProcess = subprocess.run(
|
| 105 |
+
["ollama", "run", "llama3.2:latest"],
|
| 106 |
+
input=prompt,
|
| 107 |
+
capture_output=True,
|
| 108 |
+
text=True,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if completion.returncode != 0:
|
| 112 |
+
app_logger.log_error(f"Error running subprocess: {completion.stderr}")
|
| 113 |
+
return "Error"
|
| 114 |
+
|
| 115 |
+
response: str = completion.stdout.strip()
|
| 116 |
+
|
| 117 |
+
# Validate the rating is within the expected range
|
| 118 |
+
if response.isdigit() and 1 <= int(response) <= 5:
|
| 119 |
+
self.history.append({"role": "assistant", "content": response})
|
| 120 |
+
app_logger.log_info(f"Article rated: {response}", level="INFO")
|
| 121 |
+
return response
|
| 122 |
+
else:
|
| 123 |
+
app_logger.log_warning(f"Invalid rating received: {response}")
|
| 124 |
+
return "Error"
|
| 125 |
+
|
| 126 |
+
except Exception as e:
|
| 127 |
+
app_logger.log_error(f"Error sending query to the model: {e}")
|
| 128 |
+
return "Error"
|
| 129 |
+
|
| 130 |
+
async def rate_article_credibility(self, article_title: str, article_content: str) -> str:
|
| 131 |
+
"""
|
| 132 |
+
Rate the credibility of an article using a locally created model.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
article_title (str): The title of the article.
|
| 136 |
+
article_content (str): The full content of the article.
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
str: A credibility rating based on the model's prediction.
|
| 140 |
+
"""
|
| 141 |
+
try:
|
| 142 |
+
# Load the model
|
| 143 |
+
model_path: str = hf_hub_download(repo_id="Dkethan/my-tf-nn-model-v2", filename="model.keras")
|
| 144 |
+
new_model = keras.models.load_model(model_path)
|
| 145 |
+
|
| 146 |
+
# Load the Hugging Face tokenizer
|
| 147 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
| 148 |
+
|
| 149 |
+
# Preprocess the input data
|
| 150 |
+
max_length: int = new_model.input_shape[0][1] # Ensure max_length matches the model input
|
| 151 |
+
X_text = tokenizer(
|
| 152 |
+
[article_title], # Tokenize the article title
|
| 153 |
+
max_length=max_length,
|
| 154 |
+
padding="max_length",
|
| 155 |
+
truncation=True,
|
| 156 |
+
return_tensors="tf"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# Dummy 'func_rating' input (can be replaced with actual data)
|
| 160 |
+
X_func_rating: np.ndarray = np.array([5]).reshape(-1, 1) # Replace with actual input if available
|
| 161 |
+
|
| 162 |
+
# Make predictions
|
| 163 |
+
predictions: np.ndarray = new_model.predict(
|
| 164 |
+
{"text_input": X_text["input_ids"], "func_rating_input": X_func_rating}
|
| 165 |
+
)
|
| 166 |
+
prediction: int = np.argmax(predictions, axis=1)[0]
|
| 167 |
+
|
| 168 |
+
# Log and return the prediction
|
| 169 |
+
app_logger.log_info(f"Article credibility rated: {prediction}", level="INFO")
|
| 170 |
+
return str(prediction)
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
app_logger.log_error(f"Error rating article credibility: {e}")
|
| 174 |
+
return "Error"
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def extract_news_body(news_url: str) -> str:
|
| 178 |
+
"""
|
| 179 |
+
Extract the full article body from a given news URL.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
news_url (str): The URL of the news article.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
str: Extracted full article content.
|
| 186 |
+
"""
|
| 187 |
+
headers: Dict[str, str] = {
|
| 188 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
|
| 189 |
+
}
|
| 190 |
+
retries: int = 3
|
| 191 |
+
for attempt in range(retries):
|
| 192 |
+
try:
|
| 193 |
+
response: requests.Response = requests.get(news_url, headers=headers, timeout=10)
|
| 194 |
+
if response.status_code == 403:
|
| 195 |
+
app_logger.log_error(f"Access forbidden to article: {response.status_code}")
|
| 196 |
+
return "Access forbidden to article."
|
| 197 |
+
if response.status_code != 200:
|
| 198 |
+
app_logger.log_error(f"Failed to fetch article: {response.status_code}")
|
| 199 |
+
return "Failed to fetch article."
|
| 200 |
+
|
| 201 |
+
soup: BeautifulSoup = BeautifulSoup(response.text, "html.parser")
|
| 202 |
+
paragraphs: List[BeautifulSoup] = soup.find_all("p")
|
| 203 |
+
|
| 204 |
+
# Extract and return cleaned text
|
| 205 |
+
article_content: str = "\n".join([p.text.strip() for p in paragraphs if p.text.strip()])
|
| 206 |
+
app_logger.log_info(f"Article content extracted from {news_url}", level="INFO")
|
| 207 |
+
return article_content
|
| 208 |
+
|
| 209 |
+
except requests.exceptions.Timeout:
|
| 210 |
+
app_logger.log_warning(f"Timeout occurred while fetching article: {news_url}, attempt {attempt + 1}")
|
| 211 |
+
if attempt < retries - 1:
|
| 212 |
+
time.sleep(2) # Wait before retrying
|
| 213 |
+
continue
|
| 214 |
+
return "Error: Timeout occurred while fetching article."
|
| 215 |
+
|
| 216 |
+
except Exception as e:
|
| 217 |
+
app_logger.log_error(f"Error extracting article content: {e}")
|
| 218 |
+
return f"Error extracting article content: {e}"
|
| 219 |
+
|
| 220 |
+
return "Failed to fetch article after multiple attempts."
|
| 221 |
+
|
| 222 |
+
async def invoke_duckduckgo_news_search(query: str, num: int = 3, location: str = "us-en", time_filter: str = "w") -> Dict[str, Any]:
|
| 223 |
+
"""
|
| 224 |
+
Perform a news search on DuckDuckGo and return the results.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
query (str): The search query.
|
| 228 |
+
num (int): The number of results to return.
|
| 229 |
+
location (str): The location filter for the search.
|
| 230 |
+
time_filter (str): The time filter for the search.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
Dict[str, Any]: A dictionary containing the search results.
|
| 234 |
+
"""
|
| 235 |
+
app_logger.log_info(f"Starting DuckDuckGo news search for query: {query}", level="INFO")
|
| 236 |
+
|
| 237 |
+
chrome_options: Options = Options()
|
| 238 |
+
chrome_options.add_argument("--headless")
|
| 239 |
+
driver: webdriver.Chrome = webdriver.Chrome(options=chrome_options)
|
| 240 |
+
|
| 241 |
+
duckduckgo_news_url: str = f"https://duckduckgo.com/html/?q={query.replace(' ', '+')}&kl={location}&df={time_filter}&ia=news"
|
| 242 |
+
driver.get(duckduckgo_news_url)
|
| 243 |
+
|
| 244 |
+
soup: BeautifulSoup = BeautifulSoup(driver.page_source, "html.parser")
|
| 245 |
+
search_results: List[BeautifulSoup] = soup.find_all("div", class_="result__body")
|
| 246 |
+
|
| 247 |
+
def process_article(result: BeautifulSoup, index: int) -> Optional[Dict[str, Any]]:
|
| 248 |
+
"""
|
| 249 |
+
Process a single search result and extract relevant information.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
result (BeautifulSoup): The search result to process.
|
| 253 |
+
index (int): The index of the search result.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
Optional[Dict[str, Any]]: A dictionary containing the extracted information, or None if an error occurs.
|
| 257 |
+
"""
|
| 258 |
+
try:
|
| 259 |
+
title_tag: Optional[BeautifulSoup] = result.find("a", class_="result__a")
|
| 260 |
+
if not title_tag:
|
| 261 |
+
app_logger.log_warning(f"Title tag not found for result index {index}")
|
| 262 |
+
return None
|
| 263 |
+
|
| 264 |
+
title: str = title_tag.text.strip()
|
| 265 |
+
raw_link: str = title_tag["href"]
|
| 266 |
+
|
| 267 |
+
match: Optional[re.Match] = re.search(r"uddg=(https?%3A%2F%2F[^&]+)", raw_link)
|
| 268 |
+
link: str = urllib.parse.unquote(match.group(1)) if match else "Unknown Link"
|
| 269 |
+
|
| 270 |
+
snippet_tag: Optional[BeautifulSoup] = result.find("a", class_="result__snippet")
|
| 271 |
+
summary: str = snippet_tag.text.strip() if snippet_tag else "No summary available."
|
| 272 |
+
|
| 273 |
+
article_content: str = extract_news_body(link)
|
| 274 |
+
|
| 275 |
+
bot: ChatBot = ChatBot()
|
| 276 |
+
|
| 277 |
+
# Rate the rate_body_of_article
|
| 278 |
+
# rating: str = asyncio.run(bot.rate_body_of_article(title, article_content))
|
| 279 |
+
|
| 280 |
+
# Rate the credibility of the article
|
| 281 |
+
rating: str = asyncio.run(bot.rate_article_credibility(title, article_content))
|
| 282 |
+
|
| 283 |
+
app_logger.log_info(f"Processed article: {title}", level="INFO")
|
| 284 |
+
|
| 285 |
+
return {
|
| 286 |
+
"num": index + 1,
|
| 287 |
+
"link": link,
|
| 288 |
+
"title": title,
|
| 289 |
+
"summary": summary,
|
| 290 |
+
"body": article_content,
|
| 291 |
+
"rating": rating
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
except Exception as e:
|
| 295 |
+
app_logger.log_error(f"Error processing article: {e}")
|
| 296 |
+
return None
|
| 297 |
+
|
| 298 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 299 |
+
tasks: List[concurrent.futures.Future] = [executor.submit(process_article, result, index) for index, result in enumerate(search_results[:num])]
|
| 300 |
+
extracted_results: List[Optional[Dict[str, Any]]] = [task.result() for task in concurrent.futures.as_completed(tasks)]
|
| 301 |
+
|
| 302 |
+
driver.quit()
|
| 303 |
+
|
| 304 |
+
extracted_results = [res for res in extracted_results if res is not None]
|
| 305 |
+
|
| 306 |
+
if extracted_results:
|
| 307 |
+
app_logger.log_info(f"News search completed successfully with {len(extracted_results)} results", level="INFO")
|
| 308 |
+
return {"status": "success", "results": extracted_results}
|
| 309 |
+
else:
|
| 310 |
+
app_logger.log_error("No valid news search results found")
|
| 311 |
+
return {"status": "error", "message": "No valid news search results found"}
|
| 312 |
+
|
| 313 |
+
def current_year() -> int:
|
| 314 |
+
"""Returns the current year as an integer."""
|
| 315 |
+
return datetime.now().year
|
| 316 |
+
|
| 317 |
+
def save_to_audio(text: str) -> None:
|
| 318 |
+
"""Converts text to an audio file using Google Text-to-Speech (gTTS)."""
|
| 319 |
+
try:
|
| 320 |
+
tts: gTTS = gTTS(text=text, lang="en")
|
| 321 |
+
tts.save("output.mp3")
|
| 322 |
+
app_logger.log_info("Response converted to audio", level="INFO")
|
| 323 |
+
except Exception as e:
|
| 324 |
+
app_logger.log_error(f"Error converting response to audio: {e}")
|