gsarti commited on
Commit
09bd8f1
1 Parent(s): a3fa4c8

Update v 0.0.6

Browse files
README.md CHANGED
@@ -6,7 +6,7 @@ tags:
6
  - textbox
7
  - editing
8
  - color
9
- title: gradio_highlightedtextbox v0.0.5
10
  colorFrom: indigo
11
  colorTo: green
12
  sdk: docker
 
6
  - textbox
7
  - editing
8
  - color
9
+ title: gradio_highlightedtextbox v0.0.6
10
  colorFrom: indigo
11
  colorTo: green
12
  sdk: docker
app.py CHANGED
@@ -4,64 +4,114 @@ from gradio_highlightedtextbox import HighlightedTextbox
4
 
5
 
6
  def convert_tagged_text_to_highlighted_text(
7
- tagged_text: str, tag_id: str, tag_open: str, tag_close: str
 
 
 
8
  ) -> list[tuple[str, str | None]]:
9
  return HighlightedTextbox.tagged_text_to_tuples(
10
  tagged_text, tag_id, tag_open, tag_close
11
  )
12
 
13
 
14
- with gr.Blocks() as demo:
15
- tag_id = gr.Textbox(
16
- "Potential issue",
17
- label="Tag ID",
18
- show_label=True,
19
- info="Insert a tag ID to use in the highlighted textbox.",
20
- )
21
- tag_open = gr.Textbox(
22
- "<h>",
23
- label="Tag open",
24
- show_label=True,
25
- info="Insert a tag to mark the beginning of a highlighted section.",
26
- )
27
- tag_close = gr.Textbox(
28
- "</h>",
29
- label="Tag close",
30
- show_label=True,
31
- info="Insert a tag to mark the end of a highlighted section.",
32
  )
 
 
 
 
 
 
33
  with gr.Row():
34
- tagged = gr.Textbox(
35
- "It is not something to be ashamed of: it is no different from the <h>personal fears</h> and <h>dislikes</h> of other things that <h>very many people</h> have.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  interactive=True,
37
- label="Input",
 
 
 
 
 
 
 
 
 
 
 
38
  show_label=True,
39
- info="Insert a text with <h>...</h> tags to mark spans that will be highlighted.",
 
40
  )
41
- high = HighlightedTextbox(
 
 
 
 
 
42
  interactive=True,
43
- label="Output",
44
- info="Highlighted textbox.",
45
  show_legend=True,
46
  show_label=True,
47
  legend_label="Legend:",
48
  show_legend_label=True,
49
  )
50
- button = gr.Button("Submit")
51
- button.click(
 
 
 
 
 
 
 
 
 
52
  fn=convert_tagged_text_to_highlighted_text,
53
- inputs=[tagged, tag_id, tag_open, tag_close],
54
- outputs=high,
55
  )
56
- # Initialization does not work
57
- high = HighlightedTextbox(
58
- convert_tagged_text_to_highlighted_text(
59
- tagged.value, tag_id.value, tag_open.value, tag_close.value
60
- ),
61
- interactive=True,
62
- label="Does not work",
63
- show_label=True,
64
  )
65
 
66
-
67
- demo.launch()
 
4
 
5
 
6
  def convert_tagged_text_to_highlighted_text(
7
+ tagged_text: str,
8
+ tag_id: str | list[str],
9
+ tag_open: str | list[str],
10
+ tag_close: str | list[str],
11
  ) -> list[tuple[str, str | None]]:
12
  return HighlightedTextbox.tagged_text_to_tuples(
13
  tagged_text, tag_id, tag_open, tag_close
14
  )
15
 
16
 
17
+ def convert_highlighted_text_to_tagged_text(
18
+ highlighted_text: dict[str, str | list[tuple[str, str | None]]],
19
+ tag_id: str | list[str],
20
+ tag_open: str | list[str],
21
+ tag_close: str | list[str],
22
+ ) -> str:
23
+ return HighlightedTextbox.tuples_to_tagged_text(
24
+ highlighted_text["data"], tag_id, tag_open, tag_close
 
 
 
 
 
 
 
 
 
 
25
  )
26
+
27
+
28
+ initial_text = "It is not something to be ashamed of: it is no different from the <d>personal fears</d> and <tm>dislikes</tm> of other things that <t>manny peopl</t> have."
29
+
30
+ with gr.Blocks() as demo:
31
+ gr.Markdown("### Parameters to control the highlighted textbox:")
32
  with gr.Row():
33
+ tag_id = gr.Dropdown(
34
+ choices=["Typo", "Terminology", "Disfluency"],
35
+ value=["Typo", "Terminology", "Disfluency"],
36
+ multiselect=True,
37
+ allow_custom_value=True,
38
+ label="Tag ID",
39
+ show_label=True,
40
+ info="Insert one or more tag IDs to use in the highlighted textbox.",
41
+ )
42
+ tag_open = gr.Dropdown(
43
+ choices=["<t>", "<tm>", "<d>"],
44
+ value=["<t>", "<tm>", "<d>"],
45
+ multiselect=True,
46
+ allow_custom_value=True,
47
+ label="Tag open",
48
+ show_label=True,
49
+ info="Insert one or more tags to mark the beginning of a highlighted section.",
50
+ )
51
+ tag_close = gr.Dropdown(
52
+ choices=["</t>", "</tm>", "</d>"],
53
+ value=["</t>", "</tm>", "</d>"],
54
+ multiselect=True,
55
+ allow_custom_value=True,
56
+ label="Tag close",
57
+ show_label=True,
58
+ info="Insert one or more tags to mark the end of a highlighted section.",
59
+ )
60
+ gr.Markdown("### Example tagged to highlight:")
61
+ with gr.Row():
62
+ tagged_t2h = gr.Textbox(
63
+ initial_text,
64
  interactive=True,
65
+ label="Tagged Input",
66
+ show_label=True,
67
+ info="Tagged text using the format above to mark spans that will be highlighted.",
68
+ )
69
+ high_t2h = HighlightedTextbox(
70
+ convert_tagged_text_to_highlighted_text(
71
+ tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
72
+ ),
73
+ interactive=False,
74
+ label="Highlighted Output",
75
+ info="Highlighted textbox intialized from the tagged input.",
76
+ show_legend=True,
77
  show_label=True,
78
+ legend_label="Legend:",
79
+ show_legend_label=True,
80
  )
81
+ gr.Markdown("### Example highlight to tagged:")
82
+ with gr.Row():
83
+ high_h2t = HighlightedTextbox(
84
+ convert_tagged_text_to_highlighted_text(
85
+ initial_text, tag_id.value, tag_open.value, tag_close.value
86
+ ),
87
  interactive=True,
88
+ label="Highlighted Input",
89
+ info="Highlighted textbox using the format above to mark spans that will be highlighted.",
90
  show_legend=True,
91
  show_label=True,
92
  legend_label="Legend:",
93
  show_legend_label=True,
94
  )
95
+ tagged_h2t = gr.Textbox(
96
+ initial_text,
97
+ interactive=False,
98
+ label="Tagged Output",
99
+ info="Tagged text intialized from the highlighted textbox.",
100
+ show_label=True,
101
+ )
102
+
103
+ # Functions
104
+
105
+ tagged_t2h.input(
106
  fn=convert_tagged_text_to_highlighted_text,
107
+ inputs=[tagged_t2h, tag_id, tag_open, tag_close],
108
+ outputs=high_t2h,
109
  )
110
+ high_h2t.input(
111
+ fn=convert_highlighted_text_to_tagged_text,
112
+ inputs=[high_h2t, tag_id, tag_open, tag_close],
113
+ outputs=tagged_h2t,
 
 
 
 
114
  )
115
 
116
+ if __name__ == "__main__":
117
+ demo.launch()
src/README.md CHANGED
@@ -18,7 +18,10 @@ from gradio_highlightedtextbox import HighlightedTextbox
18
 
19
 
20
  def convert_tagged_text_to_highlighted_text(
21
- tagged_text: str, tag_id: str, tag_open: str, tag_close: str
 
 
 
22
  ) -> list[tuple[str, str | None]]:
23
  return HighlightedTextbox.tagged_text_to_tuples(
24
  tagged_text, tag_id, tag_open, tag_close
@@ -27,64 +30,77 @@ def convert_tagged_text_to_highlighted_text(
27
 
28
  def convert_highlighted_text_to_tagged_text(
29
  highlighted_text: dict[str, str | list[tuple[str, str | None]]],
30
- tag_id: str,
31
- tag_open: str,
32
- tag_close: str,
33
  ) -> str:
34
  return HighlightedTextbox.tuples_to_tagged_text(
35
  highlighted_text["data"], tag_id, tag_open, tag_close
36
  )
37
 
38
 
39
- initial_text = "It is not something to be ashamed of: it is no different from the <h>personal fears</h> and <h>dislikes</h> of other things that <h>very many people</h> have."
40
 
41
  with gr.Blocks() as demo:
42
- tag_id = gr.Textbox(
43
- "Potential issue",
44
- label="Tag ID",
45
- show_label=True,
46
- info="Insert a tag ID to use in the highlighted textbox.",
47
- )
48
- tag_open = gr.Textbox(
49
- "<h>",
50
- label="Tag open",
51
- show_label=True,
52
- info="Insert a tag to mark the beginning of a highlighted section.",
53
- )
54
- tag_close = gr.Textbox(
55
- "</h>",
56
- label="Tag close",
57
- show_label=True,
58
- info="Insert a tag to mark the end of a highlighted section.",
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
60
  with gr.Row():
61
  tagged_t2h = gr.Textbox(
62
  initial_text,
63
  interactive=True,
64
- label="Input",
65
  show_label=True,
66
- info="Insert a text with <h>...</h> tags to mark spans that will be highlighted.",
67
  )
68
  high_t2h = HighlightedTextbox(
69
  convert_tagged_text_to_highlighted_text(
70
  tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
71
  ),
72
- interactive=True,
73
- label="Output",
74
- info="Highlighted textbox.",
75
  show_legend=True,
76
  show_label=True,
77
  legend_label="Legend:",
78
  show_legend_label=True,
79
  )
 
80
  with gr.Row():
81
  high_h2t = HighlightedTextbox(
82
  convert_tagged_text_to_highlighted_text(
83
- tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
84
  ),
85
  interactive=True,
86
- label="Input",
87
- info="The following text will be marked by spans according to its highlights.",
88
  show_legend=True,
89
  show_label=True,
90
  legend_label="Legend:",
@@ -92,31 +108,27 @@ with gr.Blocks() as demo:
92
  )
93
  tagged_h2t = gr.Textbox(
94
  initial_text,
95
- interactive=True,
96
- label="Output",
 
97
  show_label=True,
98
  )
99
 
100
  # Functions
101
 
102
- tagged_t2h.change(
103
  fn=convert_tagged_text_to_highlighted_text,
104
  inputs=[tagged_t2h, tag_id, tag_open, tag_close],
105
  outputs=high_t2h,
106
  )
107
- high_t2h.change(
108
- fn=lambda x: x["data"],
109
- inputs=high_t2h,
110
- outputs=high_h2t,
111
- )
112
- high_h2t.change(
113
  fn=convert_highlighted_text_to_tagged_text,
114
  inputs=[high_h2t, tag_id, tag_open, tag_close],
115
  outputs=tagged_h2t,
116
  )
117
 
118
-
119
- demo.launch()
120
 
121
  ```
122
 
 
18
 
19
 
20
  def convert_tagged_text_to_highlighted_text(
21
+ tagged_text: str,
22
+ tag_id: str | list[str],
23
+ tag_open: str | list[str],
24
+ tag_close: str | list[str],
25
  ) -> list[tuple[str, str | None]]:
26
  return HighlightedTextbox.tagged_text_to_tuples(
27
  tagged_text, tag_id, tag_open, tag_close
 
30
 
31
  def convert_highlighted_text_to_tagged_text(
32
  highlighted_text: dict[str, str | list[tuple[str, str | None]]],
33
+ tag_id: str | list[str],
34
+ tag_open: str | list[str],
35
+ tag_close: str | list[str],
36
  ) -> str:
37
  return HighlightedTextbox.tuples_to_tagged_text(
38
  highlighted_text["data"], tag_id, tag_open, tag_close
39
  )
40
 
41
 
42
+ initial_text = "It is not something to be ashamed of: it is no different from the <d>personal fears</d> and <tm>dislikes</tm> of other things that <t>manny peopl</t> have."
43
 
44
  with gr.Blocks() as demo:
45
+ gr.Markdown("### Parameters to control the highlighted textbox:")
46
+ with gr.Row():
47
+ tag_id = gr.Dropdown(
48
+ choices=["Typo", "Terminology", "Disfluency"],
49
+ value=["Typo", "Terminology", "Disfluency"],
50
+ multiselect=True,
51
+ allow_custom_value=True,
52
+ label="Tag ID",
53
+ show_label=True,
54
+ info="Insert one or more tag IDs to use in the highlighted textbox.",
55
+ )
56
+ tag_open = gr.Dropdown(
57
+ choices=["<t>", "<tm>", "<d>"],
58
+ value=["<t>", "<tm>", "<d>"],
59
+ multiselect=True,
60
+ allow_custom_value=True,
61
+ label="Tag open",
62
+ show_label=True,
63
+ info="Insert one or more tags to mark the beginning of a highlighted section.",
64
+ )
65
+ tag_close = gr.Dropdown(
66
+ choices=["</t>", "</tm>", "</d>"],
67
+ value=["</t>", "</tm>", "</d>"],
68
+ multiselect=True,
69
+ allow_custom_value=True,
70
+ label="Tag close",
71
+ show_label=True,
72
+ info="Insert one or more tags to mark the end of a highlighted section.",
73
+ )
74
+ gr.Markdown("### Example tagged to highlight:")
75
  with gr.Row():
76
  tagged_t2h = gr.Textbox(
77
  initial_text,
78
  interactive=True,
79
+ label="Tagged Input",
80
  show_label=True,
81
+ info="Tagged text using the format above to mark spans that will be highlighted.",
82
  )
83
  high_t2h = HighlightedTextbox(
84
  convert_tagged_text_to_highlighted_text(
85
  tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
86
  ),
87
+ interactive=False,
88
+ label="Highlighted Output",
89
+ info="Highlighted textbox intialized from the tagged input.",
90
  show_legend=True,
91
  show_label=True,
92
  legend_label="Legend:",
93
  show_legend_label=True,
94
  )
95
+ gr.Markdown("### Example highlight to tagged:")
96
  with gr.Row():
97
  high_h2t = HighlightedTextbox(
98
  convert_tagged_text_to_highlighted_text(
99
+ initial_text, tag_id.value, tag_open.value, tag_close.value
100
  ),
101
  interactive=True,
102
+ label="Highlighted Input",
103
+ info="Highlighted textbox using the format above to mark spans that will be highlighted.",
104
  show_legend=True,
105
  show_label=True,
106
  legend_label="Legend:",
 
108
  )
109
  tagged_h2t = gr.Textbox(
110
  initial_text,
111
+ interactive=False,
112
+ label="Tagged Output",
113
+ info="Tagged text intialized from the highlighted textbox.",
114
  show_label=True,
115
  )
116
 
117
  # Functions
118
 
119
+ tagged_t2h.input(
120
  fn=convert_tagged_text_to_highlighted_text,
121
  inputs=[tagged_t2h, tag_id, tag_open, tag_close],
122
  outputs=high_t2h,
123
  )
124
+ high_h2t.input(
 
 
 
 
 
125
  fn=convert_highlighted_text_to_tagged_text,
126
  inputs=[high_h2t, tag_id, tag_open, tag_close],
127
  outputs=tagged_h2t,
128
  )
129
 
130
+ if __name__ == "__main__":
131
+ demo.launch()
132
 
133
  ```
134
 
src/backend/gradio_highlightedtextbox/highlightedtextbox.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  from typing import Any, Callable
4
 
5
  from gradio.components.base import FormComponent
@@ -180,7 +181,7 @@ class HighlightedTextbox(FormComponent):
180
  return [("Hello", None), ("world", "highlight")]
181
 
182
  @classmethod
183
- def tagged_text_to_tuples(
184
  cls, text: str, tag_id: str, tag_open: str = "<h>", tag_close: str = "</h>"
185
  ) -> list[tuple[str, str | None]]:
186
  """Parse a text containing tags into a list of tuples in the format accepted by HighlightedTextbox.
@@ -204,43 +205,108 @@ class HighlightedTextbox(FormComponent):
204
  `list[tuple[str, str | None]]`: List of tuples in the format accepted by HighlightedTextbox.
205
  """
206
  # Check that the text is well-formed (i.e. no nested or empty tags)
207
- num_tags = text.count(tag_open)
208
- if num_tags != text.count(tag_close):
209
- raise ValueError(
210
- f"Number of open tags ({tag_open}) does not match number of closed tags ({tag_close})."
211
- )
212
- elif num_tags == 0:
213
  return [(text, None)]
214
- elif num_tags > 0:
215
  out = []
216
- pre_tag_text = text[: text.index(tag_open)]
217
- if pre_tag_text:
218
- out += [(pre_tag_text.strip(), None)]
 
 
 
 
 
 
 
 
219
 
220
- tag_text = text[
221
- text.index(tag_open) + len(tag_open) : text.index(tag_close)
222
- ]
223
- out += [(tag_text.strip(), tag_id)]
224
- if num_tags > 1:
225
- remaining_text = text[text.index(tag_close) + len(tag_close) :]
226
- out += cls.tagged_text_to_tuples(
227
- remaining_text,
228
- tag_id=tag_id,
229
- tag_open=tag_open,
230
- tag_close=tag_close,
231
- )
232
- else:
233
- post_tag_text = text[text.index(tag_close) + len(tag_close) :]
234
- if post_tag_text:
235
- out += [(post_tag_text, None)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  return out
237
 
238
  @staticmethod
239
  def tuples_to_tagged_text(
240
  tuples: list[tuple[str, str | None]],
241
  tag_ids: str | list[str] = [],
242
- tag_open: str = "<h>",
243
- tag_close: str = "</h>",
244
  ) -> str:
245
  """Convert a list of tuples in the format accepted by HighlightedTextbox into a text containing tags.
246
 
@@ -252,16 +318,27 @@ class HighlightedTextbox(FormComponent):
252
  tag_ids (`str` | `list[str]`):
253
  Label(s) to select for the second element of the tuple. All other labels will be ignored
254
  (i.e. replaced with None)
255
- tag_open (`str`, *optional*, defaults to "<h>"):
256
- Tag used to mark the beginning of a highlighted section.
257
- tag_close (`str`, *optional*, defaults to "</h>"):
258
- Tag used to mark the end of a highlighted section.
259
 
260
  Returns:
261
  `str`: Text containing tags.
262
  """
263
- if isinstance(tag_ids, str):
264
  tag_ids = [tag_ids]
 
 
 
 
 
 
 
 
 
 
 
265
  out = ""
266
  for text, tag_id in tuples:
267
  space_or_not = (
@@ -269,8 +346,9 @@ class HighlightedTextbox(FormComponent):
269
  if text not in [".", "!", "?", ",", ":", ")", "]", ";", "}", """'"""]
270
  else ""
271
  )
272
- if tag_id in tag_ids:
273
- out += f"{space_or_not}{tag_open}{text.strip()}{tag_close}"
 
274
  else:
275
  out += f"{space_or_not}{text.strip()} "
276
- return out.strip()
 
1
  from __future__ import annotations
2
 
3
+ import re
4
  from typing import Any, Callable
5
 
6
  from gradio.components.base import FormComponent
 
181
  return [("Hello", None), ("world", "highlight")]
182
 
183
  @classmethod
184
+ def tagged_text_to_tuples_single_tag(
185
  cls, text: str, tag_id: str, tag_open: str = "<h>", tag_close: str = "</h>"
186
  ) -> list[tuple[str, str | None]]:
187
  """Parse a text containing tags into a list of tuples in the format accepted by HighlightedTextbox.
 
205
  `list[tuple[str, str | None]]`: List of tuples in the format accepted by HighlightedTextbox.
206
  """
207
  # Check that the text is well-formed (i.e. no nested or empty tags)
208
+ num_tags_open = text.count(tag_open)
209
+ num_tags_close = text.count(tag_close)
210
+ if num_tags_open == 0 or num_tags_close == 0:
 
 
 
211
  return [(text, None)]
212
+ else:
213
  out = []
214
+ last_end = 0
215
+ for _ in range(min(num_tags_open, num_tags_close)):
216
+ start = text.index(tag_open, last_end)
217
+ end = text.index(tag_close, start)
218
+ if start > last_end:
219
+ out.append((text[last_end:start].strip(), None))
220
+ out.append((text[start + len(tag_open) : end].strip(), tag_id))
221
+ last_end = end + len(tag_close)
222
+ if last_end < len(text):
223
+ out.append((text[last_end:].strip(), None))
224
+ return out
225
 
226
+ @classmethod
227
+ def tagged_text_to_tuples(
228
+ cls,
229
+ text: str,
230
+ tag_ids: str | list[str],
231
+ tags_open: str | list[str] = "<h>",
232
+ tags_close: str | list[str] = "</h>",
233
+ ) -> list[tuple[str, str | None]]:
234
+ """Parse a text containing tags into a list of tuples in the format accepted by HighlightedTextbox.
235
+
236
+ E.g. Hello <h>world</h>! -> [("Hello", None), ("world", <TAG_ID>), ("!", None)]
237
+
238
+ Args:
239
+ text (`str`):
240
+ Text containing tags that needs to be parsed.
241
+ tag_ids (`str` or `list[str]`):
242
+ Label(s) to use for the second element of the tuple.
243
+ tags_open (`str` or `list[str]`, *optional*, defaults to "<h>"):
244
+ Tag(s) used to mark the beginning of a highlighted section.
245
+ tag_close (`str` or `list[str]`, *optional*, defaults to "</h>"):
246
+ Tag(s) used to mark the end of a highlighted section.
247
+
248
+ Raises:
249
+ ValueError: If the number of tag IDs, open tags and closed tags is not the same.
250
+
251
+ Returns:
252
+ `list[tuple[str, str | None]]`: List of tuples in the format accepted by HighlightedTextbox.
253
+ """
254
+ seen_tag_ids = set()
255
+ seen_tags_open = set()
256
+ seen_tags_close = set()
257
+ if not isinstance(tag_ids, list):
258
+ tag_ids = [tag_ids]
259
+ if not isinstance(tags_open, list):
260
+ tags_open = [tags_open]
261
+ if not isinstance(tags_close, list):
262
+ tags_close = [tags_close]
263
+ # Make sure tags are unique
264
+ tag_ids = [x for x in tag_ids if not (x in seen_tag_ids or seen_tag_ids.add(x))]
265
+ tags_open = [
266
+ x for x in tags_open if not (x in seen_tags_open or seen_tags_open.add(x))
267
+ ]
268
+ tags_close = [
269
+ x
270
+ for x in tags_close
271
+ if not (x in seen_tags_close or seen_tags_close.add(x))
272
+ ]
273
+ if len(tag_ids) != len(tags_open) != len(tags_close):
274
+ raise ValueError(
275
+ "The number of tag IDs, open tags and closed tags must be the same."
276
+ )
277
+ # Create a dictionary mapping tag open/close pairs to their corresponding tag id
278
+ tag_dict = {
279
+ f"{open_tag}(.+?){close_tag}": tag_id
280
+ for tag_id, open_tag, close_tag in zip(tag_ids, tags_open, tags_close)
281
+ }
282
+
283
+ # Create a regular expression that matches any of the tags
284
+ tag_regex = re.compile("|".join(tag_dict.keys()))
285
+
286
+ out = []
287
+ last_end = 0
288
+ for match in tag_regex.finditer(text):
289
+ # Add the text before the tag to the output
290
+ if match.start() > last_end:
291
+ out.append((text[last_end : match.start()].strip(), None))
292
+ # Add the tag to the output
293
+ tag_text = match.group(0)
294
+ for tag, tag_id in tag_dict.items():
295
+ if re.fullmatch(tag, tag_text):
296
+ out.append((re.search(tag, tag_text).group(1), tag_id))
297
+ break
298
+ last_end = match.end()
299
+ # Add the text after the last tag to the output
300
+ if last_end < len(text):
301
+ out.append((text[last_end:].strip(), None))
302
  return out
303
 
304
  @staticmethod
305
  def tuples_to_tagged_text(
306
  tuples: list[tuple[str, str | None]],
307
  tag_ids: str | list[str] = [],
308
+ tags_open: str | list[str] = "<h>",
309
+ tags_close: str | list[str] = "</h>",
310
  ) -> str:
311
  """Convert a list of tuples in the format accepted by HighlightedTextbox into a text containing tags.
312
 
 
318
  tag_ids (`str` | `list[str]`):
319
  Label(s) to select for the second element of the tuple. All other labels will be ignored
320
  (i.e. replaced with None)
321
+ tags_open (`str`, *optional*, defaults to "<h>"):
322
+ Tag(s) used to mark the beginning of a highlighted section.
323
+ tags_close (`str`, *optional*, defaults to "</h>"):
324
+ Tag(s) used to mark the end of a highlighted section.
325
 
326
  Returns:
327
  `str`: Text containing tags.
328
  """
329
+ if not isinstance(tag_ids, list):
330
  tag_ids = [tag_ids]
331
+ if not isinstance(tags_open, list):
332
+ tags_open = [tags_open]
333
+ if not isinstance(tags_close, list):
334
+ tags_close = [tags_close]
335
+ if len(tag_ids) != len(tags_open) != len(tags_close):
336
+ raise ValueError(
337
+ "The number of tag IDs, open tags and closed tags must be the same."
338
+ )
339
+ tuples = [
340
+ (text, tag_id if tag_id in tag_ids else None) for text, tag_id in tuples
341
+ ]
342
  out = ""
343
  for text, tag_id in tuples:
344
  space_or_not = (
 
346
  if text not in [".", "!", "?", ",", ":", ")", "]", ";", "}", """'"""]
347
  else ""
348
  )
349
+ if tag_id is not None:
350
+ tag_id_idx = tag_ids.index(tag_id)
351
+ out += f"{space_or_not}{tags_open[tag_id_idx]}{text.strip()}{tags_close[tag_id_idx]}"
352
  else:
353
  out += f"{space_or_not}{text.strip()} "
354
+ return re.sub(" +", " ", out.strip())
src/backend/gradio_highlightedtextbox/highlightedtextbox.pyi CHANGED
@@ -1,10 +1,16 @@
1
  from __future__ import annotations
2
 
 
3
  from typing import Any, Callable
4
 
5
  from gradio.components.base import FormComponent
 
6
  from gradio.events import Events
7
 
 
 
 
 
8
  from gradio.events import Dependency
9
 
10
  class HighlightedTextbox(FormComponent):
@@ -176,7 +182,7 @@ class HighlightedTextbox(FormComponent):
176
  return [("Hello", None), ("world", "highlight")]
177
 
178
  @classmethod
179
- def tagged_text_to_tuples(
180
  cls, text: str, tag_id: str, tag_open: str = "<h>", tag_close: str = "</h>"
181
  ) -> list[tuple[str, str | None]]:
182
  """Parse a text containing tags into a list of tuples in the format accepted by HighlightedTextbox.
@@ -200,43 +206,108 @@ class HighlightedTextbox(FormComponent):
200
  `list[tuple[str, str | None]]`: List of tuples in the format accepted by HighlightedTextbox.
201
  """
202
  # Check that the text is well-formed (i.e. no nested or empty tags)
203
- num_tags = text.count(tag_open)
204
- if num_tags != text.count(tag_close):
205
- raise ValueError(
206
- f"Number of open tags ({tag_open}) does not match number of closed tags ({tag_close})."
207
- )
208
- elif num_tags == 0:
209
  return [(text, None)]
210
- elif num_tags > 0:
211
  out = []
212
- pre_tag_text = text[: text.index(tag_open)]
213
- if pre_tag_text:
214
- out += [(pre_tag_text.strip(), None)]
 
 
 
 
 
 
 
 
215
 
216
- tag_text = text[
217
- text.index(tag_open) + len(tag_open) : text.index(tag_close)
218
- ]
219
- out += [(tag_text.strip(), tag_id)]
220
- if num_tags > 1:
221
- remaining_text = text[text.index(tag_close) + len(tag_close) :]
222
- out += cls.tagged_text_to_tuples(
223
- remaining_text,
224
- tag_id=tag_id,
225
- tag_open=tag_open,
226
- tag_close=tag_close,
227
- )
228
- else:
229
- post_tag_text = text[text.index(tag_close) + len(tag_close) :]
230
- if post_tag_text:
231
- out += [(post_tag_text, None)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  return out
233
 
234
  @staticmethod
235
  def tuples_to_tagged_text(
236
  tuples: list[tuple[str, str | None]],
237
  tag_ids: str | list[str] = [],
238
- tag_open: str = "<h>",
239
- tag_close: str = "</h>",
240
  ) -> str:
241
  """Convert a list of tuples in the format accepted by HighlightedTextbox into a text containing tags.
242
 
@@ -248,16 +319,27 @@ class HighlightedTextbox(FormComponent):
248
  tag_ids (`str` | `list[str]`):
249
  Label(s) to select for the second element of the tuple. All other labels will be ignored
250
  (i.e. replaced with None)
251
- tag_open (`str`, *optional*, defaults to "<h>"):
252
- Tag used to mark the beginning of a highlighted section.
253
- tag_close (`str`, *optional*, defaults to "</h>"):
254
- Tag used to mark the end of a highlighted section.
255
 
256
  Returns:
257
  `str`: Text containing tags.
258
  """
259
- if isinstance(tag_ids, str):
260
  tag_ids = [tag_ids]
 
 
 
 
 
 
 
 
 
 
 
261
  out = ""
262
  for text, tag_id in tuples:
263
  space_or_not = (
@@ -265,11 +347,12 @@ class HighlightedTextbox(FormComponent):
265
  if text not in [".", "!", "?", ",", ":", ")", "]", ";", "}", """'"""]
266
  else ""
267
  )
268
- if tag_id in tag_ids:
269
- out += f"{space_or_not}{tag_open}{text.strip()}{tag_close}"
 
270
  else:
271
  out += f"{space_or_not}{text.strip()} "
272
- return out.strip()
273
 
274
 
275
  def change(self,
@@ -522,4 +605,4 @@ class HighlightedTextbox(FormComponent):
522
  concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
523
  show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps to use this event. If fn is None, show_api will automatically be set to False.
524
  """
525
- ...
 
1
  from __future__ import annotations
2
 
3
+ import re
4
  from typing import Any, Callable
5
 
6
  from gradio.components.base import FormComponent
7
+ from gradio.data_classes import GradioRootModel
8
  from gradio.events import Events
9
 
10
+
11
+ class HighlightedTextData(GradioRootModel):
12
+ root: list[tuple[str, str | None]]
13
+
14
  from gradio.events import Dependency
15
 
16
  class HighlightedTextbox(FormComponent):
 
182
  return [("Hello", None), ("world", "highlight")]
183
 
184
  @classmethod
185
+ def tagged_text_to_tuples_single_tag(
186
  cls, text: str, tag_id: str, tag_open: str = "<h>", tag_close: str = "</h>"
187
  ) -> list[tuple[str, str | None]]:
188
  """Parse a text containing tags into a list of tuples in the format accepted by HighlightedTextbox.
 
206
  `list[tuple[str, str | None]]`: List of tuples in the format accepted by HighlightedTextbox.
207
  """
208
  # Check that the text is well-formed (i.e. no nested or empty tags)
209
+ num_tags_open = text.count(tag_open)
210
+ num_tags_close = text.count(tag_close)
211
+ if num_tags_open == 0 or num_tags_close == 0:
 
 
 
212
  return [(text, None)]
213
+ else:
214
  out = []
215
+ last_end = 0
216
+ for _ in range(min(num_tags_open, num_tags_close)):
217
+ start = text.index(tag_open, last_end)
218
+ end = text.index(tag_close, start)
219
+ if start > last_end:
220
+ out.append((text[last_end:start].strip(), None))
221
+ out.append((text[start + len(tag_open) : end].strip(), tag_id))
222
+ last_end = end + len(tag_close)
223
+ if last_end < len(text):
224
+ out.append((text[last_end:].strip(), None))
225
+ return out
226
 
227
+ @classmethod
228
+ def tagged_text_to_tuples(
229
+ cls,
230
+ text: str,
231
+ tag_ids: str | list[str],
232
+ tags_open: str | list[str] = "<h>",
233
+ tags_close: str | list[str] = "</h>",
234
+ ) -> list[tuple[str, str | None]]:
235
+ """Parse a text containing tags into a list of tuples in the format accepted by HighlightedTextbox.
236
+
237
+ E.g. Hello <h>world</h>! -> [("Hello", None), ("world", <TAG_ID>), ("!", None)]
238
+
239
+ Args:
240
+ text (`str`):
241
+ Text containing tags that needs to be parsed.
242
+ tag_ids (`str` or `list[str]`):
243
+ Label(s) to use for the second element of the tuple.
244
+ tags_open (`str` or `list[str]`, *optional*, defaults to "<h>"):
245
+ Tag(s) used to mark the beginning of a highlighted section.
246
+ tag_close (`str` or `list[str]`, *optional*, defaults to "</h>"):
247
+ Tag(s) used to mark the end of a highlighted section.
248
+
249
+ Raises:
250
+ ValueError: If the number of tag IDs, open tags and closed tags is not the same.
251
+
252
+ Returns:
253
+ `list[tuple[str, str | None]]`: List of tuples in the format accepted by HighlightedTextbox.
254
+ """
255
+ seen_tag_ids = set()
256
+ seen_tags_open = set()
257
+ seen_tags_close = set()
258
+ if not isinstance(tag_ids, list):
259
+ tag_ids = [tag_ids]
260
+ if not isinstance(tags_open, list):
261
+ tags_open = [tags_open]
262
+ if not isinstance(tags_close, list):
263
+ tags_close = [tags_close]
264
+ # Make sure tags are unique
265
+ tag_ids = [x for x in tag_ids if not (x in seen_tag_ids or seen_tag_ids.add(x))]
266
+ tags_open = [
267
+ x for x in tags_open if not (x in seen_tags_open or seen_tags_open.add(x))
268
+ ]
269
+ tags_close = [
270
+ x
271
+ for x in tags_close
272
+ if not (x in seen_tags_close or seen_tags_close.add(x))
273
+ ]
274
+ if len(tag_ids) != len(tags_open) != len(tags_close):
275
+ raise ValueError(
276
+ "The number of tag IDs, open tags and closed tags must be the same."
277
+ )
278
+ # Create a dictionary mapping tag open/close pairs to their corresponding tag id
279
+ tag_dict = {
280
+ f"{open_tag}(.+?){close_tag}": tag_id
281
+ for tag_id, open_tag, close_tag in zip(tag_ids, tags_open, tags_close)
282
+ }
283
+
284
+ # Create a regular expression that matches any of the tags
285
+ tag_regex = re.compile("|".join(tag_dict.keys()))
286
+
287
+ out = []
288
+ last_end = 0
289
+ for match in tag_regex.finditer(text):
290
+ # Add the text before the tag to the output
291
+ if match.start() > last_end:
292
+ out.append((text[last_end : match.start()].strip(), None))
293
+ # Add the tag to the output
294
+ tag_text = match.group(0)
295
+ for tag, tag_id in tag_dict.items():
296
+ if re.fullmatch(tag, tag_text):
297
+ out.append((re.search(tag, tag_text).group(1), tag_id))
298
+ break
299
+ last_end = match.end()
300
+ # Add the text after the last tag to the output
301
+ if last_end < len(text):
302
+ out.append((text[last_end:].strip(), None))
303
  return out
304
 
305
  @staticmethod
306
  def tuples_to_tagged_text(
307
  tuples: list[tuple[str, str | None]],
308
  tag_ids: str | list[str] = [],
309
+ tags_open: str | list[str] = "<h>",
310
+ tags_close: str | list[str] = "</h>",
311
  ) -> str:
312
  """Convert a list of tuples in the format accepted by HighlightedTextbox into a text containing tags.
313
 
 
319
  tag_ids (`str` | `list[str]`):
320
  Label(s) to select for the second element of the tuple. All other labels will be ignored
321
  (i.e. replaced with None)
322
+ tags_open (`str`, *optional*, defaults to "<h>"):
323
+ Tag(s) used to mark the beginning of a highlighted section.
324
+ tags_close (`str`, *optional*, defaults to "</h>"):
325
+ Tag(s) used to mark the end of a highlighted section.
326
 
327
  Returns:
328
  `str`: Text containing tags.
329
  """
330
+ if not isinstance(tag_ids, list):
331
  tag_ids = [tag_ids]
332
+ if not isinstance(tags_open, list):
333
+ tags_open = [tags_open]
334
+ if not isinstance(tags_close, list):
335
+ tags_close = [tags_close]
336
+ if len(tag_ids) != len(tags_open) != len(tags_close):
337
+ raise ValueError(
338
+ "The number of tag IDs, open tags and closed tags must be the same."
339
+ )
340
+ tuples = [
341
+ (text, tag_id if tag_id in tag_ids else None) for text, tag_id in tuples
342
+ ]
343
  out = ""
344
  for text, tag_id in tuples:
345
  space_or_not = (
 
347
  if text not in [".", "!", "?", ",", ":", ")", "]", ";", "}", """'"""]
348
  else ""
349
  )
350
+ if tag_id is not None:
351
+ tag_id_idx = tag_ids.index(tag_id)
352
+ out += f"{space_or_not}{tags_open[tag_id_idx]}{text.strip()}{tags_close[tag_id_idx]}"
353
  else:
354
  out += f"{space_or_not}{text.strip()} "
355
+ return re.sub(" +", " ", out.strip())
356
 
357
 
358
  def change(self,
 
605
  concurrency_id: If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
606
  show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps to use this event. If fn is None, show_api will automatically be set to False.
607
  """
608
+ ...
src/backend/gradio_highlightedtextbox/templates/component/index.js CHANGED
The diff for this file is too large to render. See raw diff
 
src/backend/gradio_highlightedtextbox/templates/component/style.css CHANGED
@@ -1 +1 @@
1
- .block.svelte-1t38q2d{position:relative;margin:0;box-shadow:var(--block-shadow);border-width:var(--block-border-width);border-color:var(--block-border-color);border-radius:var(--block-radius);background:var(--block-background-fill);width:100%;line-height:var(--line-sm)}.block.border_focus.svelte-1t38q2d{border-color:var(--color-accent)}.padded.svelte-1t38q2d{padding:var(--block-padding)}.hidden.svelte-1t38q2d{display:none}.hide-container.svelte-1t38q2d{margin:0;box-shadow:none;--block-border-width:0;background:transparent;padding:0;overflow:visible}div.svelte-1hnfib2{margin-bottom:var(--spacing-lg);color:var(--block-info-text-color);font-weight:var(--block-info-text-weight);font-size:var(--block-info-text-size);line-height:var(--line-sm)}span.has-info.svelte-22c38v{margin-bottom:var(--spacing-xs)}span.svelte-22c38v:not(.has-info){margin-bottom:var(--spacing-lg)}span.svelte-22c38v{display:inline-block;position:relative;z-index:var(--layer-4);border:solid var(--block-title-border-width) var(--block-title-border-color);border-radius:var(--block-title-radius);background:var(--block-title-background-fill);padding:var(--block-title-padding);color:var(--block-title-text-color);font-weight:var(--block-title-text-weight);font-size:var(--block-title-text-size);line-height:var(--line-sm)}.hide.svelte-22c38v{margin:0;height:0}label.svelte-9gxdi0{display:inline-flex;align-items:center;z-index:var(--layer-2);box-shadow:var(--block-label-shadow);border:var(--block-label-border-width) solid var(--border-color-primary);border-top:none;border-left:none;border-radius:var(--block-label-radius);background:var(--block-label-background-fill);padding:var(--block-label-padding);pointer-events:none;color:var(--block-label-text-color);font-weight:var(--block-label-text-weight);font-size:var(--block-label-text-size);line-height:var(--line-sm)}.gr-group label.svelte-9gxdi0{border-top-left-radius:0}label.float.svelte-9gxdi0{position:absolute;top:var(--block-label-margin);left:var(--block-label-margin)}label.svelte-9gxdi0:not(.float){position:static;margin-top:var(--block-label-margin);margin-left:var(--block-label-margin)}.hide.svelte-9gxdi0{height:0}span.svelte-9gxdi0{opacity:.8;margin-right:var(--size-2);width:calc(var(--block-label-text-size) - 1px);height:calc(var(--block-label-text-size) - 1px)}.hide-label.svelte-9gxdi0{box-shadow:none;border-width:0;background:transparent;overflow:visible}button.svelte-lpi64a{display:flex;justify-content:center;align-items:center;gap:1px;z-index:var(--layer-2);border-radius:var(--radius-sm);color:var(--block-label-text-color);border:1px solid transparent}button[disabled].svelte-lpi64a{opacity:.5;box-shadow:none}button[disabled].svelte-lpi64a:hover{cursor:not-allowed}.padded.svelte-lpi64a{padding:2px;background:var(--bg-color);box-shadow:var(--shadow-drop);border:1px solid var(--button-secondary-border-color)}button.svelte-lpi64a:hover,button.highlight.svelte-lpi64a{cursor:pointer;color:var(--color-accent)}.padded.svelte-lpi64a:hover{border:2px solid var(--button-secondary-border-color-hover);padding:1px;color:var(--block-label-text-color)}span.svelte-lpi64a{padding:0 1px;font-size:10px}div.svelte-lpi64a{padding:2px;display:flex;align-items:flex-end}.small.svelte-lpi64a{width:14px;height:14px}.large.svelte-lpi64a{width:22px;height:22px}.pending.svelte-lpi64a{animation:svelte-lpi64a-flash .5s infinite}@keyframes svelte-lpi64a-flash{0%{opacity:.5}50%{opacity:1}to{opacity:.5}}.transparent.svelte-lpi64a{background:transparent;border:none;box-shadow:none}.empty.svelte-3w3rth{display:flex;justify-content:center;align-items:center;margin-top:calc(0px - var(--size-6));height:var(--size-full)}.icon.svelte-3w3rth{opacity:.5;height:var(--size-5);color:var(--body-text-color)}.small.svelte-3w3rth{min-height:calc(var(--size-32) - 20px)}.large.svelte-3w3rth{min-height:calc(var(--size-64) - 20px)}.unpadded_box.svelte-3w3rth{margin-top:0}.small_parent.svelte-3w3rth{min-height:100%!important}.dropdown-arrow.svelte-145leq6{fill:currentColor}.wrap.svelte-kzcjhc{display:flex;flex-direction:column;justify-content:center;align-items:center;min-height:var(--size-60);color:var(--block-label-text-color);line-height:var(--line-md);height:100%;padding-top:var(--size-3)}.or.svelte-kzcjhc{color:var(--body-text-color-subdued);display:flex}.icon-wrap.svelte-kzcjhc{width:30px;margin-bottom:var(--spacing-lg)}@media (--screen-md){.wrap.svelte-kzcjhc{font-size:var(--text-lg)}}.hovered.svelte-kzcjhc{color:var(--color-accent)}div.svelte-ipfyu7{border-top:1px solid transparent;display:flex;max-height:100%;justify-content:center;gap:var(--spacing-sm);height:auto;align-items:flex-end;padding-bottom:var(--spacing-xl);color:var(--block-label-text-color);flex-shrink:0;width:95%}.show_border.svelte-ipfyu7{border-top:1px solid var(--block-border-color);margin-top:var(--spacing-xxl);box-shadow:var(--shadow-drop)}.source-selection.svelte-1jp3vgd{display:flex;align-items:center;justify-content:center;border-top:1px solid var(--border-color-primary);width:95%;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto}.icon.svelte-1jp3vgd{width:22px;height:22px;margin:var(--spacing-lg) var(--spacing-xs);padding:var(--spacing-xs);color:var(--neutral-400);border-radius:var(--radius-md)}.selected.svelte-1jp3vgd{color:var(--color-accent)}.icon.svelte-1jp3vgd:hover,.icon.svelte-1jp3vgd:focus{color:var(--color-accent)}label.svelte-1u11ied{display:block;width:100%}button.svelte-1u11ied{display:flex;position:absolute;top:var(--block-label-margin);right:var(--block-label-margin);align-items:center;box-shadow:var(--shadow-drop);border:1px solid var(--color-border-primary);border-top:none;border-right:none;border-radius:var(--block-label-right-radius);background:var(--block-label-background-fill);padding:5px;width:22px;height:22px;overflow:hidden;color:var(--block-label-color);font:var(--font-sans);font-size:var(--button-small-text-size)}.container.svelte-1u11ied{display:flex;flex-direction:column;gap:var(--spacing-sm);padding:var(--block-padding)}.category-legend.svelte-1u11ied{display:flex;flex-wrap:wrap;gap:var(--spacing-sm);color:#000;margin-bottom:var(--spacing-sm)}.category-label.svelte-1u11ied{border-radius:var(--radius-xs);padding-right:var(--size-2);padding-left:var(--size-2);font-weight:var(--weight-semibold)}.legend-description.svelte-1u11ied{background-color:transparent;color:var(--block-title-text-color);padding-left:0;border-radius:var(--radius-xs);font-weight:var(--input-text-weight)}.textfield.svelte-1u11ied{box-sizing:border-box;outline:none!important;box-shadow:var(--input-shadow);padding:var(--input-padding);border-radius:var(--radius-md);background:var(--input-background-fill);background-color:transparent;font-weight:var(--input-text-weight);font-size:var(--input-text-size);width:100%;line-height:var(--line-sm);word-break:break-word;border:var(--input-border-width) solid var(--input-border-color);cursor:text}.textfield.svelte-1u11ied:focus{box-shadow:var(--input-shadow-focus);border-color:var(--input-border-color-focus)}mark{border-radius:3px}svg.svelte-43sxxs.svelte-43sxxs{width:var(--size-20);height:var(--size-20)}svg.svelte-43sxxs path.svelte-43sxxs{fill:var(--loader-color)}div.svelte-43sxxs.svelte-43sxxs{z-index:var(--layer-2)}.margin.svelte-43sxxs.svelte-43sxxs{margin:var(--size-4)}.wrap.svelte-1txqlrd.svelte-1txqlrd{display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:var(--layer-top);transition:opacity .1s ease-in-out;border-radius:var(--block-radius);background:var(--block-background-fill);padding:0 var(--size-6);max-height:var(--size-screen-h);overflow:hidden;pointer-events:none}.wrap.center.svelte-1txqlrd.svelte-1txqlrd{top:0;right:0;left:0}.wrap.default.svelte-1txqlrd.svelte-1txqlrd{top:0;right:0;bottom:0;left:0}.hide.svelte-1txqlrd.svelte-1txqlrd{opacity:0;pointer-events:none}.generating.svelte-1txqlrd.svelte-1txqlrd{animation:svelte-1txqlrd-pulse 2s cubic-bezier(.4,0,.6,1) infinite;border:2px solid var(--color-accent);background:transparent}.translucent.svelte-1txqlrd.svelte-1txqlrd{background:none}@keyframes svelte-1txqlrd-pulse{0%,to{opacity:1}50%{opacity:.5}}.loading.svelte-1txqlrd.svelte-1txqlrd{z-index:var(--layer-2);color:var(--body-text-color)}.eta-bar.svelte-1txqlrd.svelte-1txqlrd{position:absolute;top:0;right:0;bottom:0;left:0;transform-origin:left;opacity:.8;z-index:var(--layer-1);transition:10ms;background:var(--background-fill-secondary)}.progress-bar-wrap.svelte-1txqlrd.svelte-1txqlrd{border:1px solid var(--border-color-primary);background:var(--background-fill-primary);width:55.5%;height:var(--size-4)}.progress-bar.svelte-1txqlrd.svelte-1txqlrd{transform-origin:left;background-color:var(--loader-color);width:var(--size-full);height:var(--size-full)}.progress-level.svelte-1txqlrd.svelte-1txqlrd{display:flex;flex-direction:column;align-items:center;gap:1;z-index:var(--layer-2);width:var(--size-full)}.progress-level-inner.svelte-1txqlrd.svelte-1txqlrd{margin:var(--size-2) auto;color:var(--body-text-color);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text.svelte-1txqlrd.svelte-1txqlrd{position:absolute;top:0;right:0;z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text-center.svelte-1txqlrd.svelte-1txqlrd{display:flex;position:absolute;top:0;right:0;justify-content:center;align-items:center;transform:translateY(var(--size-6));z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono);text-align:center}.error.svelte-1txqlrd.svelte-1txqlrd{box-shadow:var(--shadow-drop);border:solid 1px var(--error-border-color);border-radius:var(--radius-full);background:var(--error-background-fill);padding-right:var(--size-4);padding-left:var(--size-4);color:var(--error-text-color);font-weight:var(--weight-semibold);font-size:var(--text-lg);line-height:var(--line-lg);font-family:var(--font)}.minimal.svelte-1txqlrd .progress-text.svelte-1txqlrd{background:var(--block-background-fill)}.border.svelte-1txqlrd.svelte-1txqlrd{border:1px solid var(--border-color-primary)}.toast-body.svelte-solcu7{display:flex;position:relative;right:0;left:0;align-items:center;margin:var(--size-6) var(--size-4);margin:auto;border-radius:var(--container-radius);overflow:hidden;pointer-events:auto}.toast-body.error.svelte-solcu7{border:1px solid var(--color-red-700);background:var(--color-red-50)}.dark .toast-body.error.svelte-solcu7{border:1px solid var(--color-red-500);background-color:var(--color-grey-950)}.toast-body.warning.svelte-solcu7{border:1px solid var(--color-yellow-700);background:var(--color-yellow-50)}.dark .toast-body.warning.svelte-solcu7{border:1px solid var(--color-yellow-500);background-color:var(--color-grey-950)}.toast-body.info.svelte-solcu7{border:1px solid var(--color-grey-700);background:var(--color-grey-50)}.dark .toast-body.info.svelte-solcu7{border:1px solid var(--color-grey-500);background-color:var(--color-grey-950)}.toast-title.svelte-solcu7{display:flex;align-items:center;font-weight:var(--weight-bold);font-size:var(--text-lg);line-height:var(--line-sm);text-transform:capitalize}.toast-title.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-title.error.svelte-solcu7{color:var(--color-red-50)}.toast-title.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-title.warning.svelte-solcu7{color:var(--color-yellow-50)}.toast-title.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-title.info.svelte-solcu7{color:var(--color-grey-50)}.toast-close.svelte-solcu7{margin:0 var(--size-3);border-radius:var(--size-3);padding:0px var(--size-1-5);font-size:var(--size-5);line-height:var(--size-5)}.toast-close.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-close.error.svelte-solcu7{color:var(--color-red-500)}.toast-close.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-close.warning.svelte-solcu7{color:var(--color-yellow-500)}.toast-close.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-close.info.svelte-solcu7{color:var(--color-grey-500)}.toast-text.svelte-solcu7{font-size:var(--text-lg)}.toast-text.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-text.error.svelte-solcu7{color:var(--color-red-50)}.toast-text.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-text.warning.svelte-solcu7{color:var(--color-yellow-50)}.toast-text.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-text.info.svelte-solcu7{color:var(--color-grey-50)}.toast-details.svelte-solcu7{margin:var(--size-3) var(--size-3) var(--size-3) 0;width:100%}.toast-icon.svelte-solcu7{display:flex;position:absolute;position:relative;flex-shrink:0;justify-content:center;align-items:center;margin:var(--size-2);border-radius:var(--radius-full);padding:var(--size-1);padding-left:calc(var(--size-1) - 1px);width:35px;height:35px}.toast-icon.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-icon.error.svelte-solcu7{color:var(--color-red-500)}.toast-icon.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-icon.warning.svelte-solcu7{color:var(--color-yellow-500)}.toast-icon.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-icon.info.svelte-solcu7{color:var(--color-grey-500)}@keyframes svelte-solcu7-countdown{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.timer.svelte-solcu7{position:absolute;bottom:0;left:0;transform-origin:0 0;animation:svelte-solcu7-countdown 10s linear forwards;width:100%;height:var(--size-1)}.timer.error.svelte-solcu7{background:var(--color-red-700)}.dark .timer.error.svelte-solcu7{background:var(--color-red-500)}.timer.warning.svelte-solcu7{background:var(--color-yellow-700)}.dark .timer.warning.svelte-solcu7{background:var(--color-yellow-500)}.timer.info.svelte-solcu7{background:var(--color-grey-700)}.dark .timer.info.svelte-solcu7{background:var(--color-grey-500)}.toast-wrap.svelte-gatr8h{display:flex;position:fixed;top:var(--size-4);right:var(--size-4);flex-direction:column;align-items:end;gap:var(--size-2);z-index:var(--layer-top);width:calc(100% - var(--size-8))}@media (--screen-sm){.toast-wrap.svelte-gatr8h{width:calc(var(--size-96) + var(--size-10))}}
 
1
+ span.has-info.svelte-deja93{margin-bottom:var(--spacing-xs)}span.svelte-deja93:not(.has-info){margin-bottom:var(--spacing-lg)}span.svelte-deja93{display:inline-block;position:relative;z-index:var(--layer-4);border:solid var(--block-title-border-width) var(--block-title-border-color);border-radius:var(--block-title-radius);background:var(--block-title-background-fill);padding:var(--block-title-padding);color:var(--block-title-text-color);font-weight:var(--block-title-text-weight);font-size:var(--block-title-text-size);line-height:var(--line-sm)}.hide.svelte-deja93{margin:0;height:0}.category-legend.svelte-deja93{display:flex;flex-wrap:wrap;gap:var(--spacing-sm);color:#000}.category-label.svelte-deja93{border-radius:var(--radius-xs);padding-right:var(--size-2);padding-left:var(--size-2);font-weight:var(--weight-semibold)}.title-container.svelte-deja93{display:flex}.legend-separator.svelte-deja93{margin:0 var(--spacing-md) 0 var(--spacing-md)}.title-with-highlights-info.svelte-deja93{margin-bottom:var(--spacing-xs);color:var(--block-info-text-color);font-weight:var(--block-info-text-weight);font-size:var(--block-info-text-size);line-height:var(--line-sm)}.dropdown-arrow.svelte-145leq6{fill:currentColor}label.svelte-14ssfqr{display:block;width:100%}button.svelte-14ssfqr{display:flex;position:absolute;top:var(--block-label-margin);right:var(--block-label-margin);align-items:center;box-shadow:var(--shadow-drop);border:1px solid var(--color-border-primary);border-top:none;border-right:none;border-radius:var(--block-label-right-radius);background:var(--block-label-background-fill);padding:5px;width:22px;height:22px;overflow:hidden;color:var(--block-label-color);font:var(--font-sans);font-size:var(--button-small-text-size)}.container.svelte-14ssfqr{display:flex;flex-direction:column;gap:var(--spacing-sm)}.textfield.svelte-14ssfqr{box-sizing:border-box;outline:none!important;box-shadow:var(--input-shadow);padding:var(--input-padding);border-radius:var(--radius-md);background:var(--input-background-fill);background-color:transparent;font-weight:var(--input-text-weight);font-size:var(--input-text-size);width:100%;line-height:var(--line-sm);word-break:break-word;border:var(--input-border-width) solid var(--input-border-color);cursor:text}.textfield.svelte-14ssfqr:focus{box-shadow:var(--input-shadow-focus);border-color:var(--input-border-color-focus)}mark{border-radius:3px}.block.svelte-1t38q2d{position:relative;margin:0;box-shadow:var(--block-shadow);border-width:var(--block-border-width);border-color:var(--block-border-color);border-radius:var(--block-radius);background:var(--block-background-fill);width:100%;line-height:var(--line-sm)}.block.border_focus.svelte-1t38q2d{border-color:var(--color-accent)}.padded.svelte-1t38q2d{padding:var(--block-padding)}.hidden.svelte-1t38q2d{display:none}.hide-container.svelte-1t38q2d{margin:0;box-shadow:none;--block-border-width:0;background:transparent;padding:0;overflow:visible}div.svelte-1hnfib2{margin-bottom:var(--spacing-lg);color:var(--block-info-text-color);font-weight:var(--block-info-text-weight);font-size:var(--block-info-text-size);line-height:var(--line-sm)}span.has-info.svelte-22c38v{margin-bottom:var(--spacing-xs)}span.svelte-22c38v:not(.has-info){margin-bottom:var(--spacing-lg)}span.svelte-22c38v{display:inline-block;position:relative;z-index:var(--layer-4);border:solid var(--block-title-border-width) var(--block-title-border-color);border-radius:var(--block-title-radius);background:var(--block-title-background-fill);padding:var(--block-title-padding);color:var(--block-title-text-color);font-weight:var(--block-title-text-weight);font-size:var(--block-title-text-size);line-height:var(--line-sm)}.hide.svelte-22c38v{margin:0;height:0}label.svelte-9gxdi0{display:inline-flex;align-items:center;z-index:var(--layer-2);box-shadow:var(--block-label-shadow);border:var(--block-label-border-width) solid var(--border-color-primary);border-top:none;border-left:none;border-radius:var(--block-label-radius);background:var(--block-label-background-fill);padding:var(--block-label-padding);pointer-events:none;color:var(--block-label-text-color);font-weight:var(--block-label-text-weight);font-size:var(--block-label-text-size);line-height:var(--line-sm)}.gr-group label.svelte-9gxdi0{border-top-left-radius:0}label.float.svelte-9gxdi0{position:absolute;top:var(--block-label-margin);left:var(--block-label-margin)}label.svelte-9gxdi0:not(.float){position:static;margin-top:var(--block-label-margin);margin-left:var(--block-label-margin)}.hide.svelte-9gxdi0{height:0}span.svelte-9gxdi0{opacity:.8;margin-right:var(--size-2);width:calc(var(--block-label-text-size) - 1px);height:calc(var(--block-label-text-size) - 1px)}.hide-label.svelte-9gxdi0{box-shadow:none;border-width:0;background:transparent;overflow:visible}button.svelte-lpi64a{display:flex;justify-content:center;align-items:center;gap:1px;z-index:var(--layer-2);border-radius:var(--radius-sm);color:var(--block-label-text-color);border:1px solid transparent}button[disabled].svelte-lpi64a{opacity:.5;box-shadow:none}button[disabled].svelte-lpi64a:hover{cursor:not-allowed}.padded.svelte-lpi64a{padding:2px;background:var(--bg-color);box-shadow:var(--shadow-drop);border:1px solid var(--button-secondary-border-color)}button.svelte-lpi64a:hover,button.highlight.svelte-lpi64a{cursor:pointer;color:var(--color-accent)}.padded.svelte-lpi64a:hover{border:2px solid var(--button-secondary-border-color-hover);padding:1px;color:var(--block-label-text-color)}span.svelte-lpi64a{padding:0 1px;font-size:10px}div.svelte-lpi64a{padding:2px;display:flex;align-items:flex-end}.small.svelte-lpi64a{width:14px;height:14px}.large.svelte-lpi64a{width:22px;height:22px}.pending.svelte-lpi64a{animation:svelte-lpi64a-flash .5s infinite}@keyframes svelte-lpi64a-flash{0%{opacity:.5}50%{opacity:1}to{opacity:.5}}.transparent.svelte-lpi64a{background:transparent;border:none;box-shadow:none}.empty.svelte-3w3rth{display:flex;justify-content:center;align-items:center;margin-top:calc(0px - var(--size-6));height:var(--size-full)}.icon.svelte-3w3rth{opacity:.5;height:var(--size-5);color:var(--body-text-color)}.small.svelte-3w3rth{min-height:calc(var(--size-32) - 20px)}.large.svelte-3w3rth{min-height:calc(var(--size-64) - 20px)}.unpadded_box.svelte-3w3rth{margin-top:0}.small_parent.svelte-3w3rth{min-height:100%!important}.wrap.svelte-kzcjhc{display:flex;flex-direction:column;justify-content:center;align-items:center;min-height:var(--size-60);color:var(--block-label-text-color);line-height:var(--line-md);height:100%;padding-top:var(--size-3)}.or.svelte-kzcjhc{color:var(--body-text-color-subdued);display:flex}.icon-wrap.svelte-kzcjhc{width:30px;margin-bottom:var(--spacing-lg)}@media (--screen-md){.wrap.svelte-kzcjhc{font-size:var(--text-lg)}}.hovered.svelte-kzcjhc{color:var(--color-accent)}div.svelte-ipfyu7{border-top:1px solid transparent;display:flex;max-height:100%;justify-content:center;gap:var(--spacing-sm);height:auto;align-items:flex-end;padding-bottom:var(--spacing-xl);color:var(--block-label-text-color);flex-shrink:0;width:95%}.show_border.svelte-ipfyu7{border-top:1px solid var(--block-border-color);margin-top:var(--spacing-xxl);box-shadow:var(--shadow-drop)}.source-selection.svelte-1jp3vgd{display:flex;align-items:center;justify-content:center;border-top:1px solid var(--border-color-primary);width:95%;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto}.icon.svelte-1jp3vgd{width:22px;height:22px;margin:var(--spacing-lg) var(--spacing-xs);padding:var(--spacing-xs);color:var(--neutral-400);border-radius:var(--radius-md)}.selected.svelte-1jp3vgd{color:var(--color-accent)}.icon.svelte-1jp3vgd:hover,.icon.svelte-1jp3vgd:focus{color:var(--color-accent)}svg.svelte-43sxxs.svelte-43sxxs{width:var(--size-20);height:var(--size-20)}svg.svelte-43sxxs path.svelte-43sxxs{fill:var(--loader-color)}div.svelte-43sxxs.svelte-43sxxs{z-index:var(--layer-2)}.margin.svelte-43sxxs.svelte-43sxxs{margin:var(--size-4)}.wrap.svelte-1txqlrd.svelte-1txqlrd{display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:var(--layer-top);transition:opacity .1s ease-in-out;border-radius:var(--block-radius);background:var(--block-background-fill);padding:0 var(--size-6);max-height:var(--size-screen-h);overflow:hidden;pointer-events:none}.wrap.center.svelte-1txqlrd.svelte-1txqlrd{top:0;right:0;left:0}.wrap.default.svelte-1txqlrd.svelte-1txqlrd{top:0;right:0;bottom:0;left:0}.hide.svelte-1txqlrd.svelte-1txqlrd{opacity:0;pointer-events:none}.generating.svelte-1txqlrd.svelte-1txqlrd{animation:svelte-1txqlrd-pulse 2s cubic-bezier(.4,0,.6,1) infinite;border:2px solid var(--color-accent);background:transparent}.translucent.svelte-1txqlrd.svelte-1txqlrd{background:none}@keyframes svelte-1txqlrd-pulse{0%,to{opacity:1}50%{opacity:.5}}.loading.svelte-1txqlrd.svelte-1txqlrd{z-index:var(--layer-2);color:var(--body-text-color)}.eta-bar.svelte-1txqlrd.svelte-1txqlrd{position:absolute;top:0;right:0;bottom:0;left:0;transform-origin:left;opacity:.8;z-index:var(--layer-1);transition:10ms;background:var(--background-fill-secondary)}.progress-bar-wrap.svelte-1txqlrd.svelte-1txqlrd{border:1px solid var(--border-color-primary);background:var(--background-fill-primary);width:55.5%;height:var(--size-4)}.progress-bar.svelte-1txqlrd.svelte-1txqlrd{transform-origin:left;background-color:var(--loader-color);width:var(--size-full);height:var(--size-full)}.progress-level.svelte-1txqlrd.svelte-1txqlrd{display:flex;flex-direction:column;align-items:center;gap:1;z-index:var(--layer-2);width:var(--size-full)}.progress-level-inner.svelte-1txqlrd.svelte-1txqlrd{margin:var(--size-2) auto;color:var(--body-text-color);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text.svelte-1txqlrd.svelte-1txqlrd{position:absolute;top:0;right:0;z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text-center.svelte-1txqlrd.svelte-1txqlrd{display:flex;position:absolute;top:0;right:0;justify-content:center;align-items:center;transform:translateY(var(--size-6));z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono);text-align:center}.error.svelte-1txqlrd.svelte-1txqlrd{box-shadow:var(--shadow-drop);border:solid 1px var(--error-border-color);border-radius:var(--radius-full);background:var(--error-background-fill);padding-right:var(--size-4);padding-left:var(--size-4);color:var(--error-text-color);font-weight:var(--weight-semibold);font-size:var(--text-lg);line-height:var(--line-lg);font-family:var(--font)}.minimal.svelte-1txqlrd .progress-text.svelte-1txqlrd{background:var(--block-background-fill)}.border.svelte-1txqlrd.svelte-1txqlrd{border:1px solid var(--border-color-primary)}.toast-body.svelte-solcu7{display:flex;position:relative;right:0;left:0;align-items:center;margin:var(--size-6) var(--size-4);margin:auto;border-radius:var(--container-radius);overflow:hidden;pointer-events:auto}.toast-body.error.svelte-solcu7{border:1px solid var(--color-red-700);background:var(--color-red-50)}.dark .toast-body.error.svelte-solcu7{border:1px solid var(--color-red-500);background-color:var(--color-grey-950)}.toast-body.warning.svelte-solcu7{border:1px solid var(--color-yellow-700);background:var(--color-yellow-50)}.dark .toast-body.warning.svelte-solcu7{border:1px solid var(--color-yellow-500);background-color:var(--color-grey-950)}.toast-body.info.svelte-solcu7{border:1px solid var(--color-grey-700);background:var(--color-grey-50)}.dark .toast-body.info.svelte-solcu7{border:1px solid var(--color-grey-500);background-color:var(--color-grey-950)}.toast-title.svelte-solcu7{display:flex;align-items:center;font-weight:var(--weight-bold);font-size:var(--text-lg);line-height:var(--line-sm);text-transform:capitalize}.toast-title.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-title.error.svelte-solcu7{color:var(--color-red-50)}.toast-title.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-title.warning.svelte-solcu7{color:var(--color-yellow-50)}.toast-title.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-title.info.svelte-solcu7{color:var(--color-grey-50)}.toast-close.svelte-solcu7{margin:0 var(--size-3);border-radius:var(--size-3);padding:0px var(--size-1-5);font-size:var(--size-5);line-height:var(--size-5)}.toast-close.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-close.error.svelte-solcu7{color:var(--color-red-500)}.toast-close.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-close.warning.svelte-solcu7{color:var(--color-yellow-500)}.toast-close.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-close.info.svelte-solcu7{color:var(--color-grey-500)}.toast-text.svelte-solcu7{font-size:var(--text-lg)}.toast-text.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-text.error.svelte-solcu7{color:var(--color-red-50)}.toast-text.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-text.warning.svelte-solcu7{color:var(--color-yellow-50)}.toast-text.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-text.info.svelte-solcu7{color:var(--color-grey-50)}.toast-details.svelte-solcu7{margin:var(--size-3) var(--size-3) var(--size-3) 0;width:100%}.toast-icon.svelte-solcu7{display:flex;position:absolute;position:relative;flex-shrink:0;justify-content:center;align-items:center;margin:var(--size-2);border-radius:var(--radius-full);padding:var(--size-1);padding-left:calc(var(--size-1) - 1px);width:35px;height:35px}.toast-icon.error.svelte-solcu7{color:var(--color-red-700)}.dark .toast-icon.error.svelte-solcu7{color:var(--color-red-500)}.toast-icon.warning.svelte-solcu7{color:var(--color-yellow-700)}.dark .toast-icon.warning.svelte-solcu7{color:var(--color-yellow-500)}.toast-icon.info.svelte-solcu7{color:var(--color-grey-700)}.dark .toast-icon.info.svelte-solcu7{color:var(--color-grey-500)}@keyframes svelte-solcu7-countdown{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.timer.svelte-solcu7{position:absolute;bottom:0;left:0;transform-origin:0 0;animation:svelte-solcu7-countdown 10s linear forwards;width:100%;height:var(--size-1)}.timer.error.svelte-solcu7{background:var(--color-red-700)}.dark .timer.error.svelte-solcu7{background:var(--color-red-500)}.timer.warning.svelte-solcu7{background:var(--color-yellow-700)}.dark .timer.warning.svelte-solcu7{background:var(--color-yellow-500)}.timer.info.svelte-solcu7{background:var(--color-grey-700)}.dark .timer.info.svelte-solcu7{background:var(--color-grey-500)}.toast-wrap.svelte-gatr8h{display:flex;position:fixed;top:var(--size-4);right:var(--size-4);flex-direction:column;align-items:end;gap:var(--size-2);z-index:var(--layer-top);width:calc(100% - var(--size-8))}@media (--screen-sm){.toast-wrap.svelte-gatr8h{width:calc(var(--size-96) + var(--size-10))}}
src/demo/app.py CHANGED
@@ -3,7 +3,10 @@ from gradio_highlightedtextbox import HighlightedTextbox
3
 
4
 
5
  def convert_tagged_text_to_highlighted_text(
6
- tagged_text: str, tag_id: str, tag_open: str, tag_close: str
 
 
 
7
  ) -> list[tuple[str, str | None]]:
8
  return HighlightedTextbox.tagged_text_to_tuples(
9
  tagged_text, tag_id, tag_open, tag_close
@@ -12,64 +15,77 @@ def convert_tagged_text_to_highlighted_text(
12
 
13
  def convert_highlighted_text_to_tagged_text(
14
  highlighted_text: dict[str, str | list[tuple[str, str | None]]],
15
- tag_id: str,
16
- tag_open: str,
17
- tag_close: str,
18
  ) -> str:
19
  return HighlightedTextbox.tuples_to_tagged_text(
20
  highlighted_text["data"], tag_id, tag_open, tag_close
21
  )
22
 
23
 
24
- initial_text = "It is not something to be ashamed of: it is no different from the <h>personal fears</h> and <h>dislikes</h> of other things that <h>very many people</h> have."
25
 
26
  with gr.Blocks() as demo:
27
- tag_id = gr.Textbox(
28
- "Potential issue",
29
- label="Tag ID",
30
- show_label=True,
31
- info="Insert a tag ID to use in the highlighted textbox.",
32
- )
33
- tag_open = gr.Textbox(
34
- "<h>",
35
- label="Tag open",
36
- show_label=True,
37
- info="Insert a tag to mark the beginning of a highlighted section.",
38
- )
39
- tag_close = gr.Textbox(
40
- "</h>",
41
- label="Tag close",
42
- show_label=True,
43
- info="Insert a tag to mark the end of a highlighted section.",
44
- )
 
 
 
 
 
 
 
 
 
 
 
 
45
  with gr.Row():
46
  tagged_t2h = gr.Textbox(
47
  initial_text,
48
  interactive=True,
49
- label="Input",
50
  show_label=True,
51
- info="Insert a text with <h>...</h> tags to mark spans that will be highlighted.",
52
  )
53
  high_t2h = HighlightedTextbox(
54
  convert_tagged_text_to_highlighted_text(
55
  tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
56
  ),
57
- interactive=True,
58
- label="Output",
59
- info="Highlighted textbox.",
60
  show_legend=True,
61
  show_label=True,
62
  legend_label="Legend:",
63
  show_legend_label=True,
64
  )
 
65
  with gr.Row():
66
  high_h2t = HighlightedTextbox(
67
  convert_tagged_text_to_highlighted_text(
68
- tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
69
  ),
70
  interactive=True,
71
- label="Input",
72
- info="The following text will be marked by spans according to its highlights.",
73
  show_legend=True,
74
  show_label=True,
75
  legend_label="Legend:",
@@ -77,28 +93,24 @@ with gr.Blocks() as demo:
77
  )
78
  tagged_h2t = gr.Textbox(
79
  initial_text,
80
- interactive=True,
81
- label="Output",
 
82
  show_label=True,
83
  )
84
 
85
  # Functions
86
 
87
- tagged_t2h.change(
88
  fn=convert_tagged_text_to_highlighted_text,
89
  inputs=[tagged_t2h, tag_id, tag_open, tag_close],
90
  outputs=high_t2h,
91
  )
92
- high_t2h.change(
93
- fn=lambda x: x["data"],
94
- inputs=high_t2h,
95
- outputs=high_h2t,
96
- )
97
- high_h2t.change(
98
  fn=convert_highlighted_text_to_tagged_text,
99
  inputs=[high_h2t, tag_id, tag_open, tag_close],
100
  outputs=tagged_h2t,
101
  )
102
 
103
-
104
- demo.launch()
 
3
 
4
 
5
  def convert_tagged_text_to_highlighted_text(
6
+ tagged_text: str,
7
+ tag_id: str | list[str],
8
+ tag_open: str | list[str],
9
+ tag_close: str | list[str],
10
  ) -> list[tuple[str, str | None]]:
11
  return HighlightedTextbox.tagged_text_to_tuples(
12
  tagged_text, tag_id, tag_open, tag_close
 
15
 
16
  def convert_highlighted_text_to_tagged_text(
17
  highlighted_text: dict[str, str | list[tuple[str, str | None]]],
18
+ tag_id: str | list[str],
19
+ tag_open: str | list[str],
20
+ tag_close: str | list[str],
21
  ) -> str:
22
  return HighlightedTextbox.tuples_to_tagged_text(
23
  highlighted_text["data"], tag_id, tag_open, tag_close
24
  )
25
 
26
 
27
+ initial_text = "It is not something to be ashamed of: it is no different from the <d>personal fears</d> and <tm>dislikes</tm> of other things that <t>manny peopl</t> have."
28
 
29
  with gr.Blocks() as demo:
30
+ gr.Markdown("### Parameters to control the highlighted textbox:")
31
+ with gr.Row():
32
+ tag_id = gr.Dropdown(
33
+ choices=["Typo", "Terminology", "Disfluency"],
34
+ value=["Typo", "Terminology", "Disfluency"],
35
+ multiselect=True,
36
+ allow_custom_value=True,
37
+ label="Tag ID",
38
+ show_label=True,
39
+ info="Insert one or more tag IDs to use in the highlighted textbox.",
40
+ )
41
+ tag_open = gr.Dropdown(
42
+ choices=["<t>", "<tm>", "<d>"],
43
+ value=["<t>", "<tm>", "<d>"],
44
+ multiselect=True,
45
+ allow_custom_value=True,
46
+ label="Tag open",
47
+ show_label=True,
48
+ info="Insert one or more tags to mark the beginning of a highlighted section.",
49
+ )
50
+ tag_close = gr.Dropdown(
51
+ choices=["</t>", "</tm>", "</d>"],
52
+ value=["</t>", "</tm>", "</d>"],
53
+ multiselect=True,
54
+ allow_custom_value=True,
55
+ label="Tag close",
56
+ show_label=True,
57
+ info="Insert one or more tags to mark the end of a highlighted section.",
58
+ )
59
+ gr.Markdown("### Example tagged to highlight:")
60
  with gr.Row():
61
  tagged_t2h = gr.Textbox(
62
  initial_text,
63
  interactive=True,
64
+ label="Tagged Input",
65
  show_label=True,
66
+ info="Tagged text using the format above to mark spans that will be highlighted.",
67
  )
68
  high_t2h = HighlightedTextbox(
69
  convert_tagged_text_to_highlighted_text(
70
  tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
71
  ),
72
+ interactive=False,
73
+ label="Highlighted Output",
74
+ info="Highlighted textbox intialized from the tagged input.",
75
  show_legend=True,
76
  show_label=True,
77
  legend_label="Legend:",
78
  show_legend_label=True,
79
  )
80
+ gr.Markdown("### Example highlight to tagged:")
81
  with gr.Row():
82
  high_h2t = HighlightedTextbox(
83
  convert_tagged_text_to_highlighted_text(
84
+ initial_text, tag_id.value, tag_open.value, tag_close.value
85
  ),
86
  interactive=True,
87
+ label="Highlighted Input",
88
+ info="Highlighted textbox using the format above to mark spans that will be highlighted.",
89
  show_legend=True,
90
  show_label=True,
91
  legend_label="Legend:",
 
93
  )
94
  tagged_h2t = gr.Textbox(
95
  initial_text,
96
+ interactive=False,
97
+ label="Tagged Output",
98
+ info="Tagged text intialized from the highlighted textbox.",
99
  show_label=True,
100
  )
101
 
102
  # Functions
103
 
104
+ tagged_t2h.input(
105
  fn=convert_tagged_text_to_highlighted_text,
106
  inputs=[tagged_t2h, tag_id, tag_open, tag_close],
107
  outputs=high_t2h,
108
  )
109
+ high_h2t.input(
 
 
 
 
 
110
  fn=convert_highlighted_text_to_tagged_text,
111
  inputs=[high_h2t, tag_id, tag_open, tag_close],
112
  outputs=tagged_h2t,
113
  )
114
 
115
+ if __name__ == "__main__":
116
+ demo.launch()
src/demo/css.css ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ html {
2
+ font-family: Inter;
3
+ font-size: 16px;
4
+ font-weight: 400;
5
+ line-height: 1.5;
6
+ -webkit-text-size-adjust: 100%;
7
+ background: #fff;
8
+ color: #323232;
9
+ -webkit-font-smoothing: antialiased;
10
+ -moz-osx-font-smoothing: grayscale;
11
+ text-rendering: optimizeLegibility;
12
+ }
13
+
14
+ :root {
15
+ --space: 1;
16
+ --vspace: calc(var(--space) * 1rem);
17
+ --vspace-0: calc(3 * var(--space) * 1rem);
18
+ --vspace-1: calc(2 * var(--space) * 1rem);
19
+ --vspace-2: calc(1.5 * var(--space) * 1rem);
20
+ --vspace-3: calc(0.5 * var(--space) * 1rem);
21
+ }
22
+
23
+ .app {
24
+ max-width: 748px !important;
25
+ }
26
+
27
+ .prose p {
28
+ margin: var(--vspace) 0;
29
+ line-height: var(--vspace * 2);
30
+ font-size: 1rem;
31
+ }
32
+
33
+ code {
34
+ font-family: "Inconsolata", sans-serif;
35
+ font-size: 16px;
36
+ }
37
+
38
+ h1,
39
+ h1 code {
40
+ font-weight: 400;
41
+ line-height: calc(2.5 / var(--space) * var(--vspace));
42
+ }
43
+
44
+ h1 code {
45
+ background: none;
46
+ border: none;
47
+ letter-spacing: 0.05em;
48
+ padding-bottom: 5px;
49
+ position: relative;
50
+ padding: 0;
51
+ }
52
+
53
+ h2 {
54
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
55
+ line-height: 1em;
56
+ }
57
+
58
+ h3,
59
+ h3 code {
60
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
61
+ line-height: 1em;
62
+ }
63
+
64
+ h4,
65
+ h5,
66
+ h6 {
67
+ margin: var(--vspace-3) 0 var(--vspace-3) 0;
68
+ line-height: var(--vspace);
69
+ }
70
+
71
+ .bigtitle,
72
+ h1,
73
+ h1 code {
74
+ font-size: calc(8px * 4.5);
75
+ word-break: break-word;
76
+ }
77
+
78
+ .title,
79
+ h2,
80
+ h2 code {
81
+ font-size: calc(8px * 3.375);
82
+ font-weight: lighter;
83
+ word-break: break-word;
84
+ border: none;
85
+ background: none;
86
+ }
87
+
88
+ .subheading1,
89
+ h3,
90
+ h3 code {
91
+ font-size: calc(8px * 1.8);
92
+ font-weight: 600;
93
+ border: none;
94
+ background: none;
95
+ letter-spacing: 0.1em;
96
+ text-transform: uppercase;
97
+ }
98
+
99
+ h2 code {
100
+ padding: 0;
101
+ position: relative;
102
+ letter-spacing: 0.05em;
103
+ }
104
+
105
+ blockquote {
106
+ font-size: calc(8px * 1.1667);
107
+ font-style: italic;
108
+ line-height: calc(1.1667 * var(--vspace));
109
+ margin: var(--vspace-2) var(--vspace-2);
110
+ }
111
+
112
+ .subheading2,
113
+ h4 {
114
+ font-size: calc(8px * 1.4292);
115
+ text-transform: uppercase;
116
+ font-weight: 600;
117
+ }
118
+
119
+ .subheading3,
120
+ h5 {
121
+ font-size: calc(8px * 1.2917);
122
+ line-height: calc(1.2917 * var(--vspace));
123
+
124
+ font-weight: lighter;
125
+ text-transform: uppercase;
126
+ letter-spacing: 0.15em;
127
+ }
128
+
129
+ h6 {
130
+ font-size: calc(8px * 1.1667);
131
+ font-size: 1.1667em;
132
+ font-weight: normal;
133
+ font-style: italic;
134
+ font-family: "le-monde-livre-classic-byol", serif !important;
135
+ letter-spacing: 0px !important;
136
+ }
137
+
138
+ #start .md > *:first-child {
139
+ margin-top: 0;
140
+ }
141
+
142
+ h2 + h3 {
143
+ margin-top: 0;
144
+ }
145
+
146
+ .md hr {
147
+ border: none;
148
+ border-top: 1px solid var(--block-border-color);
149
+ margin: var(--vspace-2) 0 var(--vspace-2) 0;
150
+ }
151
+ .prose ul {
152
+ margin: var(--vspace-2) 0 var(--vspace-1) 0;
153
+ }
154
+
155
+ .gap {
156
+ gap: 0;
157
+ }
src/demo/space.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from app import demo as app
4
+ import os
5
+
6
+ _docs = {'HighlightedTextbox': {'description': 'Creates a textarea for user to enter string input or display string output where some\nelements are highlighted.\n (1) "text" whose value is the complete text, and\n (2) "highlights", which is a list of dictionaries, each of which have the keys:\n "highlight_type" (consisting of the highlight label),\n "start" (the character index where the label starts), and\n "end" (the character index where the label ends).\n Highlights should not overlap.', 'members': {'__init__': {'value': {'type': 'str | Callable | None', 'default': '""', 'description': 'default text to provide in textbox. If callable, the function will be called whenever the app loads to set the initial value of the component.'}, 'color_map': {'type': 'dict[str, str] | None', 'default': 'None', 'description': 'dictionary mapping labels to colors.'}, 'show_legend': {'type': 'bool', 'default': 'False', 'description': 'if True, will display legend.'}, 'show_legend_label': {'type': 'bool', 'default': 'False', 'description': 'if True, will display legend label.'}, 'legend_label': {'type': 'str', 'default': '""', 'description': 'label to display above legend.'}, 'combine_adjacent': {'type': 'bool', 'default': 'False', 'description': 'if True, will combine adjacent spans with the same label.'}, 'adjacent_separator': {'type': 'str', 'default': '""', 'description': 'separator to use when combining adjacent spans.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': 'component name in interface.'}, 'info': {'type': 'str | None', 'default': 'None', 'description': None}, 'every': {'type': 'float | None', 'default': 'None', 'description': "If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute."}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.'}, 'min_width': {'type': 'int', 'default': '160', 'description': 'minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'autofocus': {'type': 'bool', 'default': 'False', 'description': None}, 'autoscroll': {'type': 'bool', 'default': 'True', 'description': 'If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes.'}, 'interactive': {'type': 'bool', 'default': 'True', 'description': 'if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': 'An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'render': {'type': 'bool', 'default': 'True', 'description': 'If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.'}, 'show_copy_button': {'type': 'bool', 'default': 'False', 'description': 'If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True.'}}, 'postprocess': {'y': {'type': 'list[tuple[str, str | None]] | dict | None', 'description': 'List of (word, category) tuples, or a dictionary of two keys: "text", and "highlights", which itself is'}, 'value': {'type': 'list[tuple[str, str | None]] | dict | None', 'description': 'List of (word, category) tuples, or a dictionary of two keys: "text", and "highlights", which itself is'}}, 'preprocess': {'return': {'type': 'dict', 'description': None}, 'value': None}}, 'events': {'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the HighlightedTextbox changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.'}, 'input': {'type': None, 'default': None, 'description': 'This listener is triggered when the user changes the value of the HighlightedTextbox.'}, 'select': {'type': None, 'default': None, 'description': 'Event listener for when the user selects or deselects the HighlightedTextbox. Uses event data gradio.SelectData to carry `value` referring to the label of the HighlightedTextbox, and `selected` to refer to state of the HighlightedTextbox. See EventData documentation on how to use this event data'}, 'submit': {'type': None, 'default': None, 'description': 'This listener is triggered when the user presses the Enter key while the HighlightedTextbox is focused.'}, 'focus': {'type': None, 'default': None, 'description': 'This listener is triggered when the HighlightedTextbox is focused.'}, 'blur': {'type': None, 'default': None, 'description': 'This listener is triggered when the HighlightedTextbox is unfocused/blurred.'}}}, '__meta__': {'additional_interfaces': {}, 'user_fn_refs': {'HighlightedTextbox': []}}}
7
+
8
+ abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
+
10
+ with gr.Blocks(
11
+ css=abs_path,
12
+ theme=gr.themes.Default(
13
+ font_mono=[
14
+ gr.themes.GoogleFont("Inconsolata"),
15
+ "monospace",
16
+ ],
17
+ ),
18
+ ) as demo:
19
+ gr.Markdown(
20
+ """
21
+ # `gradio_highlightedtextbox`
22
+
23
+ <div style="display: flex; gap: 7px;">
24
+ <a href="https://pypi.org/project/gradio_highlightedtextbox/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/gradio_highlightedtextbox"></a> <a href="https://huggingface.co/spaces/gsarti/gradio_highlightedtextbox/discussions" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/%F0%9F%A4%97%20Discuss-%23097EFF?style=flat&logoColor=black"></a>
25
+ </div>
26
+
27
+ Editable Gradio textarea supporting highlighting
28
+ """, elem_classes=["md-custom"], header_links=True)
29
+ app.render()
30
+ gr.Markdown(
31
+ """
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install gradio_highlightedtextbox
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ import gradio as gr
42
+ from gradio_highlightedtextbox import HighlightedTextbox
43
+
44
+
45
+ def convert_tagged_text_to_highlighted_text(
46
+ tagged_text: str,
47
+ tag_id: str | list[str],
48
+ tag_open: str | list[str],
49
+ tag_close: str | list[str],
50
+ ) -> list[tuple[str, str | None]]:
51
+ return HighlightedTextbox.tagged_text_to_tuples(
52
+ tagged_text, tag_id, tag_open, tag_close
53
+ )
54
+
55
+
56
+ def convert_highlighted_text_to_tagged_text(
57
+ highlighted_text: dict[str, str | list[tuple[str, str | None]]],
58
+ tag_id: str | list[str],
59
+ tag_open: str | list[str],
60
+ tag_close: str | list[str],
61
+ ) -> str:
62
+ return HighlightedTextbox.tuples_to_tagged_text(
63
+ highlighted_text["data"], tag_id, tag_open, tag_close
64
+ )
65
+
66
+
67
+ initial_text = "It is not something to be ashamed of: it is no different from the <d>personal fears</d> and <tm>dislikes</tm> of other things that <t>manny peopl</t> have."
68
+
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("### Parameters to control the highlighted textbox:")
71
+ with gr.Row():
72
+ tag_id = gr.Dropdown(
73
+ choices=["Typo", "Terminology", "Disfluency"],
74
+ value=["Typo", "Terminology", "Disfluency"],
75
+ multiselect=True,
76
+ allow_custom_value=True,
77
+ label="Tag ID",
78
+ show_label=True,
79
+ info="Insert one or more tag IDs to use in the highlighted textbox.",
80
+ )
81
+ tag_open = gr.Dropdown(
82
+ choices=["<t>", "<tm>", "<d>"],
83
+ value=["<t>", "<tm>", "<d>"],
84
+ multiselect=True,
85
+ allow_custom_value=True,
86
+ label="Tag open",
87
+ show_label=True,
88
+ info="Insert one or more tags to mark the beginning of a highlighted section.",
89
+ )
90
+ tag_close = gr.Dropdown(
91
+ choices=["</t>", "</tm>", "</d>"],
92
+ value=["</t>", "</tm>", "</d>"],
93
+ multiselect=True,
94
+ allow_custom_value=True,
95
+ label="Tag close",
96
+ show_label=True,
97
+ info="Insert one or more tags to mark the end of a highlighted section.",
98
+ )
99
+ gr.Markdown("### Example tagged to highlight:")
100
+ with gr.Row():
101
+ tagged_t2h = gr.Textbox(
102
+ initial_text,
103
+ interactive=True,
104
+ label="Tagged Input",
105
+ show_label=True,
106
+ info="Tagged text using the format above to mark spans that will be highlighted.",
107
+ )
108
+ high_t2h = HighlightedTextbox(
109
+ convert_tagged_text_to_highlighted_text(
110
+ tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
111
+ ),
112
+ interactive=False,
113
+ label="Highlighted Output",
114
+ info="Highlighted textbox intialized from the tagged input.",
115
+ show_legend=True,
116
+ show_label=True,
117
+ legend_label="Legend:",
118
+ show_legend_label=True,
119
+ )
120
+ gr.Markdown("### Example highlight to tagged:")
121
+ with gr.Row():
122
+ high_h2t = HighlightedTextbox(
123
+ convert_tagged_text_to_highlighted_text(
124
+ initial_text, tag_id.value, tag_open.value, tag_close.value
125
+ ),
126
+ interactive=True,
127
+ label="Highlighted Input",
128
+ info="Highlighted textbox using the format above to mark spans that will be highlighted.",
129
+ show_legend=True,
130
+ show_label=True,
131
+ legend_label="Legend:",
132
+ show_legend_label=True,
133
+ )
134
+ tagged_h2t = gr.Textbox(
135
+ initial_text,
136
+ interactive=False,
137
+ label="Tagged Output",
138
+ info="Tagged text intialized from the highlighted textbox.",
139
+ show_label=True,
140
+ )
141
+
142
+ # Functions
143
+
144
+ tagged_t2h.input(
145
+ fn=convert_tagged_text_to_highlighted_text,
146
+ inputs=[tagged_t2h, tag_id, tag_open, tag_close],
147
+ outputs=high_t2h,
148
+ )
149
+ high_h2t.input(
150
+ fn=convert_highlighted_text_to_tagged_text,
151
+ inputs=[high_h2t, tag_id, tag_open, tag_close],
152
+ outputs=tagged_h2t,
153
+ )
154
+
155
+ if __name__ == "__main__":
156
+ demo.launch()
157
+
158
+ ```
159
+ """, elem_classes=["md-custom"], header_links=True)
160
+
161
+
162
+ gr.Markdown("""
163
+ ## `HighlightedTextbox`
164
+
165
+ ### Initialization
166
+ """, elem_classes=["md-custom"], header_links=True)
167
+
168
+ gr.ParamViewer(value=_docs["HighlightedTextbox"]["members"]["__init__"], linkify=[])
169
+
170
+
171
+ gr.Markdown("### Events")
172
+ gr.ParamViewer(value=_docs["HighlightedTextbox"]["events"], linkify=['Event'])
173
+
174
+
175
+
176
+
177
+ gr.Markdown("""
178
+
179
+ ### User function
180
+
181
+ The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).
182
+
183
+ - When used as an Input, the component only impacts the input signature of the user function.
184
+ - When used as an output, the component only impacts the return signature of the user function.
185
+
186
+ The code snippet below is accurate in cases where the component is used as both an input and an output.
187
+
188
+ - **As output:** Should return, list of (word, category) tuples, or a dictionary of two keys: "text", and "highlights", which itself is.
189
+
190
+ ```python
191
+ def predict(
192
+ value: dict
193
+ ) -> list[tuple[str, str | None]] | dict | None:
194
+ return value
195
+ ```
196
+ """, elem_classes=["md-custom", "HighlightedTextbox-user-fn"], header_links=True)
197
+
198
+
199
+
200
+
201
+ demo.load(None, js=r"""function() {
202
+ const refs = {};
203
+ const user_fn_refs = {
204
+ HighlightedTextbox: [], };
205
+ requestAnimationFrame(() => {
206
+
207
+ Object.entries(user_fn_refs).forEach(([key, refs]) => {
208
+ if (refs.length > 0) {
209
+ const el = document.querySelector(`.${key}-user-fn`);
210
+ if (!el) return;
211
+ refs.forEach(ref => {
212
+ el.innerHTML = el.innerHTML.replace(
213
+ new RegExp("\\b"+ref+"\\b", "g"),
214
+ `<a href="#h-${ref.toLowerCase()}">${ref}</a>`
215
+ );
216
+ })
217
+ }
218
+ })
219
+
220
+ Object.entries(refs).forEach(([key, refs]) => {
221
+ if (refs.length > 0) {
222
+ const el = document.querySelector(`.${key}`);
223
+ if (!el) return;
224
+ refs.forEach(ref => {
225
+ el.innerHTML = el.innerHTML.replace(
226
+ new RegExp("\\b"+ref+"\\b", "g"),
227
+ `<a href="#h-${ref.toLowerCase()}">${ref}</a>`
228
+ );
229
+ })
230
+ }
231
+ })
232
+ })
233
+ }
234
+
235
+ """)
236
+
237
+ demo.launch()
src/frontend/BlockTitleWithHighlights.svelte ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let show_label = true;
3
+ export let show_legend = true;
4
+ export let show_legend_label = true;
5
+ export let legend_label: string | undefined = "Highlights:";
6
+ export let _color_map: Record<string, { primary: string; secondary: string }> = {};
7
+ export let info: string | undefined = undefined;
8
+ </script>
9
+
10
+ <div class="title-container">
11
+ <span
12
+ class:sr-only={!show_label}
13
+ class:hide={!show_label}
14
+ class:has-info={info != null}
15
+ data-testid="block-info"
16
+ >
17
+ <slot />
18
+ </span>
19
+ {#if Object.keys(_color_map).length !== 0}
20
+ <span
21
+ class="legend-separator"
22
+ class:hide={!show_legend}
23
+ class:has-info={info != null}
24
+ >
25
+ ·
26
+ </span>
27
+ <div
28
+ class="category-legend"
29
+ data-testid="highlighted-text:category-legend"
30
+ class:hide={!show_legend}
31
+ >
32
+ <span class:hide={!show_legend_label} class:has-info={info != null}>
33
+ {legend_label}
34
+ </span>
35
+ {#each Object.entries(_color_map) as [category, color], i}
36
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
37
+ <div class="category-label" style={"background-color:" + color.secondary}>
38
+ {category}
39
+ </div>
40
+ {/each}
41
+ </div>
42
+ {/if}
43
+ </div>
44
+ {#if info}
45
+ <div class="title-with-highlights-info">
46
+ {info}
47
+ </div>
48
+ {/if}
49
+
50
+ <style>
51
+ span.has-info {
52
+ margin-bottom: var(--spacing-xs);
53
+ }
54
+ span:not(.has-info) {
55
+ margin-bottom: var(--spacing-lg);
56
+ }
57
+ span {
58
+ display: inline-block;
59
+ position: relative;
60
+ z-index: var(--layer-4);
61
+ border: solid var(--block-title-border-width)
62
+ var(--block-title-border-color);
63
+ border-radius: var(--block-title-radius);
64
+ background: var(--block-title-background-fill);
65
+ padding: var(--block-title-padding);
66
+ color: var(--block-title-text-color);
67
+ font-weight: var(--block-title-text-weight);
68
+ font-size: var(--block-title-text-size);
69
+ line-height: var(--line-sm);
70
+ }
71
+
72
+ .hide {
73
+ margin: 0;
74
+ height: 0;
75
+ }
76
+
77
+ .category-legend {
78
+ display: flex;
79
+ flex-wrap: wrap;
80
+ gap: var(--spacing-sm);
81
+ color: black;
82
+ }
83
+
84
+ .category-label {
85
+ border-radius: var(--radius-xs);
86
+ padding-right: var(--size-2);
87
+ padding-left: var(--size-2);
88
+ font-weight: var(--weight-semibold);
89
+ }
90
+
91
+ .title-container {
92
+ display: flex;
93
+ }
94
+
95
+ .legend-separator {
96
+ margin: 0 var(--spacing-md) 0 var(--spacing-md);
97
+ }
98
+
99
+ .title-with-highlights-info {
100
+ margin-bottom: var(--spacing-xs);
101
+ color: var(--block-info-text-color);
102
+ font-weight: var(--block-info-text-weight);
103
+ font-size: var(--block-info-text-size);
104
+ line-height: var(--line-sm);
105
+ }
106
+ </style>
src/frontend/HighlightedTextbox.svelte CHANGED
@@ -4,7 +4,7 @@
4
  afterUpdate,
5
  createEventDispatcher,
6
  } from "svelte";
7
- import { BlockTitle } from "@gradio/atoms";
8
  import { Copy, Check } from "@gradio/icons";
9
  import { fade } from "svelte/transition";
10
  import type { SelectData } from "@gradio/utils";
@@ -29,18 +29,18 @@
29
  let el_text: string = "";
30
  let marked_el_text: string = "";
31
  let ctx: CanvasRenderingContext2D;
32
- let current_color_map: Record<string, string> = {};
33
  let _color_map: Record<string, { primary: string; secondary: string }> = {};
34
  let copied = false;
35
  let timer: ReturnType<typeof setTimeout>;
36
  let can_scroll: boolean;
37
 
38
  function set_color_map(): void {
39
- if (!color_map || Object.keys(color_map).length === 0) {
40
- current_color_map = {};
41
- }
42
- else {
43
- current_color_map = color_map;
44
  }
45
  if (value.length > 0) {
46
  for (let [_, label] of value) {
@@ -54,6 +54,8 @@
54
  }
55
 
56
  function set_text_from_value(as_output: boolean): void {
 
 
57
  if (value.length > 0 && as_output) {
58
  el_text = value.map(([text, _]) => text).join(" ");
59
  marked_el_text = value.map(([text, category]) => {
@@ -71,10 +73,10 @@
71
 
72
  const dispatch = createEventDispatcher<{
73
  change: string;
 
74
  submit: undefined;
75
  blur: undefined;
76
  select: SelectData;
77
- input: string;
78
  focus: undefined;
79
  }>();
80
 
@@ -96,10 +98,7 @@
96
  });
97
  $: marked_el_text, handle_change();
98
 
99
- // Given a string like Hello <mark class="hl red" style="background-color:#fee2e2">world!</mark> This is cool.
100
- // for marked_el_text and its previous parsed version (value) like [["Hello ", null], ["world!", "red"], [" This is ", null], ["nice", "blue"]],
101
- // update value such that it matches marked_el_text (i.e. [["Hello ", null], ["world!", "red"], [" This is cool.", null]])
102
- function handle_blur(): void {
103
  let new_value: [string, string | null][] = [];
104
  let text = "";
105
  let category = null;
@@ -169,32 +168,17 @@
169
  range.setEnd(nodeAndOffset.node, nodeAndOffset.offset);
170
  newSelection.removeAllRanges();
171
  newSelection.addRange(range);
172
- handle_blur();
173
  }
174
  }
 
 
175
  }
176
  </script>
177
 
178
  <!-- svelte-ignore a11y-no-static-element-interactions -->
179
  <!-- svelte-ignore a11y-click-events-have-key-events-->
180
  <label class:container>
181
- {#if show_legend}
182
- <div
183
- class="category-legend"
184
- data-testid="highlighted-text:category-legend"
185
- >
186
- {#if show_legend_label}
187
- <div class="legend-description">{legend_label}</div>
188
- {/if}
189
- {#each Object.entries(_color_map) as [category, color], i}
190
- <!-- svelte-ignore a11y-no-static-element-interactions -->
191
- <div class="category-label" style={"background-color:" + color.secondary}>
192
- {category}
193
- </div>
194
- {/each}
195
- </div>
196
- {/if}
197
- <BlockTitle {show_label} {info}>{label}</BlockTitle>
198
  {#if show_copy_button}
199
  {#if copied}
200
  <button
@@ -228,7 +212,7 @@
228
  bind:this={el}
229
  bind:textContent={el_text}
230
  bind:innerHTML={marked_el_text}
231
- on:blur={handle_blur}
232
  on:keypress
233
  on:select
234
  on:scroll
@@ -269,30 +253,6 @@
269
  display: flex;
270
  flex-direction: column;
271
  gap: var(--spacing-sm);
272
- padding: var(--block-padding);
273
- }
274
-
275
- .category-legend {
276
- display: flex;
277
- flex-wrap: wrap;
278
- gap: var(--spacing-sm);
279
- color: black;
280
- margin-bottom: var(--spacing-sm)
281
- }
282
-
283
- .category-label {
284
- border-radius: var(--radius-xs);
285
- padding-right: var(--size-2);
286
- padding-left: var(--size-2);
287
- font-weight: var(--weight-semibold);
288
- }
289
-
290
- .legend-description {
291
- background-color: transparent;
292
- color: var(--block-title-text-color);
293
- padding-left: 0px;
294
- border-radius: var(--radius-xs);
295
- font-weight: var(--input-text-weight);
296
  }
297
 
298
  .textfield {
 
4
  afterUpdate,
5
  createEventDispatcher,
6
  } from "svelte";
7
+ import BlockTitleWithHighlights from "./BlockTitleWithHighlights.svelte";
8
  import { Copy, Check } from "@gradio/icons";
9
  import { fade } from "svelte/transition";
10
  import type { SelectData } from "@gradio/utils";
 
29
  let el_text: string = "";
30
  let marked_el_text: string = "";
31
  let ctx: CanvasRenderingContext2D;
32
+ let current_color_map: Record<string, string> = !color_map || Object.keys(color_map).length === 0 ? {} : color_map;
33
  let _color_map: Record<string, { primary: string; secondary: string }> = {};
34
  let copied = false;
35
  let timer: ReturnType<typeof setTimeout>;
36
  let can_scroll: boolean;
37
 
38
  function set_color_map(): void {
39
+ // if a label in the color map is not in the value, remove it from the color map
40
+ for (let label in current_color_map) {
41
+ if (!value.map(([_, label]) => label).includes(label)) {
42
+ delete current_color_map[label];
43
+ }
44
  }
45
  if (value.length > 0) {
46
  for (let [_, label] of value) {
 
54
  }
55
 
56
  function set_text_from_value(as_output: boolean): void {
57
+ console.log(value)
58
+ console.log(_color_map)
59
  if (value.length > 0 && as_output) {
60
  el_text = value.map(([text, _]) => text).join(" ");
61
  marked_el_text = value.map(([text, category]) => {
 
73
 
74
  const dispatch = createEventDispatcher<{
75
  change: string;
76
+ input: string;
77
  submit: undefined;
78
  blur: undefined;
79
  select: SelectData;
 
80
  focus: undefined;
81
  }>();
82
 
 
98
  });
99
  $: marked_el_text, handle_change();
100
 
101
+ function set_value_from_marked_span(): void {
 
 
 
102
  let new_value: [string, string | null][] = [];
103
  let text = "";
104
  let category = null;
 
168
  range.setEnd(nodeAndOffset.node, nodeAndOffset.offset);
169
  newSelection.removeAllRanges();
170
  newSelection.addRange(range);
 
171
  }
172
  }
173
+ set_value_from_marked_span();
174
+ dispatch("change", marked_el_text);
175
  }
176
  </script>
177
 
178
  <!-- svelte-ignore a11y-no-static-element-interactions -->
179
  <!-- svelte-ignore a11y-click-events-have-key-events-->
180
  <label class:container>
181
+ <BlockTitleWithHighlights {show_label} {info} {show_legend} {show_legend_label} {legend_label} {_color_map}>{label}</BlockTitleWithHighlights>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  {#if show_copy_button}
183
  {#if copied}
184
  <button
 
212
  bind:this={el}
213
  bind:textContent={el_text}
214
  bind:innerHTML={marked_el_text}
215
+ on:blur
216
  on:keypress
217
  on:select
218
  on:scroll
 
253
  display: flex;
254
  flex-direction: column;
255
  gap: var(--spacing-sm);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  }
257
 
258
  .textfield {
src/frontend/utils.ts CHANGED
@@ -107,4 +107,11 @@ export function getNodeAndOffset(root, index) {
107
  }
108
  var offset = node.textContent.length - (runningTotal - index);
109
  return { node: node, offset: offset };
110
- }
 
 
 
 
 
 
 
 
107
  }
108
  var offset = node.textContent.length - (runningTotal - index);
109
  return { node: node, offset: offset };
110
+ }
111
+
112
+
113
+ export function escapeHtml(unsafe: string): string {
114
+ return unsafe
115
+ .replace(/</g, "&lt;")
116
+ .replace(/>/g, "&gt;")
117
+ }
src/pyproject.toml CHANGED
@@ -8,7 +8,7 @@ build-backend = "hatchling.build"
8
 
9
  [project]
10
  name = "gradio_highlightedtextbox"
11
- version = "0.0.5"
12
  description = "Editable Gradio textarea supporting highlighting"
13
  readme = "README.md"
14
  license = "mit"
@@ -39,7 +39,7 @@ dev = ["build", "twine"]
39
  space = "https://huggingface.co/spaces/gsarti/gradio_highlightedtextbox"
40
 
41
  [tool.hatch.build]
42
- artifacts = ["/backend/gradio_highlightedtextbox/templates", "*.pyi", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "Users/gsarti/Documents/projects/highlightedtextbox/backend/gradio_highlightedtextbox/templates", "Users/gsarti/Documents/projects/highlightedtextbox/backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates"]
43
 
44
  [tool.hatch.build.targets.wheel]
45
  packages = ["/backend/gradio_highlightedtextbox"]
 
8
 
9
  [project]
10
  name = "gradio_highlightedtextbox"
11
+ version = "0.0.6"
12
  description = "Editable Gradio textarea supporting highlighting"
13
  readme = "README.md"
14
  license = "mit"
 
39
  space = "https://huggingface.co/spaces/gsarti/gradio_highlightedtextbox"
40
 
41
  [tool.hatch.build]
42
+ artifacts = ["/backend/gradio_highlightedtextbox/templates", "*.pyi", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "Users/gsarti/Documents/projects/highlightedtextbox/backend/gradio_highlightedtextbox/templates", "Users/gsarti/Documents/projects/highlightedtextbox/backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates", "backend/gradio_highlightedtextbox/templates"]
43
 
44
  [tool.hatch.build.targets.wheel]
45
  packages = ["/backend/gradio_highlightedtextbox"]