File size: 29,758 Bytes
33f1e50
72ddedb
33f1e50
 
 
 
 
 
9988100
d07bea9
9988100
 
33f1e50
72ddedb
33f1e50
 
 
 
 
 
 
218de65
90e8b4f
6773bde
 
 
 
 
 
a5594d9
 
 
5239e89
b688d25
72ddedb
33f1e50
 
 
 
 
 
 
 
 
 
 
 
6773bde
33f1e50
 
 
 
 
 
 
72ddedb
 
b688d25
 
 
 
 
 
 
 
 
 
 
 
 
 
5239e89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b688d25
 
 
 
 
 
5239e89
 
 
 
 
b688d25
5239e89
 
 
 
 
 
 
33f1e50
 
c17888a
 
33f1e50
 
72ddedb
33f1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5594d9
b577b65
a5594d9
 
 
 
 
 
 
 
 
 
 
b577b65
a5594d9
 
 
 
 
 
 
b577b65
a5594d9
b577b65
6773bde
a5594d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6773bde
a5594d9
 
 
6773bde
6c48447
a5594d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c48447
f57b788
6c48447
6773bde
a5594d9
33f1e50
a5594d9
 
 
 
 
 
 
 
33f1e50
a5594d9
 
 
33f1e50
a5594d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84a4885
33f1e50
 
120e548
 
 
 
 
33f1e50
 
120e548
33f1e50
 
 
 
 
 
72ddedb
33f1e50
 
 
 
72ddedb
33f1e50
 
 
 
 
 
 
 
 
72ddedb
33f1e50
 
 
 
72ddedb
33f1e50
 
 
 
 
72ddedb
33f1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72ddedb
33f1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120e548
33f1e50
 
 
 
 
 
 
 
120e548
33f1e50
 
 
 
 
 
 
 
72ddedb
33f1e50
 
 
 
 
 
 
 
 
 
6773bde
 
33f1e50
 
 
 
 
 
a5594d9
33f1e50
 
 
a5594d9
 
 
c6a0be6
a5594d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a0be6
b577b65
 
a5594d9
 
 
33f1e50
 
 
 
e4b2310
 
33f1e50
 
e4b2310
 
33f1e50
e4b2310
 
 
 
 
 
 
 
 
 
 
 
 
33f1e50
 
 
 
 
 
 
 
 
3c683fa
6773bde
99c2925
 
33f1e50
 
 
 
 
 
a5594d9
b864c9d
5239e89
b864c9d
33f1e50
 
 
 
 
 
 
 
5239e89
 
 
b864c9d
5239e89
b864c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f1e50
4706059
 
 
b864c9d
 
 
33f1e50
b864c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
33f1e50
b864c9d
 
 
 
 
 
 
33f1e50
6c0f253
07efc76
 
 
b9091e4
07efc76
 
 
 
 
 
 
a5594d9
07efc76
a5594d9
07efc76
 
6773bde
9988100
07efc76
 
 
 
a5594d9
 
07efc76
 
 
 
 
 
4706059
b864c9d
 
 
 
33f1e50
 
 
 
 
4706059
 
33f1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb6b9ef
33f1e50
 
 
 
 
 
 
 
 
 
4706059
 
6057fe5
33f1e50
e4b2310
 
 
 
 
 
 
 
 
 
 
 
 
 
33f1e50
e4b2310
 
33f1e50
 
 
218de65
 
33f1e50
 
5239e89
33f1e50
 
 
 
 
 
 
 
 
 
 
 
 
 
5239e89
 
33f1e50
 
 
 
 
 
5239e89
33f1e50
120e548
72ddedb
33f1e50
dad2e6e
c17888a
3a81b27
 
33f1e50
 
 
 
3a81b27
33f1e50
72ddedb
33f1e50
 
 
5239e89
72ddedb
33f1e50
 
 
 
 
 
 
 
6552a74
33f1e50
72ddedb
 
 
33f1e50
84a4885
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
import requests
import gradio as gr
from bs4 import BeautifulSoup
import logging
from urllib.parse import urlparse
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from trafilatura import fetch_url, extract
from trafilatura import extract
from requests.exceptions import Timeout
from trafilatura.settings import use_config
from urllib.request import urlopen, Request
import json
from huggingface_hub import InferenceClient
import random
import time
from sentence_transformers import SentenceTransformer, util
import torch
from datetime import datetime
import os
from dotenv import load_dotenv
import certifi
import requests
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy import signals
from scrapy.signalmanager import dispatcher
from scrapy.utils.log import configure_logging
from newspaper import Article
import PyPDF2
import io
import requests
from duckduckgo_search import DDGS
import random

# Load environment variables from a .env file
load_dotenv()

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# SearXNG instance details
SEARXNG_URL = 'https://shreyas094-searxng-local.hf.space/search'
SEARXNG_KEY = 'f9f07f93b37b8483aadb5ba717f556f3a4ac507b281b4ca01e6c6288aa3e3ae5'

# Use the environment variable
HF_TOKEN = os.getenv("HF_TOKEN")
client = InferenceClient(
    "mistralai/Mistral-Nemo-Instruct-2407",
    token=HF_TOKEN,
)

# Initialize the similarity model
similarity_model = SentenceTransformer('all-MiniLM-L6-v2')


# List of common user agents
USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (iPad; CPU OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/91.0.4472.80 Mobile/15E148 Safari/604.1",
    "Mozilla/5.0 (Android 11; Mobile; rv:68.0) Gecko/68.0 Firefox/88.0",
]

def get_random_user_agent():
    return random.choice(USER_AGENTS)

def duckduckgo_search(query, num_results=10, time_range="", language="", safesearch=2):
    try:
        ddgs = DDGS()
        
        # Convert time_range to DuckDuckGo format
        if time_range == "day":
            timelimit = "d"
        elif time_range == "week":
            timelimit = "w"
        elif time_range == "month":
            timelimit = "m"
        elif time_range == "year":
            timelimit = "y"
        else:
            timelimit = None
        
        # Convert safesearch to DuckDuckGo format
        if safesearch == 0:
            safesearch_setting = "off"
        elif safesearch == 1:
            safesearch_setting = "moderate"
        else:
            safesearch_setting = "strict"
        
        # Get a random user agent
        user_agent = get_random_user_agent()
        
        # Set the user agent for the DDGS instance
        ddgs.session.headers.update({'User-Agent': user_agent})
        
        results = ddgs.text(
            query,
            region='wt-wt',
            safesearch=safesearch_setting,
            timelimit=timelimit,
            max_results=num_results
        )
        
        return [{"url": result["href"], "title": result["title"]} for result in results]
    except Exception as e:
        logger.error(f"Error in DuckDuckGo search: {e}")
        return []

# Set up a session with retry mechanism
def requests_retry_session(
    retries=0,
    backoff_factor=0.1,
    status_forcelist=(500, 502, 504),
    session=None,
):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session

def is_valid_url(url):
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc])
    except ValueError:
        return False

def scrape_pdf_content(url, max_chars=3000, timeout=5):
    try:
        logger.info(f"Scraping PDF content from: {url}")
        
        # Download the PDF file
        response = requests.get(url, timeout=timeout)
        response.raise_for_status()
        
        # Create a PDF reader object
        pdf_reader = PyPDF2.PdfReader(io.BytesIO(response.content))
        
        # Extract text from all pages
        content = ""
        for page in pdf_reader.pages:
            content += page.extract_text() + "\n"
        
        # Limit the content to max_chars
        return content[:max_chars] if content else ""
    except requests.Timeout:
        logger.error(f"Timeout error while scraping PDF content from {url}")
        return ""
    except Exception as e:
        logger.error(f"Error scraping PDF content from {url}: {e}")
        return ""


class NewsSpider(scrapy.Spider):
    name = 'news_spider'
    
    def __init__(self, url=None, *args, **kwargs):
        super(NewsSpider, self).__init__(*args, **kwargs)
        self.start_urls = [url] if url else []
    
    def parse(self, response):
        content = ' '.join(response.css('p::text').getall())
        self.logger.info(f"Scraped content length: {len(content)}")
        return {'content': content}

def scrape_with_scrapy(url, timeout=30):
    logger.info(f"Starting to scrape with Scrapy: {url}")
    configure_logging(install_root_handler=False)
    logging.getLogger('scrapy').setLevel(logging.WARNING)
    
    results = []
    
    def spider_results(signal, sender, item, response, spider):
        results.append(item)
    
    process = CrawlerProcess(settings={
        'LOG_ENABLED': True,
        'LOG_LEVEL': 'WARNING',
        'DOWNLOAD_TIMEOUT': timeout
    })
    
    dispatcher.connect(spider_results, signal=signals.item_scraped)
    
    process.crawl(NewsSpider, url=url)
    process.start()
    
    # Get the content from results
    if results:
        return results[0]['content']
    return ''

def scrape_with_newspaper(url):
    if url.lower().endswith('.pdf'):
        return scrape_pdf_content(url)
    
    logger.info(f"Starting to scrape with Newspaper3k: {url}")
    try:
        article = Article(url)
        article.download()
        article.parse()
        
        # Combine title and text
        content = f"Title: {article.title}\n\n"
        content += article.text
        
        # Add publish date if available
        if article.publish_date:
            content += f"\n\nPublish Date: {article.publish_date}"
        
        # Add authors if available
        if article.authors:
            content += f"\n\nAuthors: {', '.join(article.authors)}"
        
        # Add top image URL if available
        if article.top_image:
            content += f"\n\nTop Image URL: {article.top_image}"
        
        return content
    except Exception as e:
        logger.error(f"Error scraping {url} with Newspaper3k: {e}")
        return ""

def scrape_with_bs4(url, session, max_chars=None):
    try:
        response = session.get(url, timeout=5)
        response.raise_for_status()
        soup = BeautifulSoup(response.content, 'html.parser')
        
        main_content = soup.find('main') or soup.find('article') or soup.find('div', class_='content')
        
        if main_content:
            content = main_content.get_text(strip=True, separator='\n')
        else:
            content = soup.get_text(strip=True, separator='\n')
        
        return content[:max_chars] if max_chars else content
    except Exception as e:
        logger.error(f"Error scraping {url} with BeautifulSoup: {e}")
        return ""

def scrape_with_trafilatura(url, max_chars=None, timeout=5, use_beautifulsoup=False):
    try:
        response = requests.get(url, timeout=timeout)
        response.raise_for_status()
        downloaded = response.text
        content = ""

        if use_beautifulsoup:
            soup = BeautifulSoup(downloaded, "lxml")
            # Convert BeautifulSoup object to a string
            html_string = str(soup)
            # Use Trafilatura's extract function directly on the HTML string
            content = extract(html_string, include_comments=False, include_tables=True, no_fallback=False)
        
        # Fallback mechanism: if BeautifulSoup didn't yield results, try without it
        if not content and use_beautifulsoup:
            logger.info("BeautifulSoup method failed to extract content. Trying without BeautifulSoup.")
            content = extract(downloaded, include_comments=False, include_tables=True, no_fallback=False)
        
        # If still no content, use the URL directly
        if not content:
            content = extract(url, include_comments=False, include_tables=True, no_fallback=False)
        
        return (content or "")[:max_chars] if max_chars else (content or "")
    except requests.Timeout:
        logger.error(f"Timeout error while scraping {url} with Trafilatura")
        return ""
    except Exception as e:
        logger.error(f"Error scraping {url} with Trafilatura: {e}")
        return ""

def rephrase_query(chat_history, query, temperature=0.2):
    system_prompt = """You are a highly intelligent and context-aware conversational assistant. Your task is to accurately rephrase the given query based on the provided conversation context. Follow these steps:
1. Assess whether the new query logically follows from the conversation context or introduces a new, unrelated topic.
2. If it is a continuation, incorporate the most relevant details from the context to make the rephrased query more specific and aligned with the ongoing conversation.
3. If it introduces a new topic, rewrite the query to ensure clarity, precision, and suitability for a standalone search, avoiding any irrelevant context from the conversation.
4. Return ONLY the rephrased query, ensuring it is concise, clear, and contextually accurate, without any additional commentary or explanation."""

    user_prompt = f"""
Conversation context:
{chat_history}

New query: {query}

Rephrased query:
"""

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ]

    try:
        logger.info(f"Sending rephrasing request to LLM with temperature {temperature}")
        response = client.chat_completion(
            messages=messages,
            max_tokens=150,
            temperature=temperature
        )
        logger.info("Received rephrased query from LLM")
        rephrased_question = response.choices[0].message.content.strip()

        # Remove surrounding quotes if present
        if (rephrased_question.startswith('"') and rephrased_question.endswith('"')) or \
           (rephrased_question.startswith("'") and rephrased_question.endswith("'")):
            rephrased_question = rephrased_question[1:-1].strip()

        logger.info(f"Rephrased Query (cleaned): {rephrased_question}")
        return rephrased_question
    except Exception as e:
        logger.error(f"Error rephrasing query with LLM: {e}")
        return query  # Fallback to original query if rephrasing fails

def rerank_documents(query, documents):
    try:
        # Step 1: Encode the query and document summaries
        query_embedding = similarity_model.encode(query, convert_to_tensor=True)
        doc_summaries = [doc['summary'] for doc in documents]
        
        if not doc_summaries:
            logger.warning("No document summaries to rerank.")
            return documents  # Return original documents if there's nothing to rerank
        
        doc_embeddings = similarity_model.encode(doc_summaries, convert_to_tensor=True)
        
        # Step 2: Compute Cosine Similarity
        cosine_scores = util.cos_sim(query_embedding, doc_embeddings)[0]
        
        # Step 3: Compute Dot Product Similarity
        dot_product_scores = torch.matmul(query_embedding, doc_embeddings.T)
        
        # Ensure dot_product_scores is a 1-D tensor
        if dot_product_scores.dim() == 0:
            dot_product_scores = dot_product_scores.unsqueeze(0)
        
        # Combine documents, cosine scores, and dot product scores
        scored_documents = list(zip(documents, cosine_scores, dot_product_scores))

        # Step 4: Sort documents by cosine similarity score
        scored_documents.sort(key=lambda x: x[1], reverse=True)
        
        # Step 5: Return only the top 5 documents
        reranked_docs = [doc[0] for doc in scored_documents[:5]]
        logger.info(f"Reranked to top {len(reranked_docs)} documents.")
        return reranked_docs
    except Exception as e:
        logger.error(f"Error during reranking documents: {e}")
        return documents[:5]  # Fallback to first 5 documents if reranking fails

def compute_similarity(text1, text2):
    # Encode the texts
    embedding1 = similarity_model.encode(text1, convert_to_tensor=True)
    embedding2 = similarity_model.encode(text2, convert_to_tensor=True)
    
    # Compute cosine similarity
    cosine_similarity = util.pytorch_cos_sim(embedding1, embedding2)
    
    return cosine_similarity.item()

def is_content_unique(new_content, existing_contents, similarity_threshold=0.8):
    for existing_content in existing_contents:
        similarity = compute_similarity(new_content, existing_content)
        if similarity > similarity_threshold:
            return False
    return True

def assess_relevance_and_summarize(llm_client, query, document, temperature=0.2):
    system_prompt = """You are a world class AI assistant. Your task is to assess whether the given text is relevant to the user's query and provide a brief summary if it is relevant."""

    user_prompt = f"""
Query: {query}

Document Content:
{document['content']}

Instructions:
1. Assess if the document is relevant to the QUERY  made by the user.
2. If relevant, summarize the main points in 1-2 sentences.
3. If not relevant, simply state "Not relevant".

Your response should be in the following format:
Relevant: [Yes/No]
Summary: [Your 1-2 sentence summary if relevant, or "Not relevant" if not]

Remember to focus on financial aspects and implications in your assessment and summary.
"""

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ]

    try:
        response = llm_client.chat_completion(
            messages=messages,
            max_tokens=150,
            temperature=temperature,
            top_p=0.9
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        logger.error(f"Error assessing relevance and summarizing with LLM: {e}")
        return "Error: Unable to assess relevance and summarize"

def scrape_full_content(url, scraper="bs4", max_chars=3000, timeout=5):
    try:
        logger.info(f"Scraping full content from: {url}")
        
        # Check if the URL ends with .pdf
        if url.lower().endswith('.pdf'):
            return scrape_pdf_content(url, max_chars, timeout)
        
        if scraper == "bs4":
            session = requests_retry_session()
            response = session.get(url, timeout=timeout)
            response.raise_for_status()
            soup = BeautifulSoup(response.content, 'html.parser')
            
            # Try to find the main content
            main_content = soup.find('main') or soup.find('article') or soup.find('div', class_='content')
            
            if main_content:
                content = main_content.get_text(strip=True, separator='\n')
            else:
                content = soup.get_text(strip=True, separator='\n')
        elif scraper == "trafilatura":
            content = scrape_with_trafilatura(url, max_chars, timeout, use_beautifulsoup=True)
        elif scraper == "scrapy":
            content = scrape_with_scrapy(url, timeout)
        elif scraper == "newspaper":
            content = scrape_with_newspaper(url)
        else:
            logger.error(f"Unknown scraper: {scraper}")
            return ""
        
        # Limit the content to max_chars
        return content[:max_chars] if content else ""
    except requests.Timeout:
        logger.error(f"Timeout error while scraping full content from {url}")
        return ""
    except Exception as e:
        logger.error(f"Error scraping full content from {url}: {e}")
        return ""

def llm_summarize(json_input, llm_client, temperature=0.2):
    system_prompt = """You are Sentinel, a world-class Financial analysis AI model who is expert at searching the web and answering user's queries. You are also an expert at summarizing web pages or documents and searching for content in them."""

    user_prompt = f"""
Please provide a comprehensive summary based on the following JSON input:
{json_input}

Instructions:
1. Analyze the query and the provided documents.
2. Write a detailed, long, and complete research document that is informative and relevant to the user's query.
3. Use an unbiased and professional tone in your response.
4. Do not repeat text verbatim from the input.
5. Provide the answer in the response itself.
6. You can use markdown to format your response.
7. Use bullet points to list information where appropriate.
8. Cite the answer using [number] notation along with the appropriate source URL embedded in the notation.
9. Place these citations at the end of the relevant sentences.
10. You can cite the same sentence multiple times if it's relevant to different parts of your answer.

Your response should be detailed, informative, accurate, and directly relevant to the user's query."""

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ]

    try:
        response = llm_client.chat_completion(
            messages=messages,
            max_tokens=10000,
            temperature=temperature,
            frequency_penalty=1.2,
            top_p=0.9
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        logger.error(f"Error in LLM summarization: {e}")
        return "Error: Unable to generate a summary. Please try again."

def search_and_scrape(query, chat_history, num_results=5, scraper="bs4", max_chars=3000, time_range="", language="all", category="", 
                      engines=[], safesearch=2, method="GET", llm_temperature=0.2, timeout=5, use_duckduckgo=False):
    
    try:
        # Step 1: Rephrase the Query
        rephrased_query = rephrase_query(chat_history, query, temperature=llm_temperature)
        logger.info(f"Rephrased Query: {rephrased_query}")

        if not rephrased_query or rephrased_query.lower() == "not_needed":
            logger.info("No need to perform search based on the rephrased query.")
            return "No search needed for the provided input."

        # Step 2: Perform search
        if use_duckduckgo:
            search_results = duckduckgo_search(rephrased_query, num_results, time_range, language, safesearch)
            results = search_results  # Assign DuckDuckGo results directly
        else:
            # Search query parameters
            params = {
                'q': rephrased_query,
                'format': 'json',
                'time_range': time_range,
                'language': language,
                'category': category,
                'engines': ','.join(engines),
                'safesearch': safesearch
            }
    
            # Remove empty parameters
            params = {k: v for k, v in params.items() if v != ""}

            # If no engines are specified, set default engines
            if 'engines' not in params:
                params['engines'] = 'google'  # Default to 'google' or any preferred engine
                logger.info("No engines specified. Defaulting to 'google'.")
    
            # Headers for SearXNG request
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Accept': 'application/json, text/javascript, */*; q=0.01',
                'Accept-Language': 'en-US,en;q=0.5',
                'Origin': 'https://shreyas094-searxng-local.hf.space',
                'Referer': 'https://shreyas094-searxng-local.hf.space/',
                'DNT': '1',
                'Connection': 'keep-alive',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
            }

        scraped_content = []
        page = 1
        while len(scraped_content) < num_results:
            if not use_duckduckgo:
                # Update params with current page
                params['pageno'] = page

                # Send request to SearXNG
                logger.info(f"Sending request to SearXNG for query: {rephrased_query} (Page {page})")
                session = requests_retry_session()

                try:
                    if method.upper() == "GET":
                        response = session.get(SEARXNG_URL, params=params, headers=headers, timeout=10, verify=certifi.where())
                    else:  # POST
                        response = session.post(SEARXNG_URL, data=params, headers=headers, timeout=10, verify=certifi.where())
                    
                    response.raise_for_status()
                except requests.exceptions.RequestException as e:
                    logger.error(f"Error during SearXNG request: {e}")
                    return f"An error occurred during the search request: {e}"

                search_results = response.json()
                logger.debug(f"SearXNG Response: {search_results}")

                results = search_results.get('results', [])
                if not results:
                    logger.warning(f"No more results returned from SearXNG on page {page}.")
                    break

            for result in results:
                if len(scraped_content) >= num_results:
                    break
        
                url = result.get('url', '') if not use_duckduckgo else result.get('url', '')
                title = result.get('title', 'No title')
        
                if not is_valid_url(url):
                    logger.warning(f"Invalid URL: {url}")
                    continue
        
                try:
                    logger.info(f"Processing content from: {url}")
                    
                    content = scrape_full_content(url, scraper, max_chars, timeout)
                    
                    if not content:
                        logger.warning(f"Failed to scrape content from {url}")
                        continue
                    
                    scraped_content.append({
                        "title": title,
                        "url": url,
                        "content": content,
                        "scraper": "pdf" if url.lower().endswith('.pdf') else scraper
                    })
                    logger.info(f"Successfully scraped content from {url}. Total scraped: {len(scraped_content)}")
                except requests.exceptions.RequestException as e:
                    logger.error(f"Error scraping {url}: {e}")
                except Exception as e:
                    logger.error(f"Unexpected error while scraping {url}: {e}")

            if use_duckduckgo:
                break  # DuckDuckGo search doesn't support pagination in this implementation
            else:
                page += 1

        if not scraped_content:
            logger.warning("No content scraped from search results.")
            return "No content could be scraped from the search results."

        logger.info(f"Successfully scraped {len(scraped_content)} documents.")

        # Step 3: Assess relevance, summarize, and check for uniqueness
        relevant_documents = []
        unique_summaries = []
        for doc in scraped_content:
            assessment = assess_relevance_and_summarize(client, rephrased_query, doc, temperature=llm_temperature)
            relevance, summary = assessment.split('\n', 1)
            
            if relevance.strip().lower() == "relevant: yes":
                summary_text = summary.replace("Summary: ", "").strip()
                
                if is_content_unique(summary_text, unique_summaries):
                    relevant_documents.append({
                        "title": doc['title'],
                        "url": doc['url'],
                        "summary": summary_text,
                        "scraper": doc['scraper']
                    })
                    unique_summaries.append(summary_text)
                else:
                    logger.info(f"Skipping similar content: {doc['title']}")

        if not relevant_documents:
            logger.warning("No relevant and unique documents found.")
            return "No relevant and unique financial news found for the given query."
            logger.debug(f"Assessment result: {assessment}")

        # Step 4: Rerank documents based on similarity to query
        reranked_docs = rerank_documents(rephrased_query, relevant_documents)
        
        if not reranked_docs:
            logger.warning("No documents remained after reranking.")
            return "No relevant financial news found after filtering and ranking."
        
        logger.info(f"Reranked and filtered to top {len(reranked_docs)} unique, finance-related documents.")

        # Step 5: Scrape full content for top documents (up to num_results)
        for doc in reranked_docs[:num_results]:
            full_content = scrape_full_content(doc['url'], scraper, max_chars)
            doc['full_content'] = full_content
    
        # Prepare JSON for LLM
        llm_input = {
            "query": query,
            "documents": [
                {
                    "title": doc['title'],
                    "url": doc['url'],
                    "summary": doc['summary'],
                    "full_content": doc['full_content']
                } for doc in reranked_docs[:num_results]
            ]
        }
    
        # Step 6: LLM Summarization
        llm_summary = llm_summarize(json.dumps(llm_input), client, temperature=llm_temperature)
    
        return llm_summary

    except Exception as e:
        logger.error(f"Unexpected error in search_and_scrape: {e}")
        return f"An unexpected error occurred during the search and scrape process: {e}"


def chat_function(message, history, num_results, scraper, max_chars, time_range, language, category, engines, safesearch, method, llm_temperature, use_duckduckgo):
    chat_history = "\n".join([f"{role}: {msg}" for role, msg in history])
    
    response = search_and_scrape(
        query=message,
        chat_history=chat_history,
        num_results=num_results,
        scraper=scraper,
        max_chars=max_chars,
        time_range=time_range,
        language=language,
        category=category,
        engines=engines,
        safesearch=safesearch,
        method=method,
        llm_temperature=llm_temperature,
        use_duckduckgo=use_duckduckgo
    )
    
    yield response

iface = gr.ChatInterface(
    chat_function,
    title="Web Scraper for Financial News",
    description="Enter your query, and I'll search the web for the most recent and relevant financial news, scrape content, and provide summarized results.",
    theme=gr.Theme.from_hub("allenai/gradio-theme"),
    additional_inputs=[
        gr.Slider(5, 20, value=10, step=1, label="Number of initial results"),
        gr.Dropdown(["bs4", "trafilatura", "scrapy", "newspaper"], value="newspaper", label="Scraping Method"),
        gr.Slider(500, 10000, value=1500, step=100, label="Max characters to retrieve"),
        gr.Dropdown(["", "day", "week", "month", "year"], value="", label="Time Range"),
        gr.Dropdown(["", "all", "en", "fr", "de", "es", "it", "nl", "pt", "pl", "ru", "zh"], value="", label="Language"),
        gr.Dropdown(["", "general", "news", "images", "videos", "music", "files", "it", "science", "social media"], value="", label="Category"),
        gr.Dropdown(
            ["google", "bing", "duckduckgo", "baidu", "yahoo", "qwant", "startpage"],
            multiselect=True,
            value=["google", "duckduckgo", "bing", "qwant"],
            label="Engines"
        ),
        gr.Slider(0, 2, value=2, step=1, label="Safe Search Level"),
        gr.Radio(["GET", "POST"], value="POST", label="HTTP Method"),
        gr.Slider(0, 1, value=0.2, step=0.1, label="LLM Temperature"),
        gr.Checkbox(label="Use DuckDuckGo Search", value=False),
    ],
    additional_inputs_accordion=gr.Accordion("⚙️ Advanced Parameters", open=True),
    retry_btn="Retry",
    undo_btn="Undo",
    clear_btn="Clear",
    chatbot=gr.Chatbot(
        show_copy_button=True,
        likeable=True,
        layout="bubble",
        height=500,
    )
)

if __name__ == "__main__":
    logger.info("Starting the SearXNG Scraper for Financial News using ChatInterface with Advanced Parameters")
    iface.launch(share=True)