Spaces:
Runtime error
Runtime error
File size: 15,056 Bytes
26ef710 707620f 26ef710 c64ef0e 26ef710 707620f 26ef710 707620f 26ef710 707620f 26ef710 03036da 26ef710 03036da 26ef710 03036da 26ef710 03036da 26ef710 bd6783b 26ef710 bd6783b 26ef710 7c1e061 26ef710 03036da 26ef710 03036da 26ef710 7c1e061 26ef710 7c1e061 26ef710 bd6783b 26ef710 bd6783b 26ef710 bd6783b 26ef710 bd6783b 26ef710 bd6783b 26ef710 bd6783b 26ef710 bd6783b 26ef710 |
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 |
import gradio as gr
import os
import re
import requests
import tempfile
import time
from pyzotero import zotero
from paperqa import Docs
from lxml import html
from models import Icons, Message
def is_integer(string):
try:
int(string)
except ValueError:
return False
else:
return True
def reset_open_ai(openai_api_key):
os.environ['OPENAI_API_KEY'] = openai_api_key.strip()
return gr.HTML.update(value=None)
def fetch_collections(openai_api_key, id, type, key, messages):
if openai_api_key == '':
messages.append(
Message(Icons.ERR, f"Your Open API key is missing. Check out: <a href='https://platform.openai.com/overview' target='_blank'>https://platform.openai.com/overview</a>."))
return (
None,
[],
None,
gr.Button.update(visible=True),
gr.HTML.update(visible=True),
messages,
gr.HTML.update(value=str(messages)),
)
if key == '':
messages.append(
Message(Icons.ERR, f"Your Zotero API key is missing. Click <a href='https: // www.zotero.org/settings/keys/new' target='_blank'>here</a> to create a new one."))
return (
None,
[],
None,
gr.Button.update(visible=True),
gr.HTML.update(visible=True),
messages,
gr.HTML.update(value=str(messages)),
)
if not is_integer(id):
messages.append(
Message(Icons.ERR, f"Your Zotero ID should be an integer."))
return (
None,
[],
None,
gr.Button.update(visible=True),
gr.HTML.update(visible=True),
messages,
gr.HTML.update(value=str(messages)),
)
zot = zotero.Zotero(int(id), type.lower(), key)
try:
collections = zot.collections_top()
collection_names = [
f"{x['data']['name']} ({x['meta']['numItems']})" for x in collections]
messages.append(
Message(Icons.INFO, "Please select a Zotero collection to proceed."))
return (
zot,
collections,
gr.Radio.update(choices=collection_names,
visible=True, interactive=True),
gr.Button.update(visible=False),
gr.HTML.update(visible=False),
messages,
gr.HTML.update(value=str(messages)),
)
except Exception as e:
messages.append(
Message(Icons.ERR, f"Error occurred when fetching Zotero collection: {e}"))
return (
None,
[],
None,
gr.Button.update(visible=True),
None,
messages,
gr.HTML.update(value=str(messages)),
)
def select_collection(collection, messages):
if collection is None:
return None, messages, gr.HTML.update(), None
collection_name = re.sub('\s\(\d+\)$', '', collection)
messages.set([Message(
Icons.OK, f"Selected collection: <span style='font-weight: bold'>{collection_name}</span>. Please type your question and hit \"Enter\".")])
return (
gr.Text.update(
placeholder="Please type your question and hit \"Enter\".", interactive=True),
messages,
gr.HTML.update(value=str(messages)),
gr.HTML.update(value=None)
)
# def search_attachments(id, type, key, collection, queries=[], limit=10):
# try:
# zot = zotero.Zotero(int(id), type.lower(), key)
# searches = [zot.collection_items(
# collection['key'],
# q=q,
# limit=limit,
# itemType='attachment',
# qmode='everything'
# ) for q in queries]
# attachments = [x for x in {item['key']: item for search in searches for item in search if item['data']
# ['contentType'] == 'application/pdf'}.values()][:limit]
# parents = set([a['data']['parentItem'] for a in attachments])
# message = f"<div>✅ Found {len(attachments)} PDF {'attachments' if len(attachments) > 1 else 'attachment'} from {len(parents)} {'articles' if len(parents) > 1 else 'article'}.</div>" if len(
# attachments) else "<div>❔ No results. Make sure to index your PDF attachments in Zotero.</div>"
# return parents, attachments, message
# except Exception as e:
# message = f"<div>⚠️ Error occurred when searching in Zotero: {e}</div>"
# return [], [], message
def download_attachment(id, type, key, attachment):
zot = zotero.Zotero(int(id), type.lower(), key)
link_mode = attachment['data']['linkMode']
if link_mode == 'imported_file':
return zot.file(attachment['key'])
elif link_mode == 'imported_url':
res = requests.get(attachment['data']['url'])
return res.content
else:
raise ValueError(
f'Unsupported link mode: {link_mode} for {attachment["key"]}.')
def reset_collection(messages):
messages.set([Message(
Icons.INFO, "Please provide all the required OpenAI and Zotero information in the left panel.")])
return (
gr.Radio.update(choices=[], visible=False),
gr.HTML.update(visible=True),
gr.Text.update(
placeholder="You have to select a Zotero collection to proceed", interactive=False),
gr.HTML.update(value=None),
messages,
gr.HTML.update(value=str(messages)),
None
)
def handle_submit(zot, collection_name, collections, style, question, messages):
collection_name_only = re.sub('\s\(\d+\)$', '', collection_name)
messages.set([Message(
Icons.OK, f"Selected collection: <span style='font-weight: bold'>{collection_name_only}</span>.")])
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
docs = Docs()
# Generate search queries from the question by Paper QA
try:
question_prompt = 'A "keyword search" is a list of no more than 3 words, which separated by whitespace only and with no boolean operators (e.g. "dog canine puppy"). Avoid adding any new words not in the question unless they are synonyms to the existing words.'
queries = [x.strip('"').lower() for x in
docs.generate_search_query(question + '\n' + question_prompt)]
query_str = ", ".join(
[f"<span style='font-weight: bold;'>{q}</span>" for q in queries])
messages.append(
Message(Icons.WAIT, f"Searching your Zotero collection for {query_str}."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
except Exception as e:
messages.append(
Message(Icons.ERR, f"Error occurred when generating search queries: {e}"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
return None, None, None
# Search for attachments in Zotero
try:
collection = [
x for x in collections if f"{x['data']['name']} ({x['meta']['numItems']})" == collection_name][0]
searches = [zot.collection_items(
collection['key'],
q=q,
limit=10,
itemType='attachment',
qmode='everything'
) for q in queries]
attachments = [x for x in {
item['key']: item for search in searches for item in search if item['data']['contentType'] == 'application/pdf'}.values()][:10]
parents = set([a['data']['parentItem'] if 'parentItem' in a['data'] else a['key'] for a in attachments ])
if len(attachments) > 0:
messages.append(Message(
Icons.SUCCESS, f"Found {len(attachments)} PDF {'attachments' if len(attachments) > 1 else 'attachment'} from {len(parents)} {'articles' if len(parents) > 1 else 'article'}."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
else:
messages.append(Message(
Icons.ERR, "No results. Make sure to index your PDF attachments in Zotero and try rephrasing your question."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
return None, None, None
except Exception as e:
messages.append(
Message(Icons.ERR, f"Error occurred when searching in Zotero: {e}"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
return None, None, None
# Compile citation metadata
citation_dict = {}
parents = {}
messages.append(
Message(Icons.WAIT, f"Fetching attachment bibliography information."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
for attachment in attachments:
parent_id = attachment["data"]["parentItem"] if "parentItem" in attachment["data"] else attachment["key"]
try:
if parent_id in parents:
citation_dict[attachment["key"]] = parents[parent_id]
else:
parent = zot.item(
parent_id, content="bib", style=style)[0]
bib = f"""
{html.fragment_fromstring(parent).xpath("normalize-space(//*)")}
<a href="{attachment['links']['alternate']['href']}" target="_blank" class="zotero-link">Open in Zotero</a>
"""
parents[parent_id] = bib
citation_dict[attachment["key"]] = bib
except Exception as e:
messages.append(Message(
Icons.WARN, f"Failed to retrieve bibliography for PDF attachment <a href='{attachment['links']['alternate']['href']}' target='_blank'>{attachment['data']['title']}</a>: {e}"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
# Load attachments
available_attachments = 0
for attachment in attachments:
try:
link_mode = attachment['data']['linkMode']
if link_mode in ['imported_file', 'imported_url']:
attachment_content = zot.file(attachment['key']) if link_mode == 'imported_file' else requests.get(
attachment['data']['url']).content
temp_file = tempfile.NamedTemporaryFile(suffix=".pdf")
temp_file.write(attachment_content)
temp_file.flush()
docs.add(temp_file.name, citation_dict[attachment["key"]])
messages.append(Message(
Icons.INDEX, f"Loaded PDF attachment: <a href='{attachment['links']['alternate']['href']}' target='_blank'>{attachment['data']['title']}</a>."))
available_attachments += 1
else:
messages.append(Message(
Icons.WARN, f"Unable to access linked PDF attachment <a href='{attachment['links']['alternate']['href']}' target='_blank'>{attachment['data']['title']}</a>: The file is not in Zotero online storage."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
except Exception as e:
messages.append(Message(
Icons.WARN, f"Failed to retrieve PDF attachment <a href='{attachment['links']['alternate']['href']}' target='_blank'>{attachment['data']['title']}</a>: {e}"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
# Build vector index
if available_attachments == 0:
messages.append(Message(
Icons.ERR, "No answer. Unable to access any PDF attachments from your Zotero online storage or public URLs."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
return None, None, None
if docs._faiss_index is None:
try:
messages.append(Message(
Icons.WAIT, f"Building vector index based on {available_attachments} available PDF {'attachment' if available_attachments==1 else 'attachments'}."))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
docs._build_faiss_index()
except Exception as e:
messages.append(Message(
Icons.ERR, f"Unable to build vector index: {e}"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
return None, None, None
# Synthesize response
messages.append(Message(
Icons.WAIT, f"""Creating answer. {"This should be done within a minute." if available_attachments==1 else "This will loop through all available PDF attachments and may take a couple of minutes."}."""))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
try:
start_time = time.time()
total_time = 0
for i, answer in enumerate(docs.query_gen(question)):
end_time = time.time()
time_dif = end_time - start_time
if time_dif > 15:
start_time = end_time
total_time += time_dif
messages.append(Message(
Icons.INFO, f"Still in prgress: {total_time:.1f} seconds"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
answer_text = "\n".join(
[f"<div>{x}</div>" for x in answer.answer.split("\n")])
reference_list = "" if answer.references == "" else "\n".join([f"<li>{x.split('.', 1)[1]}</li>"
for x in answer.references.split('\n\n')])
references = "" if reference_list == "" else f"""
<h4 style="font-size: 1rem;">References:</h4>
<ol>
{reference_list}
</ol>
"""
formatted_answer = f"""
<div>{answer_text}</div>
{references}
<div>Tokens Used: {answer.tokens} Cost: ${answer.tokens/1000 * 0.002:.2f}</div>
""".strip()
messages.append(Message(
Icons.OK, f"Answer created."))
yield (
messages,
gr.HTML.update(value=str(messages)),
gr.HTML.update(value=formatted_answer)
)
except Exception as e:
messages.append(Message(
Icons.ERR, f"Error occurred when creating answer: {e}"))
yield (
messages,
gr.HTML.update(value=str(messages)),
None,
)
return None, None, None
|