Rams901 commited on
Commit
3c528ae
1 Parent(s): f936bb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -212
app.py CHANGED
@@ -148,220 +148,8 @@ def jsonify_articles(query, tier_1 = None):
148
 
149
  return json_articles
150
 
151
- def qa_retrieve(query, media):
152
-
153
- docs = ""
154
-
155
- global mp_docs
156
- thoughts = retrieve_thoughts(query, media)
157
- if not(thoughts):
158
-
159
- if mp_docs:
160
- thoughts = mp_docs
161
- else:
162
- mp_docs = thoughts
163
-
164
- tier_1 = thoughts['tier 1']
165
- tier_2 = thoughts['tier 2']
166
-
167
- reference = tier_1[['ref', 'url', 'title']].to_dict('records')
168
-
169
- tier_1 = list(tier_1.apply(lambda x: f"ref: [{int(x['ref'])}]\ntitle: {x['title']}\n Content: {x.content}", axis = 1).values)
170
- tier_2 = list(tier_2.apply(lambda x: f"title: {x['title']}\n Content: {x.content}", axis = 1).values)
171
- print(f"QUERY: {query}\nTIER 1: {tier_1}\nTIER2: {tier_2}")
172
-
173
- # print(f"DOCS RETRIEVED: {mp_docs.values}")
174
- # Cynthesis Generation
175
-
176
- session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to you. You will generate a rich synthesis with numerous arguments extracted from the sources given."""
177
- # task = """Create a coherent synthesis in which you use references to the id of articles provided and relevant to the query.
178
-
179
- # Follow the example structure:
180
-
181
- # The best wine to pair with steak depends on the cut of steak and the preparation. Here are some general guidelines for pairing wine with steak:
182
- # - Choose a dry red wine. The rule of thumb is to choose dry red wines
183
- # - leaner cuts of meat pair with lighter wines, while richer, fattier cuts pair up with high tannin wines that can cut through the fat [1].
184
- # - Consider the cut of steak. Lighter red wines tend to go best with the leaner cuts of steak such as filet mignon, while more marbled, higher fat cuts of meat like a rib eye do well when accompanied by more robust red wines [3].
185
- # - Take into account the preparation. For a spiced steak, go for a wine with lots of fruit to balance out the heat, like an Old Vine Zinfandel. And if you're drowning your steak in a decadent sauce, find a wine with enough body to stand up to it, like a Cabernet Sauvignon [5].
186
- # - Popular wine choices include Cabernet Sauvignon, Pinot Noir, Zinfandel, Malbec, Syrah, and Merlot [2].
187
- # Remember, the goal is to choose a wine that complements the cut of steak and not overwhelm or take away from the flavor of the meat [3]."
188
- # """
189
- articles = grab_jsons(query, tier_1 = tier_1)
190
- prompt = PromptTemplate(
191
- input_variables=["query", "session_prompt", "articles"],
192
- template="""
193
- You are a {session_prompt}
194
- Create a rich well-structured synthesis in which you use references to the id of articles provided and relevant to the query.
195
- The Synthesis should include at least 500 words englobing all prespectives found in the sources.
196
-
197
- Follow the example structure:
198
- User: What are the secondary effects of covid?
199
- Synthesis: \nSecondary effects of COVID-19, often referred to as \"Long COVID\", are a significant concern. These effects are not limited to the acute phase of the disease but persist well past the first month, affecting various organ systems and leading to adverse outcomes such as all-cause death and hospitalization [1]. \n\nOne of the most alarming secondary effects is the increased risk of cardiovascular diseases. Studies have shown a 1.6-fold increased risk of stroke and a 2-fold higher risk of acute coronary disease in individuals who had COVID-19 [2][3][8]. These risks were observed even in younger populations, with a mean age of 44, and were prevalent after 30 days post-infection [2][3]. \n\nAnother study found that the adverse outcomes of COVID-19 could persist up to the 2-year mark, with the toll of adverse sequelae being worst during the first year [3]. The study also highlighted that individuals with severe COVID-19, who were hospitalized, were more likely to be afflicted with protracted symptoms and new medical diagnoses [3]. \n\nHowever, it's important to note that the risks associated with Long COVID might be most significant in the first few weeks post-infection and fade away as time goes on [4][9]. For instance, the chance of developing pulmonary embolism was found to be 32 times higher in the first month after testing positive for COVID-19 [4]. \n\nMoreover, the number of excess deaths in the U.S., which would indicate fatal consequences of mild infections at a delay of months or years, dropped to zero in April, about two months after the end of the winter surge, and have stayed relatively low ever since [4]. This suggests that a second wave of deaths—a long-COVID wave—never seems to break [4]. \n\nIn conclusion, while the secondary effects of COVID-19 are significant and can persist for a long time, the most severe risks seem to occur in the first few weeks post-infection and then gradually decrease. However, the full extent of the long-term effects of COVID-19 is still unknown, and further research is needed to fully understand the ways and extent COVID-19 has affected us.",
200
-
201
- query: {query}
202
-
203
- Articles:
204
- {articles}
205
-
206
- Make sure to quote the article used if the argument corresponds to the query. Add as many arguments and point of views as possible as long as they have a reference.
207
- Keep your answer direct and use careful reasoning and professional writing for the synthesis. No need to mention your interaction with articles.
208
- Remember not to mention articles used at the beginning of sentences, keep it cohesive and rich in text while referencing as much as possible of sources given.
209
- """,
210
- )
211
-
212
-
213
- # llm = BardLLM()
214
- chain = LLMChain(llm=claude2, prompt = prompt)
215
-
216
- consensus = chain.run(query=query, articles=articles, session_prompt = session_prompt,)
217
- consensus = consensus[consensus.index(':')+1:].strip()
218
-
219
- if "In conclusion" in consensus:
220
- consensus = consensus[:consensus.index('In conclusion')]
221
- intro = qa_intro(query, consensus, articles)
222
- conclusion = qa_conclusion(query, consensus, articles)
223
- cynthesis = intro + "\n\n" + consensus + "\n\n" + conclusion
224
-
225
- # for i in range(1, len(tier_1)+1):
226
- # response = response.replace(f'[{i}]', f"<span class='text-primary'>[{i}]</span>")
227
-
228
-
229
- # json_resp = {'cynthesis': response, 'questions': questions, 'reference': reference}
230
-
231
- return cynthesis
232
-
233
- def qa_intro(query, cynthesis, tier_1,):
234
-
235
-
236
- llm = ClaudeLLM()
237
- llm_4 = ChatOpenAI(
238
- temperature=0,
239
- model='gpt-3.5-turbo-16k'
240
- )
241
-
242
- session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""
243
-
244
- prompt = PromptTemplate(
245
- input_variables=["query", "cynthesis", "articles"],
246
- template="""
247
- Give me an introduction to the following consensus without repeating how it starts. Consider this an abstract. And after finishing the introduction, pick one quote from the sources given below.
248
-
249
- query: {query}
250
- Here's the consensus: {cynthesis}
251
-
252
- We have the opportunity to give an introduction to this synthesis without repeating information found.
253
- Pick an opening quote from the sources given below\n
254
- ---------\n
255
- {articles}
256
- ---------\n
257
-
258
- Don't forget that your job is to only provide an introduction, abstract part that introduces the synthesis without repeating it and then pick one general quote from the sources given.""",
259
- )
260
-
261
-
262
- # llm = BardLLM()
263
- chain = LLMChain(llm=llm_4, prompt = prompt)
264
-
265
- intro = chain.run(query=query, articles=tier_1, cynthesis = cynthesis)
266
- return intro.strip()
267
-
268
- def qa_conclusion(query, cynthesis, tier_1,):
269
-
270
-
271
- llm = ClaudeLLM()
272
- llm_4 = ChatOpenAI(
273
- temperature=0,
274
- model='gpt-3.5-turbo-16k'
275
- )
276
-
277
- session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""
278
-
279
- prompt = PromptTemplate(
280
- input_variables=["query", "cynthesis", "articles"],
281
- template="""
282
- Give me a final conclusion to the following consensus without repeating how it starts. Consider this an abstract.
283
-
284
- query: {query}
285
- Here's the consensus: {cynthesis}
286
-
287
- We have the opportunity to give a final conclusion to this synthesis without repeating information found.
288
- \nHere is also some references used to write the synthesis if you want to include some of them in the final conclusion.
289
- ---------\n
290
- {articles}
291
- ---------\n
292
-
293
- Don't forget that your job is to only provide a conclusion, abstract part that give a closure to the synthesis. Feel free to have an opening question if needed, if not no need to write it.""",
294
- )
295
-
296
-
297
- # llm = BardLLM()
298
- chain = LLMChain(llm=llm_4, prompt = prompt)
299
-
300
- conclusion = chain.run(query=query, articles=tier_1, cynthesis = cynthesis)
301
- return conclusion.strip()
302
-
303
- def qa_faqs(query, media):
304
-
305
- thoughts = retrieve_thoughts(query, media)
306
-
307
- # tier_1 = thoughts['tier 1']
308
- tier_2 = thoughts['tier 2']
309
-
310
- # reference = tier_1[['ref', 'url', 'title']].to_dict('records')
311
-
312
- # tier_1 = list(tier_1.apply(lambda x: f"[{int(x['ref'])}] title: {x['title']}\n Content: {x.content}", axis = 1).values)
313
- tier_2 = list(tier_2.apply(lambda x: f"title: {x['title']}\n Content: {x.content}", axis = 1).values)
314
- # Generate related questions
315
- session_prompt = """ A bot that is open to discussions about different cultural, philosophical and political exchanges. You will do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only."""
316
-
317
- prompt_q = PromptTemplate(
318
- input_variables=[ "session_prompt", "articles"],
319
- template="""
320
- You are a {session_prompt}
321
- Give general/global questions related the following articles:
322
-
323
- Articles:
324
- {articles}
325
-
326
- Make sure not to ask specific questions, keep them general, short and concise.
327
- """,
328
- )
329
-
330
- chain_q = LLMChain(llm=claude, prompt = prompt_q)
331
-
332
- questions = chain_q.run(session_prompt = session_prompt, articles = "\n".join(tier_2), )
333
- questions = questions[questions.index('1'):]
334
-
335
- questions = [ t.strip() for (i, t) in enumerate(questions.split('\n\n')) if len(t) > 5][:5]
336
-
337
- return "\n\n".join(questions)
338
-
339
-
340
- def parallel_greet_claude(batch, ):
341
-
342
- batch = ast.literal_eval(batch)
343
- query, thoughts = batch['query'], batch['thoughts']
344
- print(thoughts)
345
- result = qa_retrieve(query, "claude", thoughts)
346
-
347
- return result
348
-
349
- # examples = [
350
- # ["Will Russia win the war in Ukraine?"],
351
- # ["Covid Global Impact and what's beyond that"]
352
- # ]
353
-
354
- cynthesis = gr.Interface(fn = qa_retrieve, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="Cynthesis"))
355
- questions = gr.Interface(fn = qa_faqs, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="Related Questions"))
356
- #themes = gr.Interface(fn = qa_themes, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="themes"))
357
-
358
- # gpt_3 = gr.Interface(fn = parallel_greet_gpt_3, inputs = "text", outputs = gr.components.Textbox(lines=3, label="GPT3.5"))
359
- # gpt_4 = gr.Interface(fn = parallel_greet_gpt_4, inputs = "text", outputs = gr.components.Textbox(lines=3, label="GPT4"))
360
- # claude = gr.Interface(fn = parallel_greet_claude, inputs = "text", outputs = gr.components.Textbox(lines=3, label="Claude"))
361
  reference = gr.Interface(fn = get_references, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = "json", label = "Reference")
362
  json = gr.Interface(fn = grab_jsons, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="json"))
363
- #demo = gr.Parallel(cynthesis, reference)
364
- #demo = gr.Parallel(themes, reference)
365
 
366
  demo = gr.Parallel(json, reference)
367
  demo.queue(concurrency_count = 4)
 
148
 
149
  return json_articles
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  reference = gr.Interface(fn = get_references, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = "json", label = "Reference")
152
  json = gr.Interface(fn = grab_jsons, inputs = ["text", gr.CheckboxGroup(["Articles", "Podcasts", "Youtube"], label="Media", info="Choose One Type of Media until we merge (Podcasts excluded for now)"),], outputs = gr.components.Textbox(lines=3, label="json"))
 
 
153
 
154
  demo = gr.Parallel(json, reference)
155
  demo.queue(concurrency_count = 4)