eaglelandsonce/GraniteGuruLabLab
0
1import streamlit as st2import os3import numpy as np4import matplotlib.pyplot as plt5from ibm_watsonx_ai.foundation_models import Model6from matplotlib.colors import ListedColormap7 8st.set_page_config(page_title="Granite Gurus Many Eyes", layout="wide")9 10# Set up the tabs11tab1, tab2, tab3 = st.tabs(["Project Intro", "Granite Search", "Notes"])12 13# Initialize session state for credentials if not already initialized14if 'apikey' not in st.session_state:15 st.session_state.apikey = ''16if 'project_id' not in st.session_state:17 st.session_state.project_id = ''18if 'credentials_submitted' not in st.session_state:19 st.session_state.credentials_submitted = False20 21# Tab 1: Project Intro22with tab1:23 st.header("Project Introduction")24 st.write("""25 Welcome to the Granite Gurus Many Eyes Hackathon project. 26 This project is an extension of the previous Hackathons: Build Your AI Startup, Codestral, and Edge Runners.27 28 In this project, we focus on introducing two powerful principles: 29 1. **Uniqueness**30 2. **Many Eyes**31 These principles are demonstrated through a search engine that sits on top of IBM Granite.32 """)33 34 # Embed a YouTube video35 video_url = "https://www.youtube.com/watch?v=Zk1V_V9GoHQ"36 st.video(video_url)37 38# Tab 2: Granite Search39with tab2:40 # Function to modify the generated number according to the rules41 def modify_number(number):42 modified_number = ''43 for digit in number:44 if digit not in '01': # Change any digit that is not 0 or 1 to 145 modified_number += '1'46 else:47 modified_number += digit48 return modified_number49 50 # Function to create the grid based on the boolean string51 def create_grid(boolean_string):52 if len(boolean_string) != 16:53 st.error("The generated string is not 16 digits long.")54 return None55 56 # Convert string to a list of integers57 grid = np.array([int(bit) for bit in boolean_string]).reshape(4, 4)58 59 # Create a colormap for the grid60 cmap = ListedColormap(['white', 'black'])61 62 # Plot the grid63 fig, ax = plt.subplots(figsize=(2, 2)) # Shrink the graph size64 ax.matshow(grid, cmap=cmap)65 66 # Add grid lines and remove ticks67 ax.set_xticks(np.arange(-0.5, 4, 1), minor=True)68 ax.set_yticks(np.arange(-0.5, 4, 1), minor=True)69 ax.grid(which='minor', color='gray', linestyle='-', linewidth=2)70 ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)71 72 return fig73 74 # Function to interpolate between start and end values75 def interpolate_value(start_value, end_value, position, max_position):76 difference = end_value - start_value77 interpolated_value = start_value + (difference * (position / max_position))78 interpolated_value_int = int(interpolated_value)79 binary_representation = bin(interpolated_value_int)[2:].zfill(16)80 81 return binary_representation82 83 # Streamlit app84 def main():85 st.title("Granite Star Search with IBM")86 87 # Sliders for selecting the start value and position88 start_value = st.slider("Start Value", 0, 65535, 32768)89 max_slider_value = 25690 position = st.slider("Radial Out", 0, max_slider_value, 0)91 92 # Define the distinct end values for each of the four numbers93 end_values = [0, 65280, 65534, 255]94 95 # Interpolate each value based on the slider position96 interpolated_values = [97 interpolate_value(start_value, end_values[0], position, max_slider_value), # Number 198 interpolate_value(start_value, end_values[1], position, max_slider_value), # Number 299 interpolate_value(start_value, end_values[2], position, max_slider_value), # Number 3100 interpolate_value(start_value, end_values[3], position, max_slider_value) # Number 4101 ]102 103 # Display the interpolated boolean strings horizontally104 st.write("Interpolated Boolean Strings:")105 cols = st.columns(len(interpolated_values)) # Create a column for each boolean string106 107 for i, boolean_string in enumerate(interpolated_values):108 with cols[i]: # Place each boolean string in its respective column109 st.write(f"Number {i+1}: {boolean_string}")110 111 # Manual input for the 5th grid112 manual_input = st.text_input("Enter a 16-digit boolean number (e.g., 1010101010101010):", "0000000000000000")113 114 # Validate and modify the input if necessary115 manual_input = modify_number(manual_input)116 117 # Display the grids in a row, including the manual input118 cols = st.columns(5) # Change the number of columns to 5119 for i, boolean_string in enumerate(interpolated_values):120 with cols[i]:121 st.write(f"Grid Number {i+1}:")122 fig = create_grid(boolean_string)123 if fig:124 st.pyplot(fig)125 126 # Add the 5th grid for the manual input127 with cols[4]: # Use the 5th column for the manual input grid128 st.write("Predicted Pattern:")129 if len(manual_input) != 16:130 st.error("The input is not 16 digits long.")131 else:132 fig = create_grid(manual_input)133 if fig:134 st.pyplot(fig)135 136 # Request the IBM API key and Project ID from the user137 st.session_state.apikey = st.text_input("Enter your IBM API Key:", type="password")138 st.session_state.project_id = st.text_input("Enter your Project ID:")139 140 # Only show "Predict Next Pattern" button if both credentials are provided141 if st.session_state.apikey and st.session_state.project_id:142 if st.button("Predict Next Pattern"):143 st.session_state.credentials_submitted = True144 145 # Proceed if credentials are submitted146 if st.session_state.credentials_submitted:147 # Model and parameters148 model_id = "ibm/granite-13b-chat-v2"149 parameters = {150 "decoding_method": "greedy",151 "max_new_tokens": 900,152 "repetition_penalty": 1.05153 }154 155 # Initialize the model156 model = Model(157 model_id=model_id,158 params=parameters,159 credentials={"url": "https://us-south.ml.cloud.ibm.com", "apikey": st.session_state.apikey},160 project_id=st.session_state.project_id161 )162 163 # Prepare the prompt for the model164 prompt_input = """165 Analyze the four 16 digit boolean numbers, identify the underlying pattern in the sequence, and use this underlying pattern to predict the next 16 digit boolean number. Return only the predicted boolean number 16 digits long. If it is not 15 digit add leading zeros to make it 16 digits.166 """167 formatted_question = " ".join(interpolated_values)168 prompt = f"{prompt_input}\n{formatted_question}"169 170 # Generate and display the response171 generated_response = model.generate_text(prompt=prompt, guardrails=False)172 st.write(f"**Predicted Next Boolean Number:** {generated_response}")173 else:174 st.warning("Please provide both API key and Project ID to proceed.")175 176 if __name__ == "__main__":177 main()178 179# Tab 3: Notes180with tab3:181 st.header("Notes")182 st.write("Setting up your IBM Account.")183 mynotes = """184 Steps to get the API Key1851. Go to the main website. https://cloud.ibm.com/1862. Then click on “manage” on the top bar. In the drop down menu click “Access(IAM)”. It will take you to this link: https://cloud.ibm.com/iam1873. Now, In the left side bar click on “API Keys”. It will take you to this link: https://cloud.ibm.com/iam/apikeys1884. Then just create a key. You can also download the key value.189In the code we also need Project_ID. I have set it up as hugging face secrets. here are the steps too create a project and get its ID. Steps to get the project ID:1901. Go this link: https://dataplatform.cloud.ibm.com/wx/home?context=wx1912. Go to the end of the page to the “Projects section” and click on “+”. Enter any name for the project. 1923. Then open the project. You will see a tab “Manage”. Click on it and you will see the project ID. You can refer to the attached screenshot to get an idea too.1934. Also for testing prompt lab you have to associate a Watson instance with it. Just click on “Services & integrations” then click on “Associate” service and select “Watsonx Challenge-XML”. 194 """195 st.write(mynotes)196 