-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
176 lines (121 loc) · 5.89 KB
/
main.py
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
import google.generativeai as ai
import streamlit as st
import time
from googlesearch import search
import requests
with st.sidebar:
api_key = st.text_input("Drop your google api key below below ⬇️",type="password")
ai.configure(api_key=api_key)
model = ai.GenerativeModel(model_name="gemini-1.5-pro-latest")
llm_output = ""
st.title("LLM verify")
st.markdown(":green[Verify outputs generated by llms\nwith realtime data 🛜📈]")
st.write("<br>", unsafe_allow_html=True)
st.write("<br>", unsafe_allow_html=True)
llm_output = st.text_area("Enter the output that needs to be verefied")
def summarize_core_claims(user_q):
a = user_q
response = model.generate_content(f'Hey youre a reponsible assistant, you need to only summarize the main claims made in this given text data, only give output in bulleted format directly, nothing else. Heres it: + {a}')
result = response.text
return result
def get_search_terms(texts):
find_search_query = texts
response = model.generate_content(f"Youre an responsible assistant, you need to output the search query to find relevant articles related to the given text data, be direct, but include related keywords, only output search query nothing else. heres the data: {find_search_query}")
st.write(response.text)
return response.text
def search_find_relevant_articles(q):
query = q
links = []
for result in search(query,5):
links.append(result)
return links
def summarize_web_content(m):
key_points_webdata = {}
for key, value in m.items():
response = model.generate_content(f"Heres the article, what you need to do is find the core points/claims made in it. Only output what is said nothing else. heres the article: {value}")
key_points_webdata[key] = response.text
return key_points_webdata
def final_scoring_ranking(webcontent, res):
model = ai.GenerativeModel('models/gemini-pro')
accuracy_scores = []
content_to_verify = res
realtime_results = webcontent
for value in realtime_results.values():
try:
response = model.generate_content(f"Hi here are 2 pieces of data A and B. A is the data that needs to be verfied. To do so use B as a source. Compare A with B, depending on how similar they both are give a score between (1 to 100)%, if they arent same at all then keep the score below 50%. Also if no data present then just reply 0%. ONLY REPLY with the score nothing else. Heres the data: A -> {content_to_verify} \n B -> {value}")
accuracy_scores.append(int(response.text.rstrip('%')))
except ValueError as e:
st.error(f"Error occured unfortunately: {e}. Response: {response.text}")
return accuracy_scores
def access_content_from_links(l):
model = ai.GenerativeModel('models/gemini-pro')
link = l
sourceData = {}
def get_markdown_content(url):
urli = "https://r.jina.ai/" + url
response = requests.get(urli)
if response.status_code == 200:
markdownC = response.text
else:
markdownC = f"error: {response.status_code}"
return markdownC
for i in range(5):
website = link[i]
response = model.generate_content(f"Here the website link, using it just tell me the website domain name. dont output anything else except correct website name and if there's an url which links to a .pdf or any document file then just reply VOID. Heres the link: {website}")
if response.text == "VOID":
sourceData["Void"] = "Data not avaiable"
else:
sourceData[f"{response.text}"] = get_markdown_content(link[i])
return sourceData
def ask_AI(user_q):
a = user_q
sources = []
with st.status("Working on it..."):
result = summarize_core_claims(a)
time.sleep(2)
st.write("Finding parameters...")
search_terms = get_search_terms(result)
time.sleep(2)
st.write("Searching the web...")
search_output = search_find_relevant_articles(search_terms)
time.sleep(2)
st.write("Converting data to markdown.")
markdownContent = access_content_from_links(search_output)
st.write("Finding insights from the data")
time.sleep(1)
st.write("This process might take sometime, relax")
webContent_summary = summarize_web_content(markdownContent)
st.write("Almost done, now checking accuracy...")
time.sleep(1)
finalScoring = final_scoring_ranking(webContent_summary, result)
st.write("Got accuracy score")
for key in webContent_summary:
sources.append(key)
percentCalculate = sum(finalScoring)/len(finalScoring)
sourceFilter = ""
for i in range(len(sources)):
if str(sources[i]).lower() != "void":
sourceFilter += f"\n{i+1}. [{sources[i]}](https://www.{sources[i]}) \n"
else:
pass
percent= f"This given data is {percentCalculate}% accurate\n"
source = f"Sources considered: {sourceFilter}"
st.write("Got sources..")
time.sleep(0.3)
st.write("Completed!")
return percent, source
def loadSpinner():
if llm_output != "":
pass
else:
st.error("Hey, you need to input something first, then click on verify!")
button_click = st.button("Verify", on_click=loadSpinner)
if button_click:
if llm_output != "":
st.write("<br>", unsafe_allow_html=True)
with st.container(border=True):
takeP, takeS = ask_AI(llm_output)
st.markdown(f"{takeP} <br> {takeS}", unsafe_allow_html=True)
st.write("<br>", unsafe_allow_html=True)
st.success("Done!")
st.container()