Created
December 19, 2024 10:09
-
-
Save izikeros/2308fc4cafeecf3ad61157c08bc1604f to your computer and use it in GitHub Desktop.
[display_colored_text_demo.py] text coloring, useful when working on RAG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Demo for displaying colored text in Jupyter Notebook.""" | |
import matplotlib | |
import matplotlib.pyplot as plt | |
from IPython.display import HTML, display | |
def importance_to_color(importance): | |
cmap = plt.get_cmap("Greys") # YlOrRd, Greys | |
rgba = cmap(importance) | |
return matplotlib.colors.rgb2hex(rgba) | |
def display_colored_text(items, sepatate_lines=False): | |
if sepatate_lines: | |
colored_text = [ | |
f'<p style="color: {importance_to_color(item["importance"])}">{item["text"]}</p>' | |
for item in items | |
] | |
else: | |
colored_text = [ | |
f'<span style="color: {importance_to_color(item["importance"])}">{item["text"]}</span>' | |
for item in items | |
] | |
display(HTML(" ".join(colored_text))) | |
items = [ | |
{"text": "Hello, world!", "importance": 0.5}, | |
{"text": "How are you?", "importance": 0.7}, | |
{"text": "Goodbye", "importance": 0.15}, | |
{"text": "How it is going?", "importance": 0.99}, | |
{"text": "Goodbye", "importance": 0.2}, | |
{"text": "How are you?", "importance": 0.7}, | |
] | |
# display the colored text | |
display_colored_text(items) | |
# items |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment