shikharyashmaurya
commited on
Commit
•
3e8b0d8
1
Parent(s):
183505a
Upload improved-fact-checker-app.py
Browse files- improved-fact-checker-app.py +100 -0
improved-fact-checker-app.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import google.generativeai as genai
|
3 |
+
import ast
|
4 |
+
import time
|
5 |
+
# import os
|
6 |
+
import re
|
7 |
+
from typing import List, Tuple, Optional
|
8 |
+
|
9 |
+
def extract_python_code(text: str) -> Optional[str]:
|
10 |
+
pattern = r"```python\n(.*?)```"
|
11 |
+
match = re.search(pattern, text, re.DOTALL)
|
12 |
+
return match.group(1).strip() if match else None
|
13 |
+
|
14 |
+
def configure_genai():
|
15 |
+
secret_key = 'AIzaSyBK7WgO74DGM0xZJc5f9lTITQK9c50xJN4'#os.getenv("SECRET_KEY")
|
16 |
+
if not secret_key:
|
17 |
+
st.error("API key not found. Please set the SECRET_KEY environment variable.")
|
18 |
+
st.stop()
|
19 |
+
genai.configure(api_key=secret_key)
|
20 |
+
|
21 |
+
def parse_gemini_response(response_text: str) -> Tuple[str, str]:
|
22 |
+
try:
|
23 |
+
parsed = ast.literal_eval(response_text)
|
24 |
+
if isinstance(parsed, list) and len(parsed) == 2:
|
25 |
+
return parsed[0], parsed[1]
|
26 |
+
raise ValueError("Unexpected response format")
|
27 |
+
except Exception as e:
|
28 |
+
return "Error", f"Failed to parse response: {str(e)}"
|
29 |
+
|
30 |
+
def get_gemini_response(input_text: str) -> Tuple[str, str]:
|
31 |
+
prompt = """You are a fact checker. Given a text, respond with:
|
32 |
+
1. 'True', 'False', or 'Unsure' (if you are unsure or knowledge cutoff)
|
33 |
+
2. Evidence in support or 'knowledge cutoff'
|
34 |
+
|
35 |
+
Respond in this exact format: ['True/False/Unsure', 'evidence or knowledge cutoff']
|
36 |
+
Example input: 'Google was founded in 1998'
|
37 |
+
Example output: ['True', 'Google was indeed founded in September 1998 by Larry Page and Sergey Brin']
|
38 |
+
|
39 |
+
Now give a response in the exact described format for the following text:
|
40 |
+
"""
|
41 |
+
model = genai.GenerativeModel('gemini-1.5-pro')
|
42 |
+
try:
|
43 |
+
response = model.generate_content(prompt + input_text)
|
44 |
+
result, evidence = parse_gemini_response(response.text)
|
45 |
+
return result, evidence
|
46 |
+
except Exception as e:
|
47 |
+
return "Error", f"Failed to get or parse the model's response: {str(e)}"
|
48 |
+
|
49 |
+
def generate_interesting_facts(topic: str) -> List[str]:
|
50 |
+
prompt = f"""Generate up to 10 interesting facts about the following topic.
|
51 |
+
Return only a Python list of strings, with each string being a single fact.
|
52 |
+
Topic: {topic}
|
53 |
+
"""
|
54 |
+
model = genai.GenerativeModel('gemini-1.5-pro')
|
55 |
+
try:
|
56 |
+
response = model.generate_content(prompt)
|
57 |
+
code = extract_python_code(response.text)
|
58 |
+
facts = ast.literal_eval(code) if code else []
|
59 |
+
return facts if isinstance(facts, list) else []
|
60 |
+
except Exception as e:
|
61 |
+
st.error(f"Failed to generate facts: {str(e)}")
|
62 |
+
return []
|
63 |
+
|
64 |
+
def main():
|
65 |
+
st.title("Verified Interesting Fact Generator")
|
66 |
+
configure_genai()
|
67 |
+
|
68 |
+
topic = st.text_input('Enter a topic to generate interesting facts about (e.g., "Elephants", "Mars")')
|
69 |
+
|
70 |
+
if st.button("Generate and Verify Facts"):
|
71 |
+
if not topic:
|
72 |
+
st.warning("Please enter a topic.")
|
73 |
+
return
|
74 |
+
|
75 |
+
with st.spinner('Generating facts...'):
|
76 |
+
facts = generate_interesting_facts(topic)
|
77 |
+
|
78 |
+
if not facts:
|
79 |
+
st.error("Failed to generate facts. Please try a different topic or try again later.")
|
80 |
+
return
|
81 |
+
|
82 |
+
st.subheader(f"Verified Interesting Facts about {topic}:")
|
83 |
+
for fact in facts:
|
84 |
+
with st.expander(fact):
|
85 |
+
with st.spinner('Verifying...'):
|
86 |
+
result, evidence = get_gemini_response(fact)
|
87 |
+
|
88 |
+
if result.lower() == "true":
|
89 |
+
st.success(f"Likely True: {evidence}")
|
90 |
+
elif result.lower() == "false":
|
91 |
+
st.error(f"Likely False: {evidence}")
|
92 |
+
elif result.lower() == "unsure":
|
93 |
+
st.warning(f"Uncertain: {evidence}")
|
94 |
+
else:
|
95 |
+
st.error(f"Error in fact-checking: {evidence}")
|
96 |
+
|
97 |
+
time.sleep(4) # Delay to avoid rate limiting
|
98 |
+
|
99 |
+
if __name__ == "__main__":
|
100 |
+
main()
|