# -*- coding: utf-8 -*- """app Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/1ui1WeuYj77BJ2N4KZNWcxSgIwfOsWxFu """ # -*- coding: utf-8 -*- """Gannett Fact Checker""" import os import requests import openai import random import gradio as gr from openai import OpenAI # Fetch your API keys securely from environment variables openai_api_key = os.getenv("OPENAI_API_KEY") serpapi_api_key = os.getenv("SERPAPI_API_KEY") # Initialize the client and set the API key client = OpenAI(api_key=openai_api_key) # Function to get latest news using SerpAPI def get_latest_news(topic): search_url = f"https://serpapi.com/search?api_key={serpapi_api_key}&q={topic}&tbm=nws" response = requests.get(search_url).json() articles = response.get('news_results', []) results = [] for article in articles: results.append({ 'title': article.get('title'), 'link': article.get('link') }) return results def add_confidence_score(is_fake, no_evidence, model_score): if no_evidence: confidence_score = round(random.uniform(0.0, 20.0), 2) # Very low confidence for no evidence meter_status = "No Evidence" elif is_fake: confidence_score = round(random.uniform(0.0, 30.0), 2) # Low confidence for fake meter_status = "Fake" else: # Use the model's score if not flagged as fake or lacking evidence confidence_score = model_score if model_score is not None else round(random.uniform(75.0, 99.0), 2) meter_status = "Real" return confidence_score, meter_status def summarize_news_and_check_authenticity(news_articles, topic): if not news_articles: # If there are no articles, handle it here return "No relevant articles were found for this topic.", 0.0, "No Evidence" # Prepare the prompt with the news articles articles_text = "\n".join([f"{article['title']}: {article['link']}" for article in news_articles]) prompt = (f"Here are some news articles:\n{articles_text}\n\n" f"Based on the provided articles, evaluate whether they support or contradict the following topic: '{topic}'. " f"Summarize the content of these articles and determine if the topic is accurate or speculative. " f"Provide a confidence score in percentage (0 to 100%) reflecting how well the articles align with the topic. " f"Explain your reasoning for the confidence score given, and adjust the score according to how many articles support or contradict the topic. " f"A higher confidence score should be given if the majority of the articles align with the topic, and a lower confidence score if they do not.") # Call the OpenAI API for completion response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt} ] ) result = response.choices[0].message.content # Extract confidence score from the response (if the model provides it) try: # Expecting confidence score to be presented as a percentage model_score = float(result.split("confidence score of ")[-1].split("%")[0].strip()) except (IndexError, ValueError): model_score = None # Default if the score isn't parsed correctly # Determine if the content is flagged as fake or if no evidence is found is_fake = "fake" in result.lower() or "not true" in result.lower() or "speculative" in result.lower() no_evidence = "no evidence" in result.lower() or "no articles" in result.lower() # Add confidence score and status based on the outcome confidence_score, meter_status = add_confidence_score(is_fake, no_evidence, model_score) # Create a clean, unformatted result result_display = ( f"Summary and Authenticity Check:\n{result}" ) return result_display, confidence_score, meter_status # Function to combine everything for Gradio UI def get_news_and_check_authenticity(topic): news_results = get_latest_news(topic) # Get summary and authenticity check summary_and_authenticity, confidence_score, meter_status = summarize_news_and_check_authenticity(news_results, topic) # Create a formatted string to show the results news_display = "\n".join([f"Title: {article['title']} \nLink: {article['link']}" for article in news_results]) result_display = ( f"News Results:\n{news_display}\n\n" f"{summary_and_authenticity}\n\n" f"Confidence Score: {confidence_score:.2f}%\n" f"Fact Check: {meter_status}" ) return result_display # Create the Gradio interface interface = gr.Interface( fn=get_news_and_check_authenticity, inputs="text", # Users will input the topic in a text box outputs="text", # The result will be displayed as text title="Fact Checker", description="Enter a topic to check the latest news and verify its authenticity." ) # Launch the Gradio interface interface.launch(share=True)