File size: 18,160 Bytes
f6350fe
 
 
 
58754c2
f6350fe
58754c2
 
 
 
 
 
 
 
 
 
f6350fe
 
 
 
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
 
58754c2
 
 
 
f6350fe
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58754c2
 
 
 
 
 
 
 
 
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
58754c2
 
 
f6350fe
58754c2
f6350fe
 
58754c2
 
 
 
f6350fe
 
58754c2
f6350fe
 
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
 
 
58754c2
 
f6350fe
 
 
 
 
 
58754c2
 
 
 
 
 
 
 
 
 
f6350fe
 
58754c2
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58754c2
f6350fe
 
 
 
 
 
58754c2
 
 
f6350fe
 
 
 
 
58754c2
 
 
f6350fe
 
 
58754c2
f6350fe
 
58754c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58754c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6350fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
397
398
399
400
401
402
403
404
405
406
407
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Admin\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python310\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "import google.generativeai as genai\n",
    "import utils\n",
    "import os\n",
    "from getpass import getpass\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['GEMINI_API_KEY'] = getpass(\"Your gemini API key: \")\n",
    "\n",
    "def configure():\n",
    "    sqldb = utils.ArxivSQL()\n",
    "    db = utils.ArxivChroma()\n",
    "    gemini_api_key = os.getenv(\"GEMINI_API_KEY\")\n",
    "    if not gemini_api_key:\n",
    "        raise ValueError(\n",
    "            \"Gemini API Key not provided. Please provide GEMINI_API_KEY as an environment variable\"\n",
    "        )\n",
    "    genai.configure(api_key=gemini_api_key)\n",
    "    config = genai.GenerationConfig(max_output_tokens=1024,\n",
    "                                    temperature=0.5)\n",
    "    model = genai.GenerativeModel(\"gemini-pro\",\n",
    "                                  generation_config=config)\n",
    "    return model, sqldb, db\n",
    "\n",
    "model, sqldb, db = configure()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_keyword_prompt(query):\n",
    "    \"\"\"A prompt that return a JSON block as arguments for querying database\"\"\"\n",
    "\n",
    "    prompt = (\n",
    "        \"\"\"[INST] SYSTEM: You are an assistant that choose only one action below based on guest question.\n",
    "   1. If the guest question is asking for some specific document or article, you need to respond the information in JSON format with 2 keys \"title\", \"author\" if found any above. The authors are separated with the word 'and'. \n",
    "   2. If the guest question is asking for relevant informations about a topic, you need to respond the information in JSON format with 2 keys \"keywords\", \"description\", include a list of keywords represent the main academic topic, \\\n",
    "     and a description about the main topic. You may paraphrase the keywords to add more. \\\n",
    "   3. If the guest is not asking for any informations or documents, you need to respond with a polite answer in JSON format with 1 key \"answer\".\n",
    "   QUESTION: '{query}'\n",
    "   [/INST]\n",
    "   ANSWER: \n",
    "   \"\"\"\n",
    "    ).format(query=query)\n",
    "\n",
    "    return prompt\n",
    "\n",
    "def make_answer_prompt(input, contexts):\n",
    "    \"\"\"A prompt that return the final answer, based on the queried context\"\"\"\n",
    "\n",
    "    prompt = (\n",
    "        \"\"\"[INST] You are an library assistant that help to search articles and documents based on user's question.\n",
    "  From guest's question, you have found some records and documents that may help. Now you need to answer the guest with the information found.\n",
    "  If no information found in the database, you may generate some other recommendation related to user's question using your own knowledge. You should answer in a conversational form politely.\n",
    "  QUESTION: '{input}'\n",
    "  INFORMATION: '{contexts}'\n",
    "  [/INST]\n",
    "  ANSWER:\n",
    "  \"\"\"\n",
    "    ).format(input=input, contexts=contexts)\n",
    "\n",
    "    return prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def response(args):\n",
    "    \"\"\"Create response context, based on input arguments\"\"\"\n",
    "    keys = list(dict.keys(args))\n",
    "    if \"answer\" in keys:\n",
    "        return args['answer'], None  # trả lời trực tiếp\n",
    "    \n",
    "    if \"keywords\" in keys:\n",
    "        # perform query\n",
    "        query_texts = args[\"description\"]\n",
    "        keywords = args[\"keywords\"]\n",
    "        results = db.query_relevant(keywords=keywords, query_texts=query_texts)\n",
    "        # print(results)\n",
    "        ids = results['metadatas'][0]\n",
    "        if len(ids) == 0:\n",
    "            # go crawl some\n",
    "            new_records = utils.crawl_arxiv(keyword_list=keywords)\n",
    "            if type(new_records) == str:\n",
    "                return \"Error occured, information not found\", new_records\n",
    "            db.add(new_records)\n",
    "            sqldb.add(new_records)\n",
    "            results = db.query_relevant(keywords=keywords, query_texts=query_texts)\n",
    "            ids = results['metadatas'][0]\n",
    "        paper_id = [id['paper_id'] for id in ids]\n",
    "        paper_info = sqldb.query_id(paper_id)\n",
    "        # print(paper_info)\n",
    "        records = [] # get title (2), author (3), link (6)\n",
    "        result_string = \"\"\n",
    "        for i in range(len(paper_id)):\n",
    "            result_string += \"Title: {}, Author: {}, Link: {}\".format(paper_info[i][2],paper_info[i][3],paper_info[i][6])\n",
    "            records.append([paper_info[i][2],paper_info[i][3],paper_info[i][6]])\n",
    "        # process results:\n",
    "        return result_string, records\n",
    "        # invoke llm and return result\n",
    "\n",
    "    if \"title\" in keys:\n",
    "        title = args['title']\n",
    "        authors = utils.process_authors_list(args['author'])\n",
    "        paper_info = sqldb.query(title = title,author = authors)\n",
    "        # if query not found then go crawl brh\n",
    "        # print(paper_info)\n",
    "\n",
    "        if len(paper_info) == 0:\n",
    "            new_records = utils.crawl_exact_paper(title=title,author=authors)\n",
    "            if type(new_records) == str:\n",
    "                # print(new_records)\n",
    "                return \"Error occured, information not found\", \"Information not found\"\n",
    "            db.add(new_records)\n",
    "            sqldb.add(new_records)\n",
    "            paper_info = sqldb.query(title = title,author = authors)\n",
    "        # -------------------------------------\n",
    "        records = [] # get title (2), author (3), link (6)\n",
    "        result_string = \"\"\n",
    "        for i in range(len(paper_info)):\n",
    "            result_string += \"Title: {}, Author: {}, Link: {}\".format(paper_info[i][2],paper_info[i][3],paper_info[i][6])\n",
    "            records.append([paper_info[i][2],paper_info[i][3],paper_info[i][6]])\n",
    "        # process results:\n",
    "        if len(result_string) == 0:\n",
    "            return \"Information not found\", \"Information not found\"\n",
    "        return result_string, records\n",
    "        # invoke llm and return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------\n",
      "{\n",
      " \"keywords\": [\"Long short-term memory\", \"Video action recognition\", \"Convolutional neural networks\"],\n",
      " \"description\": \"Long short-term memory (LSTM) is a type of recurrent neural network (RNN) that is used for processing sequential data. It is particularly well-suited for tasks such as video action recognition, where the order of the frames in the video is important. Convolutional neural networks (CNNs) are another type of neural network that is often used for image and video processing. They are particularly good at learning the spatial features of images and videos. LSTM networks and CNNs can be used together to create powerful models for video action recognition.\"\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "('Title: LiteLSTM Architecture for Deep Recurrent Neural Networks, Author: Nelly Elsayed, Zag ElSayed, Anthony S. Maid, Link: http://arxiv.org/pdf/2201.11624v2Title: AdderNet and its Minimalist Hardware Design for Energy-Efficient Artificial Intelligence, Author: Yunhe Wang, Mingqiang Huang, Kai Han, Hanting Chen, Wei Zhang, Chunjing Xu, Dacheng Ta, Link: http://arxiv.org/pdf/2101.10015v2Title: Audio Tagging on an Embedded Hardware Platform, Author: Gabriel Bibbo, Arshdeep Singh, Mark D. Plumble, Link: http://arxiv.org/pdf/2306.09106v1',\n",
       " [['LiteLSTM Architecture for Deep Recurrent Neural Networks',\n",
       "   'Nelly Elsayed, Zag ElSayed, Anthony S. Maid',\n",
       "   'http://arxiv.org/pdf/2201.11624v2'],\n",
       "  ['AdderNet and its Minimalist Hardware Design for Energy-Efficient Artificial Intelligence',\n",
       "   'Yunhe Wang, Mingqiang Huang, Kai Han, Hanting Chen, Wei Zhang, Chunjing Xu, Dacheng Ta',\n",
       "   'http://arxiv.org/pdf/2101.10015v2'],\n",
       "  ['Audio Tagging on an Embedded Hardware Platform',\n",
       "   'Gabriel Bibbo, Arshdeep Singh, Mark D. Plumble',\n",
       "   'http://arxiv.org/pdf/2306.09106v1']])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "# test first step\n",
    "# input_prompt = input()\n",
    "input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
    "first_prompt = extract_keyword_prompt(input_prompt)\n",
    "# print(first_prompt)\n",
    "# answer = model.invoke(first_prompt,\n",
    "#                       temperature=0.0) # ctrans\n",
    "answer = model.generate_content(first_prompt).text\n",
    "print(\"--------------------------\")\n",
    "print(answer)\n",
    "args = json.loads(utils.trimming(answer))\n",
    "# print(args)\n",
    "response(args)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "near \")\": syntax error\n",
      "Error query:  select * from arxivsql where id in )\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# test response, second step\n",
    "input_prompt = \"Can you suggest some key papers on model predictive control for nonlinear systems, and are there any recent reviews on the application of control theory to robotics?\"\n",
    "args =  \"{\\n \\\"keywords\\\": [\\n  \\\"Power Electronics\\\",\\n  \\\"Renewable Energy Systems\\\",\\n  \\\"High-Frequency Power Converters\\\",\\n  \\\"Power Electronics Applications\\\",\\n  \\\"Renewable Energy Sources\\\"\\n ],\\n \\\"description\\\": \\\"Power electronics is a branch of electrical engineering that deals with the conversion, control, and conditioning of electrical power. It is used in a wide variety of applications, including power generation, transmission, distribution, and utilization. Renewable energy systems are systems that generate electricity from renewable sources, such as solar, wind, and hydro power. Power electronics is used in renewable energy systems to convert the electrical output of the renewable source into a form that can be used by the grid or by consumers.\\\"\\n}\"\n",
    "args = json.loads(args)\n",
    "contexts, results = response(args)\n",
    "if not results:\n",
    "  # direct answer\n",
    "  print(contexts)\n",
    "else:\n",
    "  output_prompt = make_answer_prompt(input_prompt,contexts)\n",
    "  answer = model.generate_content(output_prompt).text\n",
    "  print(answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'desired': 'Natural Language Processing (Computer Science)', 'question': 'What are some recent papers on deep learning architectures for text classification, and can you recommend any surveys or reviews on the topic?'}\n"
     ]
    }
   ],
   "source": [
    "with open(\"test_questions.txt\",\"r\") as infile:\n",
    "    data = json.load(infile)\n",
    "print(data[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------\n",
      "```json\n",
      "{\n",
      "  \"keywords\": [\n",
      "    \"Video Recognition\",\n",
      "    \"LSTM\",\n",
      "    \"Action Recognition\",\n",
      "    \"Deep Learning\"\n",
      "  ],\n",
      "  \"description\": \"Action recognition in videos is a challenging task due to the large variations in appearance, scale, and viewpoint. LSTM models have been shown to be effective for this task, as they can learn long-term dependencies in the data. Some related papers that you may find useful include:\\n\\n1. [Long-term recurrent convolutional networks for visual recognition](https://arxiv.org/abs/1411.4389) by Karen Simonyan and Andrew Zisserman\\n2. [Two-stream convolutional networks for action recognition in videos](https://arxiv.org/abs/1406.2199) by Karen Simonyan and Andrew Zisserman\\n3. [LSTM networks for video action recognition](https://arxiv.org/abs/1502.04793) by Jeff Donahue, Lisa Anne Hendricks, Sergio Guadarrama, Marcus Rohrbach, Subhashini Venugopalan, Kate Saenko, and Trevor Darrell\"\n",
      "}\n",
      "```\n",
      "--------------------------\n",
      "Of course, here are a few papers that you may find helpful for your LSTM model to recognize actions in a video:\n",
      "\n",
      "1. **ActNetFormer: Transformer-ResNet Hybrid Method for Semi-Supervised Action Recognition in Videos** by Sharana Dharshikgan Suresh Dass, Hrishav Bakul Barua, Ganesh Krishnasamy, Raveendran Paramesran, Raphael C. -W. Pha. (link: http://arxiv.org/pdf/2404.06243v1)\n",
      "\n",
      "2. **Deep Neural Networks in Video Human Action Recognition: A Review** by Zihan Wang, Yang Yang, Zhi Liu, Yifan Zhen. (link: http://arxiv.org/pdf/2305.15692v1)\n",
      "\n",
      "3. **3D Convolutional Neural Networks for Ultrasound-Based Silent Speech Interfaces** by László Tóth, Amin Honarmandi Shandi. (link: http://arxiv.org/pdf/2104.11532v1)\n",
      "\n",
      "These papers provide a good overview of the state-of-the-art in action recognition using LSTM models. I hope you find them helpful! Let me know if you have any other questions.\n"
     ]
    }
   ],
   "source": [
    "# full chain\n",
    "# input_prompt = input()\n",
    "input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
    "first_prompt = extract_keyword_prompt(input_prompt)\n",
    "# print(first_prompt)\n",
    "# answer = model.invoke(first_prompt,\n",
    "#                       temperature=0.0) # ctrans\n",
    "answer = model.generate_content(first_prompt).text\n",
    "print(\"--------------------------\")\n",
    "print(answer)\n",
    "args = json.loads(utils.trimming(answer))\n",
    "# print(args)\n",
    "contexts, results = response(args)\n",
    "if not results:\n",
    "  # direct answer\n",
    "    print(contexts)\n",
    "else:\n",
    "  output_prompt = make_answer_prompt(input_prompt,contexts)\n",
    "  # answer = model.invoke(output_prompt,\n",
    "  #                       temperature=0.3) # ctrans, answer is a string\n",
    "  answer = model.generate_content(output_prompt).text # llama, answer is a dict\n",
    "  print(\"--------------------------\")\n",
    "  print(answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def full_chain_single_question(input_prompt):\n",
    "    try:\n",
    "        first_prompt = extract_keyword_prompt(input_prompt)\n",
    "        temp_answer = model.generate_content(first_prompt).text\n",
    "\n",
    "        args = json.loads(utils.trimming(temp_answer))\n",
    "        contexts, results = response(args)\n",
    "        if not results:\n",
    "            print(contexts)\n",
    "        else:\n",
    "            output_prompt = make_answer_prompt(input_prompt,contexts)\n",
    "            answer = model.generate_content(output_prompt).text\n",
    "        return temp_answer, answer\n",
    "    except Exception as e:\n",
    "        return temp_answer, \"Error occured: \" + str(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n",
      "[]\n",
      "Error: timed out\n",
      "[]\n",
      "near \")\": syntax error\n",
      "Error query:  select * from arxivsql where id in )\n",
      "\n"
     ]
    }
   ],
   "source": [
    "test_log = []\n",
    "for t in data:\n",
    "    temp_answer, answer = full_chain_single_question(t['question'])\n",
    "    test_log.append({'desired topic':t['desired'],\n",
    "           'question':t['question'],\n",
    "           'first answer':temp_answer,\n",
    "           'final answer':answer})\n",
    "with open(\"test_results.json\",\"w\") as outfile:\n",
    "    json.dump(test_log,outfile)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip freeze > requirements.txt"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain_llms",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}