tosanoob commited on
Commit
f6350fe
1 Parent(s): 2739bfd

Update mainflow for single question

Browse files
Files changed (2) hide show
  1. .gitignore +3 -0
  2. mainflow_single_question.ipynb +347 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ mainflow_single_question.py
2
+ models/
3
+ __pycache__/
mainflow_single_question.ipynb ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 4,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import google.generativeai as genai\n",
10
+ "import utils\n",
11
+ "import os\n",
12
+ "from getpass import getpass\n",
13
+ "import json"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": null,
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "os.environ['GEMINI_API_KEY'] = getpass(\"Your gemini API key: \")\n",
23
+ "\n",
24
+ "def configure():\n",
25
+ " sqldb = utils.ArxivSQL()\n",
26
+ " db = utils.ArxivChroma()\n",
27
+ " gemini_api_key = os.getenv(\"GEMINI_API_KEY\")\n",
28
+ " if not gemini_api_key:\n",
29
+ " raise ValueError(\n",
30
+ " \"Gemini API Key not provided. Please provide GEMINI_API_KEY as an environment variable\"\n",
31
+ " )\n",
32
+ " genai.configure(api_key=gemini_api_key)\n",
33
+ " model = genai.GenerativeModel(\"gemini-pro\")\n",
34
+ " return model, sqldb, db\n",
35
+ "\n",
36
+ "\n",
37
+ "model, sqldb, db = configure()"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": 2,
43
+ "metadata": {},
44
+ "outputs": [],
45
+ "source": [
46
+ "def extract_keyword_prompt(query):\n",
47
+ " \"\"\"A prompt that return a JSON block as arguments for querying database\"\"\"\n",
48
+ "\n",
49
+ " prompt = (\n",
50
+ " \"\"\"[INST] You are an assistant that choose only one action below based on guest question.\n",
51
+ " 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",
52
+ " 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",
53
+ " and a description about the main topic. You may paraphrase the keywords to add more. \\\n",
54
+ " 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",
55
+ " QUESTION: '{query}'\n",
56
+ " [/INST]\n",
57
+ " ANSWER: \n",
58
+ " \"\"\"\n",
59
+ " ).format(query=query)\n",
60
+ "\n",
61
+ " return prompt\n",
62
+ "\n",
63
+ "def make_answer_prompt(input, contexts):\n",
64
+ " \"\"\"A prompt that return the final answer, based on the queried context\"\"\"\n",
65
+ "\n",
66
+ " prompt = (\n",
67
+ " \"\"\"[INST] You are an library assistant that help to search articles and documents based on user's question.\n",
68
+ " 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",
69
+ " You should answer in a conversational form politely.\n",
70
+ " QUESTION: '{input}'\n",
71
+ " INFORMATION: '{contexts}'\n",
72
+ " [/INST]\n",
73
+ " ANSWER:\n",
74
+ " \"\"\"\n",
75
+ " ).format(input=input, contexts=contexts)\n",
76
+ "\n",
77
+ " return prompt"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "execution_count": 3,
83
+ "metadata": {},
84
+ "outputs": [],
85
+ "source": [
86
+ "def response(args):\n",
87
+ " \"\"\"Create response context, based on input arguments\"\"\"\n",
88
+ " keys = list(dict.keys(args))\n",
89
+ " if \"answer\" in keys:\n",
90
+ " return args['answer'], None # trả lời trực tiếp\n",
91
+ " \n",
92
+ " if \"keywords\" in keys:\n",
93
+ " # perform query\n",
94
+ " query_texts = args[\"description\"]\n",
95
+ " keywords = args[\"keywords\"]\n",
96
+ " results = db.query_relevant(keywords=keywords, query_texts=query_texts)\n",
97
+ " # print(results)\n",
98
+ " ids = results['metadatas'][0]\n",
99
+ " paper_id = [id['paper_id'] for id in ids]\n",
100
+ " paper_info = sqldb.query_id(paper_id)\n",
101
+ " # print(paper_info)\n",
102
+ " records = [] # get title (2), author (3), link (6)\n",
103
+ " result_string = \"\"\n",
104
+ " for i in range(len(paper_id)):\n",
105
+ " result_string += \"Title: {}, Author: {}, Link: {}\".format(paper_info[i][2],paper_info[i][3],paper_info[i][6])\n",
106
+ " records.append([paper_info[i][2],paper_info[i][3],paper_info[i][6]])\n",
107
+ " # process results:\n",
108
+ " return result_string, records\n",
109
+ " # invoke llm and return result\n",
110
+ "\n",
111
+ " if \"title\" in keys:\n",
112
+ " results = sqldb.query(title = args['title'],author = args['author'])\n",
113
+ " print(results)\n",
114
+ " paper_info = sqldb.query(title = args['title'],author = args['author'])\n",
115
+ " # if query not found then go crawl brh\n",
116
+ "\n",
117
+ " if len(paper_info) == 0:\n",
118
+ " new_records = utils.crawl_exact_paper(title=args['title'],author=args['author'])\n",
119
+ " db.add(new_records)\n",
120
+ " sqldb.add(new_records)\n",
121
+ " paper_info = sqldb.query(title = args['title'],author = args['author'])\n",
122
+ " # -------------------------------------\n",
123
+ " records = [] # get title (2), author (3), link (6)\n",
124
+ " result_string = \"\"\n",
125
+ " for i in range(len(paper_info)):\n",
126
+ " result_string += \"Title: {}, Author: {}, Link: {}\".format(paper_info[i][2],paper_info[i][3],paper_info[i][6])\n",
127
+ " records.append([paper_info[i][2],paper_info[i][3],paper_info[i][6]])\n",
128
+ " # process results:\n",
129
+ " if len(result_string) == 0:\n",
130
+ " return \"Information not found\", None\n",
131
+ " return result_string, records\n",
132
+ " # invoke llm and return result"
133
+ ]
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "execution_count": 8,
138
+ "metadata": {},
139
+ "outputs": [
140
+ {
141
+ "name": "stdout",
142
+ "output_type": "stream",
143
+ "text": [
144
+ "--------------------------\n",
145
+ "{\n",
146
+ " \"keywords\": [\"Video action recognition\", \"Long Short-Term Memory\", \"Computer vision\", \"Deep learning\", \"Time series analysis\"],\n",
147
+ " \"description\": \"Video action recognition is a challenging task in computer vision. It requires the ability to understand the temporal dynamics of a video and to identify the actions being performed. Long Short-Term Memory (LSTM) networks are a type of recurrent neural network that is well-suited for learning long-term dependencies. This makes them a good choice for video action recognition tasks. LSTM networks have been shown to achieve state-of-the-art results on a variety of video action recognition datasets using deep learning techniques.\"\n",
148
+ "}\n"
149
+ ]
150
+ },
151
+ {
152
+ "data": {
153
+ "text/plain": [
154
+ "('Title: Applications of Deep Neural Networks with Keras, Author: Jeff Heato, Link: http://arxiv.org/pdf/2009.05673v5Title: DeepDrum: An Adaptive Conditional Neural Network, Author: Dimos Makris, Maximos Kaliakatsos-Papakostas, Katia Lida Kermanidi, Link: http://arxiv.org/pdf/1809.06127v2Title: A Video Recognition Method by using Adaptive Structural Learning of Long Short Term Memory based Deep Belief Network, Author: Shin Kamada, Takumi Ichimur, Link: http://arxiv.org/pdf/1909.13480v1',\n",
155
+ " [['Applications of Deep Neural Networks with Keras',\n",
156
+ " 'Jeff Heato',\n",
157
+ " 'http://arxiv.org/pdf/2009.05673v5'],\n",
158
+ " ['DeepDrum: An Adaptive Conditional Neural Network',\n",
159
+ " 'Dimos Makris, Maximos Kaliakatsos-Papakostas, Katia Lida Kermanidi',\n",
160
+ " 'http://arxiv.org/pdf/1809.06127v2'],\n",
161
+ " ['A Video Recognition Method by using Adaptive Structural Learning of Long Short Term Memory based Deep Belief Network',\n",
162
+ " 'Shin Kamada, Takumi Ichimur',\n",
163
+ " 'http://arxiv.org/pdf/1909.13480v1']])"
164
+ ]
165
+ },
166
+ "execution_count": 8,
167
+ "metadata": {},
168
+ "output_type": "execute_result"
169
+ }
170
+ ],
171
+ "source": [
172
+ "import json\n",
173
+ "# test first step\n",
174
+ "# input_prompt = input()\n",
175
+ "input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
176
+ "first_prompt = extract_keyword_prompt(input_prompt)\n",
177
+ "# print(first_prompt)\n",
178
+ "# answer = model.invoke(first_prompt,\n",
179
+ "# temperature=0.0) # ctrans\n",
180
+ "answer = model.generate_content(first_prompt).text\n",
181
+ "print(\"--------------------------\")\n",
182
+ "print(answer)\n",
183
+ "args = json.loads(utils.trimming(answer))\n",
184
+ "# print(args)\n",
185
+ "response(args)"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 10,
191
+ "metadata": {},
192
+ "outputs": [
193
+ {
194
+ "name": "stdout",
195
+ "output_type": "stream",
196
+ "text": [
197
+ "For recognizing actions in videos using Long Short-Term Memory (LSTM) models, you may find the following papers insightful. These studies explore various aspects of action recognition using LSTM: (1) 'Action Recognition with 3D Convolutional Neural Networks and Long Short-Term Memory' by Tran et al., 2015; (2) 'ConvLSTM: A Convolutional Neural Network for Video Recognition' by Shi et al., 2015; (3) 'Using Long-Short Term Memory for Action Recognition in Videos' by Graves, 2013.\n",
198
+ "['LSTM model', 'video analysis', 'action recognition']\n"
199
+ ]
200
+ },
201
+ {
202
+ "name": "stderr",
203
+ "output_type": "stream",
204
+ "text": [
205
+ "Llama.generate: prefix-match hit\n",
206
+ "\n",
207
+ "llama_print_timings: load time = 139768.70 ms\n",
208
+ "llama_print_timings: sample time = 140.16 ms / 412 runs ( 0.34 ms per token, 2939.41 tokens per second)\n",
209
+ "llama_print_timings: prompt eval time = 0.00 ms / 1 tokens ( 0.00 ms per token, inf tokens per second)\n",
210
+ "llama_print_timings: eval time = 91570.34 ms / 412 runs ( 222.26 ms per token, 4.50 tokens per second)\n",
211
+ "llama_print_timings: total time = 93048.98 ms / 413 tokens\n"
212
+ ]
213
+ },
214
+ {
215
+ "name": "stdout",
216
+ "output_type": "stream",
217
+ "text": [
218
+ "------------------------\n",
219
+ "Hello there! I see that you're working on an LSTM model for recognizing actions in videos. I have found some related papers that might be of interest to you.\n",
220
+ "\n",
221
+ " 1. The first one is titled \"Action in Mind: A Neural Network Approach to Action Recognition and Segmentation\" by Zahra Gharae. This paper proposes a neural network approach for action recognition and segmentation, which could provide some insights into your work with LSTM models. You can find it at this link: <http://arxiv.org/pdf/2104.14870v1>\n",
222
+ "\n",
223
+ " 2. Another interesting paper is \"Deep Neural Networks in Video Human Action Recognition: A Review\" by Zihan Wang, Yang Yang, Zhi Liu, and Yifan Zhen. This review discusses the application of deep neural networks for video human action recognition. It could give you a broader perspective on the current state-of-the-art methods in this field. You can access it here: <http://arxiv.org/pdf/2305.15692v1>\n",
224
+ "\n",
225
+ " 3. Lastly, there's \"3D Convolutional Neural Networks for Ultrasound-Based Silent Speech Interfaces\" by László Tóth and Amin Honarmandi Shandi. Although the title might not seem directly related to your work on LSTM models for action recognition, it does involve the use of 3D convolutional neural networks in video processing, which could still provide valuable insights. You can read it at this link: <http://arxiv.org/pdf/2104.11532v1>\n",
226
+ "\n",
227
+ " I hope you find these resources helpful! Let me know if there's anything else I can assist you with. Have a great day!\n"
228
+ ]
229
+ }
230
+ ],
231
+ "source": [
232
+ "# test response, second step\n",
233
+ "input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
234
+ "args = {\n",
235
+ " \"keywords\": [\"LSTM model\", \"video analysis\", \"action recognition\"],\n",
236
+ " \"description\": \"For recognizing actions in videos using Long Short-Term Memory (LSTM) models, you may find the following papers insightful. These studies explore various aspects of action recognition using LSTM: (1) 'Action Recognition with 3D Convolutional Neural Networks and Long Short-Term Memory' by Tran et al., 2015; (2) 'ConvLSTM: A Convolutional Neural Network for Video Recognition' by Shi et al., 2015; (3) 'Using Long-Short Term Memory for Action Recognition in Videos' by Graves, 2013.\"\n",
237
+ " }\n",
238
+ "contexts, results = response(args)\n",
239
+ "if not results:\n",
240
+ " # direct answer\n",
241
+ " print(contexts)\n",
242
+ "else:\n",
243
+ " output_prompt = make_answer_prompt(input_prompt,contexts)\n",
244
+ " # answer = model.invoke(output_prompt,\n",
245
+ " # temperature=0.3) # ctrans\n",
246
+ " answer = model(prompt=output_prompt,\n",
247
+ " temperature=0.0,\n",
248
+ " max_tokens=1024,\n",
249
+ " ) # llama\n",
250
+ " print(\"------------------------\")\n",
251
+ " print(answer['choices'][0]['text'])"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": 5,
257
+ "metadata": {},
258
+ "outputs": [
259
+ {
260
+ "name": "stdout",
261
+ "output_type": "stream",
262
+ "text": [
263
+ "--------------------------\n",
264
+ "```json\n",
265
+ "{\n",
266
+ " \"keywords\": [\n",
267
+ " \"Video Recognition\",\n",
268
+ " \"LSTM\",\n",
269
+ " \"Action Recognition\",\n",
270
+ " \"Deep Learning\"\n",
271
+ " ],\n",
272
+ " \"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",
273
+ "}\n",
274
+ "```\n",
275
+ "--------------------------\n",
276
+ "Of course, here are a few papers that you may find helpful for your LSTM model to recognize actions in a video:\n",
277
+ "\n",
278
+ "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",
279
+ "\n",
280
+ "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",
281
+ "\n",
282
+ "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",
283
+ "\n",
284
+ "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"
285
+ ]
286
+ }
287
+ ],
288
+ "source": [
289
+ "# full chain\n",
290
+ "# inference time depends on hardware ability :')\n",
291
+ "# with CPU i7-8750H, 16GB RAM and no GPU cuda, expect inference time up to 5-6 min\n",
292
+ "# input_prompt = input()\n",
293
+ "input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n",
294
+ "first_prompt = extract_keyword_prompt(input_prompt)\n",
295
+ "# print(first_prompt)\n",
296
+ "# answer = model.invoke(first_prompt,\n",
297
+ "# temperature=0.0) # ctrans\n",
298
+ "answer = model.generate_content(first_prompt).text\n",
299
+ "print(\"--------------------------\")\n",
300
+ "print(answer)\n",
301
+ "args = json.loads(utils.trimming(answer))\n",
302
+ "# print(args)\n",
303
+ "contexts, results = response(args)\n",
304
+ "if not results:\n",
305
+ " # direct answer\n",
306
+ " print(contexts)\n",
307
+ "else:\n",
308
+ " output_prompt = make_answer_prompt(input_prompt,contexts)\n",
309
+ " # answer = model.invoke(output_prompt,\n",
310
+ " # temperature=0.3) # ctrans, answer is a string\n",
311
+ " answer = model.generate_content(output_prompt).text # llama, answer is a dict\n",
312
+ " print(\"--------------------------\")\n",
313
+ " print(answer)"
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": 17,
319
+ "metadata": {},
320
+ "outputs": [],
321
+ "source": [
322
+ "!pip freeze > requirements.txt"
323
+ ]
324
+ }
325
+ ],
326
+ "metadata": {
327
+ "kernelspec": {
328
+ "display_name": "langchain_llms",
329
+ "language": "python",
330
+ "name": "python3"
331
+ },
332
+ "language_info": {
333
+ "codemirror_mode": {
334
+ "name": "ipython",
335
+ "version": 3
336
+ },
337
+ "file_extension": ".py",
338
+ "mimetype": "text/x-python",
339
+ "name": "python",
340
+ "nbconvert_exporter": "python",
341
+ "pygments_lexer": "ipython3",
342
+ "version": "3.10.11"
343
+ }
344
+ },
345
+ "nbformat": 4,
346
+ "nbformat_minor": 2
347
+ }