in the following streamlit code can we have the text "Using Ollama Vision Model for…
- User
in the following streamlit code can we have the text "Using Ollama Vision Model for Image Analysis" below the "Enter your prompt here" input box:
import streamlit as st import ollama from PIL import Image import io import json from datetime import datetime import os import shutil
def delete_conversation(filename): # Delete JSON file json_path = os.path.join('conversations', filename) if os.path.exists(json_path): os.remove(json_path)
# Delete associated image if it exists image_filename = f"image_{filename.split('_')[1].split('.')[0]}.png" image_path = os.path.join('conversations', image_filename) if os.path.exists(image_path): os.remove(image_path)def save_conversation(messages, image=None): if not messages: # Don't save empty conversations return None
if not os.path.exists('conversations'): os.makedirs('conversations') timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") conversation_data = { 'timestamp': timestamp, 'messages': messages } filename = f'conversations/conversation_{timestamp}.json' with open(filename, 'w') as f: json.dump(conversation_data, f, indent=4) if image: image_filename = f'conversations/image_{timestamp}.png' image.save(image_filename) return filenamedef load_conversation(filename): with open(filename, 'r') as f: return json.load(f)
def get_saved_conversations(): if not os.path.exists('conversations'): return [] files = [f for f in os.listdir('conversations') if f.endswith('.json')] conversations = [] for file in files: with open(os.path.join('conversations', file), 'r') as f: data = json.load(f) conversations.append({ 'filename': file, 'timestamp': data['timestamp'], 'preview': data['messages'][0]['content'] if data['messages'] else 'Empty conversation' }) return sorted(conversations, key=lambda x: x['timestamp'], reverse=True)
def process_image_and_text(image, text_prompt, messages_history): if image is not None: img_byte_arr = io.BytesIO() image.save(img_byte_arr, format=image.format) img_byte_arr = img_byte_arr.getvalue()
try: response = ollama.chat( model='llama3.2-vision', messages=[*messages_history, { 'role': 'user', 'content': text_prompt, 'images': [img_byte_arr] }] ) return response['message']['content'] except Exception as e: return f"Error processing request: {str(e)}" return "Please upload an image first"def main(): st.set_page_config( page_title="Image Analysis with Ollama", page_icon="🔍", layout="wide" )
# Initialize session states if 'messages' not in st.session_state: st.session_state.messages = [] if 'current_image' not in st.session_state: st.session_state.current_image = None if 'uploaded_file' not in st.session_state: st.session_state.uploaded_file = None st.title("Image Analysis with Ollama Vision Model") # Sidebar for conversation management with st.sidebar: st.header("Conversation Management") # New conversation button if st.button("New Conversation"): if st.session_state.messages: save_conversation(st.session_state.messages, st.session_state.current_image) st.session_state.messages = [] st.session_state.current_image = None st.session_state.uploaded_file = None st.rerun() # Clear conversation button if st.button("Clear Current Conversation"): st.session_state.messages = [] st.session_state.current_image = None st.rerun() # Load and manage previous conversations st.header("Previous Conversations") conversations = get_saved_conversations() for conv in conversations: col1, col2 = st.columns([3, 1]) with col1: if st.button(f"Load: {conv['timestamp']}", key=f"load_{conv['filename']}"): loaded_conv = load_conversation(os.path.join('conversations', conv['filename'])) st.session_state.messages = loaded_conv['messages'] st.rerun() with col2: if st.button("🗑️", key=f"delete_{conv['filename']}"): delete_conversation(conv['filename']) st.rerun() # Add button to delete all conversations if st.button("Delete All Conversations"): if os.path.exists('conversations'): shutil.rmtree('conversations') st.rerun() # Main chat interface col1, col2 = st.columns(2) with col1: uploaded_file = st.file_uploader( "Choose an image...", type=['png', 'jpg', 'jpeg'], key="file_uploader" ) if uploaded_file is not None: image = Image.open(uploaded_file) st.session_state.current_image = image st.image(image, caption='Uploaded Image', use_container_width=True) # Display chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Chat input if prompt := st.chat_input("Enter your prompt here"): with st.chat_message("user"): st.markdown(prompt) st.session_state.messages.append({"role": "user", "content": prompt}) if uploaded_file is not None: with st.spinner('Processing...'): messages_history = [{"role": m["role"], "content": m["content"]} for m in st.session_state.messages[:-1]] response = process_image_and_text(image, prompt, messages_history) with st.chat_message("assistant"): st.markdown(response) st.session_state.messages.append({"role": "assistant", "content": response}) else: st.error("Please upload an image") st.markdown("---") st.markdown( """ <div style='text-align: center'> <p>Using Ollama Vision Model for Image Analysis</p> </div> """, unsafe_allow_html=True ) - Assistant