【InternLM 實戰營筆記】浦語·靈筆的圖文理解及創作部署、 Lagent 工具調用 Demo

浦語·靈筆的圖文理解及創作部署

浦語·靈筆是基于書生·浦語大語言模型研發的視覺-語言大模型,提供出色的圖文理解和創作能力,結合了視覺和語言的先進技術,能夠實現圖像到文本、文本到圖像的雙向轉換。使用浦語·靈筆大模型可以輕松的創作一篇圖文推文,也能夠輕松識別一張圖片中的物體,并生成對應的文本描述。

使用 InternStudio 中的 A100(1/4) * 2 機器和 internlm-xcomposer-7b 模型部署一個圖文理解創作 Demo

克隆環境

/root/share/install_conda_env_internlm_base.sh xcomposer-demo

激活環境

conda activate xcomposer-demo

安裝依賴

pip install transformers==4.33.1 timm==0.4.12 sentencepiece==0.1.99 gradio==3.44.4 markdown2==2.4.10 xlsxwriter==3.1.2 einops accelerate

模型下載

mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-xcomposer-7b /root/model/Shanghai_AI_Laboratory

代碼準備

cd /root/code
git clone https://gitee.com/internlm/InternLM-XComposer.git
cd /root/code/InternLM-XComposer
git checkout 3e8c79051a1356b9c388a6447867355c0634932d

demo運行

cd /root/code/InternLM-XComposer
python examples/web_demo.py  \--folder /root/model/Shanghai_AI_Laboratory/internlm-xcomposer-7b \--num_gpus 1 \--port 6006

運行效果
在這里插入圖片描述

完成 Lagent 工具調用 Demo 創作部署

環境準備.

python -m pip install --upgrade pippip install modelscope==1.9.5
pip install transformers==4.35.2
pip install streamlit==1.24.0
pip install sentencepiece==0.1.99
pip install accelerate==0.24.1

模型下載

mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-chat-7b /root/model/Shanghai_AI_Laboratory

Lagent 安裝

cd /root/code
git clone https://gitee.com/internlm/lagent.git
cd /root/code/lagent
git checkout 511b03889010c4811b1701abb153e02b8e94fb5e # 盡量保證和教程commit版本一致
pip install -e . # 源碼安裝

修改代碼
由于代碼修改的地方比較多,大家直接將 /root/code/lagent/examples/react_web_demo.py 內容替換為以下代碼

import copy
import osimport streamlit as st
from streamlit.logger import get_loggerfrom lagent.actions import ActionExecutor, GoogleSearch, PythonInterpreter
from lagent.agents.react import ReAct
from lagent.llms import GPTAPI
from lagent.llms.huggingface import HFTransformerCasualLMclass SessionState:def init_state(self):"""Initialize session state variables."""st.session_state['assistant'] = []st.session_state['user'] = []#action_list = [PythonInterpreter(), GoogleSearch()]action_list = [PythonInterpreter()]st.session_state['plugin_map'] = {action.name: actionfor action in action_list}st.session_state['model_map'] = {}st.session_state['model_selected'] = Nonest.session_state['plugin_actions'] = set()def clear_state(self):"""Clear the existing session state."""st.session_state['assistant'] = []st.session_state['user'] = []st.session_state['model_selected'] = Noneif 'chatbot' in st.session_state:st.session_state['chatbot']._session_history = []class StreamlitUI:def __init__(self, session_state: SessionState):self.init_streamlit()self.session_state = session_statedef init_streamlit(self):"""Initialize Streamlit's UI settings."""st.set_page_config(layout='wide',page_title='lagent-web',page_icon='./docs/imgs/lagent_icon.png')# st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')st.sidebar.title('模型控制')def setup_sidebar(self):"""Setup the sidebar for model and plugin selection."""model_name = st.sidebar.selectbox('模型選擇:', options=['gpt-3.5-turbo','internlm'])if model_name != st.session_state['model_selected']:model = self.init_model(model_name)self.session_state.clear_state()st.session_state['model_selected'] = model_nameif 'chatbot' in st.session_state:del st.session_state['chatbot']else:model = st.session_state['model_map'][model_name]plugin_name = st.sidebar.multiselect('插件選擇',options=list(st.session_state['plugin_map'].keys()),default=[list(st.session_state['plugin_map'].keys())[0]],)plugin_action = [st.session_state['plugin_map'][name] for name in plugin_name]if 'chatbot' in st.session_state:st.session_state['chatbot']._action_executor = ActionExecutor(actions=plugin_action)if st.sidebar.button('清空對話', key='clear'):self.session_state.clear_state()uploaded_file = st.sidebar.file_uploader('上傳文件', type=['png', 'jpg', 'jpeg', 'mp4', 'mp3', 'wav'])return model_name, model, plugin_action, uploaded_filedef init_model(self, option):"""Initialize the model based on the selected option."""if option not in st.session_state['model_map']:if option.startswith('gpt'):st.session_state['model_map'][option] = GPTAPI(model_type=option)else:st.session_state['model_map'][option] = HFTransformerCasualLM('/root/model/Shanghai_AI_Laboratory/internlm-chat-7b')return st.session_state['model_map'][option]def initialize_chatbot(self, model, plugin_action):"""Initialize the chatbot with the given model and plugin actions."""return ReAct(llm=model, action_executor=ActionExecutor(actions=plugin_action))def render_user(self, prompt: str):with st.chat_message('user'):st.markdown(prompt)def render_assistant(self, agent_return):with st.chat_message('assistant'):for action in agent_return.actions:if (action):self.render_action(action)st.markdown(agent_return.response)def render_action(self, action):with st.expander(action.type, expanded=True):st.markdown("<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>插    件</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501+ action.type + '</span></p>',unsafe_allow_html=True)st.markdown("<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>思考步驟</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501+ action.thought + '</span></p>',unsafe_allow_html=True)if (isinstance(action.args, dict) and 'text' in action.args):st.markdown("<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 執行內容</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501unsafe_allow_html=True)st.markdown(action.args['text'])self.render_action_results(action)def render_action_results(self, action):"""Render the results of action, including text, images, videos, andaudios."""if (isinstance(action.result, dict)):st.markdown("<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 執行結果</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501unsafe_allow_html=True)if 'text' in action.result:st.markdown("<p style='text-align: left;'>" + action.result['text'] +'</p>',unsafe_allow_html=True)if 'image' in action.result:image_path = action.result['image']image_data = open(image_path, 'rb').read()st.image(image_data, caption='Generated Image')if 'video' in action.result:video_data = action.result['video']video_data = open(video_data, 'rb').read()st.video(video_data)if 'audio' in action.result:audio_data = action.result['audio']audio_data = open(audio_data, 'rb').read()st.audio(audio_data)def main():logger = get_logger(__name__)# Initialize Streamlit UI and setup sidebarif 'ui' not in st.session_state:session_state = SessionState()session_state.init_state()st.session_state['ui'] = StreamlitUI(session_state)else:st.set_page_config(layout='wide',page_title='lagent-web',page_icon='./docs/imgs/lagent_icon.png')# st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')model_name, model, plugin_action, uploaded_file = st.session_state['ui'].setup_sidebar()# Initialize chatbot if it is not already initialized# or if the model has changedif 'chatbot' not in st.session_state or model != st.session_state['chatbot']._llm:st.session_state['chatbot'] = st.session_state['ui'].initialize_chatbot(model, plugin_action)for prompt, agent_return in zip(st.session_state['user'],st.session_state['assistant']):st.session_state['ui'].render_user(prompt)st.session_state['ui'].render_assistant(agent_return)# User input form at the bottom (this part will be at the bottom)# with st.form(key='my_form', clear_on_submit=True):if user_input := st.chat_input(''):st.session_state['ui'].render_user(user_input)st.session_state['user'].append(user_input)# Add file uploader to sidebarif uploaded_file:file_bytes = uploaded_file.read()file_type = uploaded_file.typeif 'image' in file_type:st.image(file_bytes, caption='Uploaded Image')elif 'video' in file_type:st.video(file_bytes, caption='Uploaded Video')elif 'audio' in file_type:st.audio(file_bytes, caption='Uploaded Audio')# Save the file to a temporary location and get the pathfile_path = os.path.join(root_dir, uploaded_file.name)with open(file_path, 'wb') as tmpfile:tmpfile.write(file_bytes)st.write(f'File saved at: {file_path}')user_input = '我上傳了一個圖像,路徑為: {file_path}. {user_input}'.format(file_path=file_path, user_input=user_input)agent_return = st.session_state['chatbot'].chat(user_input)st.session_state['assistant'].append(copy.deepcopy(agent_return))logger.info(agent_return.inner_steps)st.session_state['ui'].render_assistant(agent_return)if __name__ == '__main__':root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))root_dir = os.path.join(root_dir, 'tmp_dir')os.makedirs(root_dir, exist_ok=True)main()

Demo運行

streamlit run /root/code/lagent/examples/react_web_demo.py --server.address 127.0.0.1 --server.port 6006

運行效果:
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/714550.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/714550.shtml
英文地址,請注明出處:http://en.pswp.cn/news/714550.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

進程間的通信 -- 共享內存

一 共享內存的概念 1. 1 共享內存的原理 之前我們學過管道通信&#xff0c;分為匿名管道和命名管道&#xff0c;匿名管道通過父子進程的屬性繼承原理來完成父子進程看到同一份資源的目的&#xff0c;而命名管道則是通過路徑與文件名來唯一標識管道文件&#xff0c;來讓不同的進…

學習Android的第二十一天

目錄 Android ProgressDialog (進度條對話框) 例子 Android DatePickerDialog 日期選擇對話框 例子 Android TimePickerDialog 時間選擇對話框 Android PopupWindow 懸浮框 構造函數 方法 例子 官方文檔 Android OptionMenu 選項菜單 例子 官方文檔 Android Progr…

Java實戰:Spring Boot中各類參數校驗機制

引言 在開發Web應用程序時&#xff0c;對客戶端傳入的參數進行有效校驗是保證系統安全性和穩定性的重要環節。Spring Boot作為一個現代化的Java開發框架&#xff0c;提供了多種參數校驗的方法和工具&#xff0c;以滿足不同場景下的需求。本文將深入探討Spring Boot中實現各種參…

typescript 的常用方式

文章目錄 前言一、綁定props 默認值的方式&#xff1a;withDefaults1.vue2 的props設置默認值2.vue3 的props設置默認值(1) 不設置默認值的寫法(2) 設置默認值的寫法&#xff08;分離模式&#xff09;(3) 設置默認值的寫法&#xff08;組合模式&#xff09; 二、定義一個二維數…

Matlab在同一張圖中如何加入多個圖例

根據代碼最終畫出的圖片如下&#xff1a; 其實原理很簡單&#xff0c;就是在一張figure中畫多個坐標軸&#xff0c;每個坐標軸都有對應的圖例&#xff0c;之后再將多余坐標軸隱藏&#xff0c;只保留一個即可。 代碼如下&#xff1a; clear all; close all;dd_linewidth 1;a …

maven archetype 項目原型

拓展閱讀 maven 包管理平臺-01-maven 入門介紹 Maven、Gradle、Ant、Ivy、Bazel 和 SBT 的詳細對比表格 maven 包管理平臺-02-windows 安裝配置 mac 安裝配置 maven 包管理平臺-03-maven project maven 項目的創建入門 maven 包管理平臺-04-maven archetype 項目原型 ma…

Spring學習筆記(六)利用Spring的jdbc實現學生管理系統的用戶登錄功能

一、案例分析 本案例要求學生在控制臺輸入用戶名密碼&#xff0c;如果用戶賬號密碼正確則顯示用戶所屬班級&#xff0c;如果登錄失敗則顯示登錄失敗。 &#xff08;1&#xff09;為了存儲學生信息&#xff0c;需要創建一個數據庫。 &#xff08;2&#xff09;為了程序連接數…

洛谷P1927防護傘

題目描述 據說 20122012 的災難和太陽黑子的爆發有關。于是地球防衛小隊決定制造一個特殊防護傘&#xff0c;擋住太陽黑子爆發的區域&#xff0c;減少其對地球的影響。由于太陽相對于地球來說實在是太大了&#xff0c;我們可以把太陽表面看作一個平面&#xff0c;中心定為(0,0…

C 基本語法

我們已經看過 C 程序的基本結構&#xff0c;這將有助于我們理解 C 語言的其他基本的構建塊。 C 的令牌&#xff08;Token&#xff09; C 程序由各種令牌組成&#xff0c;令牌可以是關鍵字、標識符、常量、字符串值&#xff0c;或者是一個符號。例如&#xff0c;下面的 C 語句…

30天自制操作系統(第23天)

23.1 編寫malloc 參考第22天的內容&#xff0c;在繪制窗口前先分配了150*50個字節大小的內存&#xff0c;所以導致該文件經編譯后有7.6k左右&#xff0c;能否在其中使用指針呢&#xff1f;當需要開辟空間時&#xff0c;移動指針即可。在之前的章節中也有函數memman_alloc函數可…

php源碼 單色bmp圖片取模工具 按任意方式取模 生成字節數組 自由編輯點陣

http://2.wjsou.com/BMP/index.html 想試試chatGPT4生成&#xff0c;還是要手工改 php 寫一個網頁界面上可以選擇一張bmp圖片&#xff0c;界面上就顯示這張bmp圖片&#xff0c; 點生成取模按鈕&#xff0c;在圖片下方會顯示這張bmp圖片的取模數據。 取模規則是按界面設置的&a…

Linux 的交換空間(swap)是什么?有什么用?

目錄 swap是什么&#xff1f;swap有什么用&#xff1f;swap使用典型場景如何查看你的系統是否用到交換空間呢&#xff1f;查看系統中swap in/out的情況 swap是什么&#xff1f; swap就是磁盤上的一塊區域。它和Windows系統中的交換文件作用類似&#xff0c;但是它是一段連續的…

03、MongoDB -- MongoDB 權限的設計

目錄 MongoDB 權限的設計演示前準備&#xff1a;啟動 mongodb 服務器 和 客戶端 &#xff1a;1、啟動單機模式的 mongodb 服務器2、啟動 mongodb 的客戶端 MongoDB 權限的設計1、MongoDB 的每個數據庫都可以保存用戶&#xff0c;不止admin數據庫可以保存用戶。2、保存用戶的數據…

Linux 學習筆記(8)

八、 啟動引導 1 、 Linux 的啟動流程 1) BIOS 自檢 2) 啟動 GRUB/LILO 3) 運行 Linux kernel 并檢測硬件 4) 掛載根文件系統 5) 運行 Linux 系統的第一個進程 init( 其 PID 永遠為 1 &#xff0c;是所有其它進程的父進程 ) 6) init 讀取系統引導配置文件…

GD25Q32驅動

GD25Q32是一款基于SPI的Flash芯片&#xff0c;容量為32/84M bytes。它的引腳如下&#xff1a; 該芯片支持多種SPI操作方式&#xff0c;包括&#xff1a;Standard SPI(標準SPI)、Dual SPI(雙線 SPI)和Quad SPI(四線 SPI) 。有關SPI的介紹可以參考&#xff1a; SPI通信原理-CSDN…

flutter 文字一行顯示,超出換行

因為app有多語言&#xff0c;中文和其他語言長度不一致&#xff0c;可能導致英文會很長。 中文樣式 英文樣式 代碼 Row(mainAxisAlignment: MainAxisAlignment.end,crossAxisAlignment: CrossAxisAlignment.end,children: [Visibility(visible: controller.info.fee ! null,ch…

探尋2024年國內熱門低代碼平臺排行!| 功能特點一覽

低代碼開發是一項革命性的技術&#xff0c;主要目的是盡量避免程序研發的復雜性&#xff0c;讓外行開發者也能加入到應用程序的搭建中。低代碼平臺的核心概念和構成部分通常包括用戶界面和拖拽設計、預構件和模塊、自動化工作內容與數據庫集成和擴展應用&#xff0c;應用低代碼…

web前端css基本內容

web前端css 當我們用html的語法給內容規劃布局樣式時&#xff0c;可能會出現許多個相似的內容需要運用同一種樣式&#xff0c;復制粘貼太麻煩而且如果后期要改動的話比如把許多個地方從紅色改成藍色&#xff0c;就需要一個一個改了&#xff0c;這時候就需要引入css來操作了 把…

java-使用jacob刪除指定文件夾的郵件

總結見文章最后,具體代碼如下: ActiveXComponent outlook = new ActiveXComponent("Outlook.Application");Dispatch myNamespace = Dispatch.call(outlook, "GetNamespace", "MAPI").toDispatch();//指定搜索特定的文件Dispatch allFolders =…

我耀學IT—day05-Bootstrap下拉菜單與導航

一、Bootstrap5 下拉菜單 下拉菜單是可切換的&#xff0c;是以列表格式顯示鏈接的上下文菜單。 例&#xff1a; <div class"dropdown"><button type"button" class"btn btn-primary dropdown-toggle" data-bs-toggle"dropdown&…