{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "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": null, "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", " model = genai.GenerativeModel(\"gemini-pro\")\n", " return model, sqldb, db\n", "\n", "\n", "model, sqldb, db = configure()" ] }, { "cell_type": "code", "execution_count": 2, "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] 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", " 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": 3, "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", " 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", " results = sqldb.query(title = args['title'],author = args['author'])\n", " print(results)\n", " paper_info = sqldb.query(title = args['title'],author = args['author'])\n", " # if query not found then go crawl brh\n", "\n", " if len(paper_info) == 0:\n", " new_records = utils.crawl_exact_paper(title=args['title'],author=args['author'])\n", " db.add(new_records)\n", " sqldb.add(new_records)\n", " paper_info = sqldb.query(title = args['title'],author = args['author'])\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\", None\n", " return result_string, records\n", " # invoke llm and return result" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--------------------------\n", "{\n", " \"keywords\": [\"Video action recognition\", \"Long Short-Term Memory\", \"Computer vision\", \"Deep learning\", \"Time series analysis\"],\n", " \"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", "}\n" ] }, { "data": { "text/plain": [ "('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", " [['Applications of Deep Neural Networks with Keras',\n", " 'Jeff Heato',\n", " 'http://arxiv.org/pdf/2009.05673v5'],\n", " ['DeepDrum: An Adaptive Conditional Neural Network',\n", " 'Dimos Makris, Maximos Kaliakatsos-Papakostas, Katia Lida Kermanidi',\n", " 'http://arxiv.org/pdf/1809.06127v2'],\n", " ['A Video Recognition Method by using Adaptive Structural Learning of Long Short Term Memory based Deep Belief Network',\n", " 'Shin Kamada, Takumi Ichimur',\n", " 'http://arxiv.org/pdf/1909.13480v1']])" ] }, "execution_count": 8, "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": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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", "['LSTM model', 'video analysis', 'action recognition']\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Llama.generate: prefix-match hit\n", "\n", "llama_print_timings: load time = 139768.70 ms\n", "llama_print_timings: sample time = 140.16 ms / 412 runs ( 0.34 ms per token, 2939.41 tokens per second)\n", "llama_print_timings: prompt eval time = 0.00 ms / 1 tokens ( 0.00 ms per token, inf tokens per second)\n", "llama_print_timings: eval time = 91570.34 ms / 412 runs ( 222.26 ms per token, 4.50 tokens per second)\n", "llama_print_timings: total time = 93048.98 ms / 413 tokens\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "------------------------\n", "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", "\n", " 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: \n", "\n", " 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: \n", "\n", " 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: \n", "\n", " 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" ] } ], "source": [ "# test response, second step\n", "input_prompt = \"I'm working on a LSTM model to recognize actions in a video, recommend me some related papers\"\n", "args = {\n", " \"keywords\": [\"LSTM model\", \"video analysis\", \"action recognition\"],\n", " \"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", " }\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\n", " answer = model(prompt=output_prompt,\n", " temperature=0.0,\n", " max_tokens=1024,\n", " ) # llama\n", " print(\"------------------------\")\n", " print(answer['choices'][0]['text'])" ] }, { "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", "# inference time depends on hardware ability :')\n", "# with CPU i7-8750H, 16GB RAM and no GPU cuda, expect inference time up to 5-6 min\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": 17, "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 }