One approach would be to identify a minimum difference in saturation (S) and either value or lightness (V/L); or some combination thereof. Convert the foreground text colour and the tag colour to HS{V/L} and compute the difference. If it's not big enough, adjust S and V/L while keeping H constant. Then convert back to RGB and use for the tag background.
colorsys seems to give S=0 for black, but treating that as S=1.0 might be more useful.
Also, I think this is what you've already suggested, but the border around the tag text should always be the unaltered tag colour.
@Jeff: the Python standard library is a treasure trove of neat stuff. For example, searching for "color" brought up http:// docs.python. org/library/ colorsys. html. There are also lots of cool diagrams at http:// en.wikipedia. org/wiki/ HSL_and_ HSV.
One approach would be to identify a minimum difference in saturation (S) and either value or lightness (V/L); or some combination thereof. Convert the foreground text colour and the tag colour to HS{V/L} and compute the difference. If it's not big enough, adjust S and V/L while keeping H constant. Then convert back to RGB and use for the tag background.
colorsys seems to give S=0 for black, but treating that as S=1.0 might be more useful.
Also, I think this is what you've already suggested, but the border around the tag text should always be the unaltered tag colour.