Skip to content

Commit

Permalink
simplify the colors builtin
Browse files Browse the repository at this point in the history
  • Loading branch information
rgbkrk committed Mar 4, 2024
1 parent 35dc6d1 commit 1e6311f
Show file tree
Hide file tree
Showing 4 changed files with 209 additions and 446 deletions.
57 changes: 21 additions & 36 deletions chatlab/builtins/colors.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,43 @@
"""Color hacking in the notebook.
This module exposes a function that will display a color palette in a notebook"""
"""Let models pick and show color palettes to you."""
import hashlib
from typing import Dict, List, Optional
from pydantic import BaseModel, validator, Field

from IPython.display import display


class Palette:
class Palette(BaseModel):
"""A palette of colors for the user to see."""
colors: List[str] = Field(..., description="A list of CSS colors to display.")
name: Optional[str] = None

def __init__(self, colors: List[str], name: Optional[str]):
"""Creates a palette of colors for the user to see."""
self.colors = colors
self.name = name

@property
def colors(self):
"""Returns the colors in the palette."""
return self._colors

@colors.setter
def colors(self, colors: List[str]):
self._colors = colors
self.html = "<div>"
for color in colors:
self.html += f'<div style="background-color:{color}; width:50px; height:50px; display:inline-block;"></div>'
self.html += "</div>"
@validator('colors', each_item=True)
def check_color_validity(cls, v):
if not isinstance(v, str):
raise ValueError('Each color must be a string representation of a CSS color.')
if not all(c.isalnum() or c in '#.,()% ' for c in v):
raise ValueError('Color contains invalid characters. Only alphanumeric and CSS color specific characters are allowed.')
return v

def _repr_html_(self):
return self.html
html = "<div>"
for color in self.colors:
html += f'<div style="background-color:{color}; width:50px; height:50px; display:inline-block;"></div>'
html += "</div>"

return html

def __repr__(self):
"""Returns a string representation of the palette."""
return f"Palette({self.colors}, {self.name})"


palettes: Dict[str, Palette] = {}


def _generate_palette_name(colors: List[str]) -> str:
hash_object = hashlib.sha1("".join(colors).encode())
return f"palette-{hash_object.hexdigest()}"


def show_colors(colors: List[str], store_as: Optional[str] = None):
def show_colors(colors: List[str]):
"""Shows a list of CSS colors for the user in their notebook."""
global palettes

if store_as is None:
store_as = _generate_palette_name(colors)

palette = Palette(colors, store_as)
palettes[store_as] = palette
palette = Palette(colors=colors)

display(palette)
return f"Displayed colors for user and stored as `palettes['{store_as}']`."
return f"Displayed colors for user."
126 changes: 39 additions & 87 deletions notebooks/basics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,13 @@
{
"data": {
"text/markdown": [
"Murkrow is a Pokémon species in the popular franchise. It is categorized as the \"Darkness\" Pokémon and it resembles a crow or raven in appearance. However, in real life, there is no bird species called \"Murkrow.\""
"Murkrow is a fictional Pokémon species in the Pokémon franchise. It is a Dark/Flying type Pokémon that resembles a crow or raven."
],
"text/plain": [
"Murkrow is a Pokémon species in the popular franchise. It is categorized as the \"Darkness\" Pokémon and it resembles a crow or raven in appearance. However, in real life, there is no bird species called \"Murkrow.\""
"AssistantMessageView(display_id='98a8e327-1f13-4e72-aef2-9a2bf738edae', content='Murkrow is a fictional Pokémon species in the Pokémon franchise. It is a Dark/Flying type Pokémon that resembles a crow or raven.', finished=False, has_displayed=True)"
]
},
"metadata": {
"text/markdown": {
"chatlab": {
"default": true
}
}
},
"metadata": {},
"output_type": "display_data"
}
],
Expand All @@ -52,35 +46,27 @@
{
"data": {
"text/markdown": [
"Certainly! To get started, let's first load the data from the CSV file \"circulation-grade-6.csv\". We can use the pandas library for this task. Assuming the file is in the same directory as your Jupyter Notebook, you can use the following code:\n",
"Sure! To start working with the \"circulation-grade-6.csv\" file, we need to load it into a pandas DataFrame. Here's how you can do it:\n",
"\n",
"``` python\n",
"```python\n",
"import pandas as pd\n",
"\n",
"data = pd.read_csv('circulation-grade-6.csv')\n",
"# Load the CSV file into a DataFrame\n",
"df = pd.read_csv('circulation-grade-6.csv')\n",
"\n",
"# Display the first few rows of the DataFrame\n",
"df.head()\n",
"```\n",
"\n",
"Now that the data is loaded, we can start exploring it and performing various operations. Could you please provide some specific tasks you would like to accomplish or any questions you have about the data?"
"This code will load the CSV file into a DataFrame called `df` and display the first few rows of the DataFrame. You can adjust the number of rows to display by passing an argument to the `head()` function.\n",
"\n",
"Once you have loaded the data, you can perform various operations on it, such as data cleaning, exploration, and analysis. Let me know what specific tasks or analysis you would like to perform on the data, and I'll be happy to assist you further."
],
"text/plain": [
"Certainly! To get started, let's first load the data from the CSV file \"circulation-grade-6.csv\". We can use the pandas library for this task. Assuming the file is in the same directory as your Jupyter Notebook, you can use the following code:\n",
"\n",
"``` python\n",
"import pandas as pd\n",
"\n",
"data = pd.read_csv('circulation-grade-6.csv')\n",
"```\n",
"\n",
"Now that the data is loaded, we can start exploring it and performing various operations. Could you please provide some specific tasks you would like to accomplish or any questions you have about the data?"
"AssistantMessageView(display_id='a05a1a2d-3cde-4aef-b478-ed7a6674be82', content='Sure! To start working with the \"circulation-grade-6.csv\" file, we need to load it into a pandas DataFrame. Here\\'s how you can do it:\\n\\n```python\\nimport pandas as pd\\n\\n# Load the CSV file into a DataFrame\\ndf = pd.read_csv(\\'circulation-grade-6.csv\\')\\n\\n# Display the first few rows of the DataFrame\\ndf.head()\\n```\\n\\nThis code will load the CSV file into a DataFrame called `df` and display the first few rows of the DataFrame. You can adjust the number of rows to display by passing an argument to the `head()` function.\\n\\nOnce you have loaded the data, you can perform various operations on it, such as data cleaning, exploration, and analysis. Let me know what specific tasks or analysis you would like to perform on the data, and I\\'ll be happy to assist you further.', finished=False, has_displayed=True)"
]
},
"metadata": {
"text/markdown": {
"chatlab": {
"default": true
}
}
},
"metadata": {},
"output_type": "display_data"
}
],
Expand Down Expand Up @@ -154,11 +140,7 @@
{
"data": {
"text/plain": [
"{'name': 'what_time',\n",
" 'description': 'Current time, defaulting to UTC',\n",
" 'parameters': {'title': 'WhatTime',\n",
" 'type': 'object',\n",
" 'properties': {'tz': {'title': 'Tz', 'type': 'string'}}}}"
"FunctionDefinition(name='what_time', description='Current time, defaulting to UTC', parameters={'properties': {'tz': {'anyOf': [{'type': 'string'}, {'type': 'null'}]}}, 'required': ['tz'], 'type': 'object'})"
]
},
"execution_count": 4,
Expand Down Expand Up @@ -259,7 +241,7 @@
}
},
"children": [
""
"..."
],
"tagName": "span"
}
Expand Down Expand Up @@ -304,7 +286,7 @@
}
},
"children": [
"{}"
"{\n \"tz\": null\n}"
],
"tagName": "div"
}
Expand All @@ -313,39 +295,7 @@
},
{
"attributes": {},
"children": [
{
"attributes": {
"style": {
"color": "#27374D",
"fontWeight": "500",
"marginBottom": "5px"
}
},
"children": [
"Output:"
],
"tagName": "div"
},
{
"attributes": {
"style": {
"background": "#F7F9FA",
"color": "#27374D",
"fontFamily": "monospace",
"marginBottom": "10px",
"overflowX": "auto",
"padding": "10px",
"unicodeBidi": "embed",
"whiteSpace": "pre"
}
},
"children": [
"06:08 PM"
],
"tagName": "div"
}
],
"children": [],
"tagName": "div"
}
],
Expand All @@ -358,10 +308,14 @@
"tagName": "div"
},
"text/html": [
"<div><style>.chatlab-chat-details summary &gt; * { display: inline; color: #27374D; }</style><details style=\"background: #DDE6ED; border-radius: 5px; padding: .5rem 1rem\" className=\"chatlab-chat-details\"><summary style=\"color: #27374D; cursor: pointer\"><span style=\"color: #9DB2BF; padding-left: 5px; padding-right: 5px\">𝑓</span><span style=\"color: #27374D; padding-left: 5px; padding-right: 5px\">Ran</span><span style=\"font-family: monospace; unicode-bidi: embed; white-space: pre\">what_time</span><span style=\"font-family: monospace; unicode-bidi: embed; white-space: pre\"></span></summary><div style=\"margin-left: 10px; margin-top: 10px\"><div><div style=\"color: #27374D; font-weight: 500; margin-bottom: 5px\">Input:</div><div style=\"background: #F7F9FA; color: #27374D; font-family: monospace; margin-bottom: 10px; overflow-x: auto; padding: 10px; unicode-bidi: embed; white-space: pre\">{}</div></div><div><div style=\"color: #27374D; font-weight: 500; margin-bottom: 5px\">Output:</div><div style=\"background: #F7F9FA; color: #27374D; font-family: monospace; margin-bottom: 10px; overflow-x: auto; padding: 10px; unicode-bidi: embed; white-space: pre\">06:08 PM</div></div></div></details></div>"
"<div><style>.chatlab-chat-details summary &gt; * { display: inline; color: #27374D; }</style><details style=\"background: #DDE6ED; border-radius: 5px; padding: .5rem 1rem\" className=\"chatlab-chat-details\"><summary style=\"color: #27374D; cursor: pointer\"><span style=\"color: #9DB2BF; padding-left: 5px; padding-right: 5px\">𝑓</span><span style=\"color: #27374D; padding-left: 5px; padding-right: 5px\">Ran</span><span style=\"font-family: monospace; unicode-bidi: embed; white-space: pre\">what_time</span><span style=\"font-family: monospace; unicode-bidi: embed; white-space: pre\">...</span></summary><div style=\"margin-left: 10px; margin-top: 10px\"><div><div style=\"color: #27374D; font-weight: 500; margin-bottom: 5px\">Input:</div><div style=\"background: #F7F9FA; color: #27374D; font-family: monospace; margin-bottom: 10px; overflow-x: auto; padding: 10px; unicode-bidi: embed; white-space: pre\">{\n",
" &quot;tz&quot;: null\n",
"}</div></div><div></div></div></details></div>"
],
"text/plain": [
"<chatlab.display.ChatFunctionCall at 0x106c7b550>"
"<div><style>.chatlab-chat-details summary &gt; * { display: inline; color: #27374D; }</style><details style=\"background: #DDE6ED; border-radius: 5px; padding: .5rem 1rem\" className=\"chatlab-chat-details\"><summary style=\"color: #27374D; cursor: pointer\"><span style=\"color: #9DB2BF; padding-left: 5px; padding-right: 5px\">𝑓</span><span style=\"color: #27374D; padding-left: 5px; padding-right: 5px\">Ran</span><span style=\"font-family: monospace; unicode-bidi: embed; white-space: pre\">what_time</span><span style=\"font-family: monospace; unicode-bidi: embed; white-space: pre\">...</span></summary><div style=\"margin-left: 10px; margin-top: 10px\"><div><div style=\"color: #27374D; font-weight: 500; margin-bottom: 5px\">Input:</div><div style=\"background: #F7F9FA; color: #27374D; font-family: monospace; margin-bottom: 10px; overflow-x: auto; padding: 10px; unicode-bidi: embed; white-space: pre\">{\n",
" &quot;tz&quot;: null\n",
"}</div></div><div></div></div></details></div>"
]
},
"metadata": {},
Expand All @@ -370,19 +324,13 @@
{
"data": {
"text/markdown": [
"The current time is 06:08 PM."
"The current time is 12:44 PM."
],
"text/plain": [
"The current time is 06:08 PM."
"AssistantMessageView(display_id='e5c26ac5-6bc1-437e-a369-8b021e720449', content='The current time is 12:44 PM.', finished=False, has_displayed=True)"
]
},
"metadata": {
"text/markdown": {
"chatlab": {
"default": true
}
}
},
"metadata": {},
"output_type": "display_data"
}
],
Expand All @@ -401,10 +349,14 @@
"text/plain": [
"[{'role': 'user', 'content': 'What time is it?'},\n",
" {'role': 'assistant',\n",
" 'content': None,\n",
" 'function_call': {'name': 'what_time', 'arguments': '{}'}},\n",
" {'role': 'function', 'content': '06:08 PM', 'name': 'what_time'},\n",
" {'role': 'assistant', 'content': ''}]"
" 'tool_calls': [{'id': 'call_YNqXo5IGQHFNkHXbacF1cfM7',\n",
" 'function': {'name': 'what_time', 'arguments': '{\\n \"tz\": null\\n}'},\n",
" 'type': 'function'}]},\n",
" {'role': 'tool',\n",
" 'name': 'what_time',\n",
" 'content': '12:44 PM',\n",
" 'tool_call_id': 'call_YNqXo5IGQHFNkHXbacF1cfM7'},\n",
" {'role': 'assistant', 'content': 'The current time is 12:44 PM.'}]"
]
},
"execution_count": 6,
Expand Down Expand Up @@ -687,9 +639,9 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python (chatlab-dev)",
"display_name": "chatlab-0EWIBOuo-py3.11",
"language": "python",
"name": "python-chatlab-dev"
"name": "python3"
},
"language_info": {
"codemirror_mode": {
Expand All @@ -701,7 +653,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.1"
"version": "3.11.7"
}
},
"nbformat": 4,
Expand Down
4 changes: 3 additions & 1 deletion notebooks/color-picker.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@
"AssistantMessageView(display_id='a80ad66d-dfb5-4349-881f-c46050acb576', content='Here is a dark-themed color palette suitable for a portfolio website:\\n\\n1. **Primary Background**: `#1C1C1E` - A deep, dark gray that serves as a strong base for the dark theme.\\n2. **Secondary Background**: `#2C2C2E` - Slightly lighter than the primary background, for sections or card backgrounds.\\n3. **Tertiary Background**: `#3A3A3C` - Even lighter, for subtle differentiation of UI elements like sidebars or modals.\\n4. **Accent Background**: `#48484A` - A medium-dark gray that can be used for hover states or to highlight active elements.\\n5. **Neutral Text**: `#9DA5B4` - A muted blue-gray for body text that contrasts well against the dark backgrounds.\\n6. **Primary Accent**: `#6366F1` - A vibrant indigo for call-to-action buttons and links to stand out.\\n7. **Secondary Accent**: `#8B5CF6` - A purple accent for secondary buttons or interactive elements.\\n8. **Tertiary Accent**: `#EC4899` - A pink accent for highlights, icons, or progress bars.\\n9. **Quaternary Accent**: `#F43F5E` - A red accent for important warnings or errors.\\n10. **Highlight Accent**: `#10B981` - A fresh green for success messages or to denote active statuses.\\n\\nThis palette combines a range of dark grays to create depth and layering in the UI, with pops of color to draw attention to important elements and actions. The use of indigo, purple, pink, red, and green as accent colors adds vibrancy and visual interest to the dark theme, ensuring that the portfolio remains engaging and easy to navigate.', finished=False, has_displayed=True)"
]
},
"metadata": {},
"metadata": {
"role": "assistant"
},
"output_type": "display_data"
}
],
Expand Down
Loading

0 comments on commit 1e6311f

Please sign in to comment.