TheHickman commited on
Commit
87c662d
·
verified ·
1 Parent(s): 7773cb2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -146
app.py CHANGED
@@ -6,198 +6,199 @@ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
6
 
7
  # ---- GPT explanation backend ----
8
  def explain_text(selected_text):
9
- if not selected_text or not selected_text.strip():
10
- return "__NO_SELECTION__"
 
 
 
 
11
  try:
12
- response = client.responses.create(
13
- model="gpt-4.1-mini",
14
- input=[
15
- {"role": "system", "content": "You are an expert ML instructor. Explain clearly for beginners."},
16
- {"role": "user", "content": f'Explain this text:\n"""{selected_text}"""'}
17
  ],
18
- max_output_tokens=400
 
19
  )
20
- return response.output_text
21
  except Exception as e:
22
- return f"__ERROR__: {str(e)}"
23
 
24
-
25
- # ---- Page content ----
26
  YOUR_WORK_HTML = """
27
- <div id="content" style="max-width: 800px; margin: auto; font-size: 16px; line-height: 1.8;">
28
  <h1>Text Generation</h1>
29
  <p>
30
- Text generation is the task of producing natural language text given an input prompt.
31
  It is commonly used for chatbots, creative writing, summarization, and code generation.
32
  </p>
33
  <p>
34
- Most modern text generation models are based on the transformer architecture and are
35
  trained using next-token prediction.
36
  </p>
37
  <p>
38
- During inference, the model repeatedly samples the most likely next token until a
39
  stopping condition is reached.
40
  </p>
41
  </div>
42
  """
43
 
 
44
  HF_REFERENCE_HTML = """
45
- <div id="hf-content" style="max-width: 800px; margin: auto; font-size: 16px; line-height: 1.8;">
46
  <h1>Text Generation (Hugging Face Reference)</h1>
47
- <h2>About Text Generation</h2>
48
  <p>
49
- This task covers guides on both text-generation and text-to-text generation models.
50
- Popular large language models that are used for chats or following instructions are also covered in this task.
51
- You can find the list of selected open-source large language models on the Open LLM Leaderboard, ranked by their performance scores.
52
  </p>
 
53
  <h2>Use Cases</h2>
 
54
  <h3>Instruction Models</h3>
55
  <p>
56
- A model trained for text generation can be later adapted to follow instructions.
57
- You can try some of the most powerful instruction-tuned open-access models like Mixtral 8x7B, Cohere Command R+, and Meta Llama3 70B at Hugging Chat.
58
  </p>
 
59
  <h3>Code Generation</h3>
60
  <p>
61
- A Text Generation model, also known as a causal language model, can be trained on code from scratch to help programmers with repetitive coding tasks.
62
- One of the most popular open-source models for code generation is StarCoder, which can generate code in 80+ languages.
63
  </p>
 
64
  <h3>Stories Generation</h3>
65
  <p>
66
- A story generation model can receive an input like "Once upon a time" and proceed to create a story-like text.
67
- If your generative model training data differs from your use case, you can train a causal language model from scratch.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  </div>
70
  """
71
 
72
  def switch_content(choice):
73
- return YOUR_WORK_HTML if choice == "My Work" else HF_REFERENCE_HTML
 
 
 
74
 
75
-
76
- # ---- Floating FAB + tooltip JS ----
77
- HEAD_HTML = """
78
- <style>
79
- #explain-fab {
80
- position: fixed;
81
- bottom: 36px;
82
- right: 36px;
83
- z-index: 99999;
84
- padding: 12px 22px;
85
- border-radius: 999px;
86
- background: #1e1b4b;
87
- color: #fff;
88
- font-weight: 600;
89
- cursor: pointer;
90
- border: none;
91
- opacity: 0;
92
- transform: translateY(12px);
93
- transition: opacity 0.2s ease, transform 0.2s ease, background 0.15s;
94
- }
95
- #explain-fab:hover:not(:disabled){background:#3730a3;}
96
- </style>
97
  <script>
98
- (function(){
99
- let selectedText="", savedRange=null, popup=null;
100
-
101
- function buildFAB() {
102
- if(document.getElementById("explain-fab")) return;
103
- const btn=document.createElement("button");
104
- btn.id="explain-fab"; btn.textContent="Explain 🧠";
105
- document.body.appendChild(btn);
106
- btn.addEventListener("click", onExplainClick);
107
- }
108
-
109
- function showFAB(text) {
110
- const fab=document.getElementById("explain-fab");
111
- if(!fab) return;
112
- fab.style.opacity="1"; fab.disabled=false;
113
- fab.dataset.text=text;
114
- }
115
-
116
- function hideFAB() { const fab=document.getElementById("explain-fab"); if(fab) fab.style.opacity="0"; }
117
-
118
- document.addEventListener("mouseup", e=>{
119
- const sel=window.getSelection();
120
- if(!sel || sel.rangeCount===0) return hideFAB();
121
- const text=sel.toString().trim();
122
- if(text.length<3) return hideFAB();
123
- selectedText=text;
124
- savedRange=sel.getRangeAt(0).cloneRange();
125
- showFAB(text);
126
- });
127
-
128
- async function onExplainClick() {
129
- if(!selectedText) return;
130
- // call hidden Gradio button with input
131
- const hiddenBtn=gradioApp().getElement("hidden-btn");
132
- if(hiddenBtn){
133
- hiddenBtn.querySelector("button").click(); // triggers backend
134
- // assign the selected text to hidden textbox
135
- const ta=hiddenBtn.querySelector("textarea");
136
- if(ta){ ta.value=selectedText; ta.dispatchEvent(new Event('input',{bubbles:true})); }
137
- // wait for response
138
- const output=await new Promise(resolve=>{
139
- const obs=new MutationObserver(m=>{
140
- const outTa=document.querySelector("#hidden-output textarea");
141
- if(outTa && outTa.value.trim()!==""){
142
- obs.disconnect();
143
- resolve(outTa.value.trim());
144
- }
145
- });
146
- obs.observe(document.querySelector("#hidden-output"),{subtree:true,childList:true});
147
- });
148
- showPopup(output);
149
- }
150
- selectedText=""; savedRange=null; hideFAB();
151
- }
152
-
153
- function showPopup(text){
154
- if(popup) popup.remove();
155
- popup=document.createElement("div");
156
- popup.style.position="absolute";
157
- popup.style.background="#fef3c7";
158
- popup.style.border="1px solid #f59e0b";
159
- popup.style.padding="10px";
160
- popup.style.borderRadius="6px";
161
- popup.style.maxWidth="300px";
162
- popup.style.zIndex=99999;
163
- popup.style.fontSize="14px";
164
- popup.style.lineHeight="1.5";
165
- popup.style.color="#1c1917";
166
- popup.textContent=text;
167
- document.body.appendChild(popup);
168
- if(savedRange){
169
- const rect=savedRange.getBoundingClientRect();
170
- popup.style.top=`${window.scrollY+rect.bottom+8}px`;
171
- popup.style.left=`${window.scrollX+rect.left}px`;
172
  }
173
- setTimeout(()=>{ if(popup) popup.remove(); popup=null; },20000);
174
- }
175
-
176
- document.addEventListener("DOMContentLoaded", buildFAB);
177
- })();
178
  </script>
179
- """
180
-
181
-
182
- with gr.Blocks(head=HEAD_HTML) as demo:
183
- gr.Markdown(
184
- "### 📘 Highlight any text — a floating **Explain 🧠** button will appear. "
185
- "Click it to show an AI explanation in a popup near your selection."
186
- )
187
-
188
  view_toggle = gr.Radio(
189
  choices=["My Work", "HF Reference"],
190
  value="My Work",
191
  label="View",
 
192
  )
 
193
  content_display = gr.HTML(YOUR_WORK_HTML)
194
- view_toggle.change(fn=switch_content, inputs=view_toggle, outputs=content_display)
195
-
196
- # Hidden plumbing
197
- hidden_row = gr.Row(visible=False)
198
- hidden_input = gr.Textbox(label="hidden-input", visible=False)
199
- hidden_output = gr.Textbox(label="hidden-output", visible=False, elem_id="hidden-output")
200
- hidden_btn = gr.Button("hidden-btn", elem_id="hidden-btn", visible=False)
201
- hidden_btn.click(fn=explain_text, inputs=hidden_input, outputs=hidden_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
  demo.launch()
 
6
 
7
  # ---- GPT explanation backend ----
8
  def explain_text(selected_text):
9
+ if selected_text is None:
10
+ return ""
11
+ selected_text = selected_text.strip()
12
+ if not selected_text:
13
+ return "Please select or enter some text first."
14
+
15
  try:
16
+ response = client.chat.completions.create(
17
+ model="gpt-4o",
18
+ messages=[
19
+ {"role": "system", "content": "You are an expert machine learning instructor. Explain concepts clearly and intuitively for learners with basic ML knowledge. Keep explanations concise and educational."},
20
+ {"role": "user", "content": f"Explain this text from a learning resource:\n\n\"\"\"\n{selected_text}\n\"\"\""}
21
  ],
22
+ temperature=0.7,
23
+ max_tokens=500
24
  )
25
+ return response.choices[0].message.content
26
  except Exception as e:
27
+ return f"Error: {str(e)}"
28
 
29
+ # ---- Your work content ----
 
30
  YOUR_WORK_HTML = """
31
+ <div id="content" style="max-width: 800px; margin: auto; font-size: 16px; line-height: 1.6;">
32
  <h1>Text Generation</h1>
33
  <p>
34
+ Text generation is the task of producing natural language text given an input prompt.
35
  It is commonly used for chatbots, creative writing, summarization, and code generation.
36
  </p>
37
  <p>
38
+ Most modern text generation models are based on the transformer architecture and are
39
  trained using next-token prediction.
40
  </p>
41
  <p>
42
+ During inference, the model repeatedly samples the most likely next token until a
43
  stopping condition is reached.
44
  </p>
45
  </div>
46
  """
47
 
48
+ # ---- Hugging Face reference content ----
49
  HF_REFERENCE_HTML = """
50
+ <div id="hf-content" style="max-width: 800px; margin: auto; font-size: 16px; line-height: 1.6;">
51
  <h1>Text Generation (Hugging Face Reference)</h1>
52
+ <h1>About Text Generation</h1>
53
  <p>
54
+ This task covers guides on both <a href="https://huggingface.co/models?pipeline_tag=text-generation&sort=downloads">text-generation</a> and <a href="https://huggingface.co/models?other=text2text-generation&sort=downloads">text-to-text generation</a> models.
55
+ Popular large language models that are used for chats or following instructions are also covered in this task.
56
+ You can find the list of selected open-source large language models <a href="https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard">here</a>, ranked by their performance scores.
57
  </p>
58
+
59
  <h2>Use Cases</h2>
60
+
61
  <h3>Instruction Models</h3>
62
  <p>
63
+ A model trained for text generation can be later adapted to follow instructions.
64
+ You can try some of the most powerful instruction-tuned open-access models like Mixtral 8x7B, Cohere Command R+, and Meta Llama3 70B at <a href="https://huggingface.co/chat">Hugging Chat</a>.
65
  </p>
66
+
67
  <h3>Code Generation</h3>
68
  <p>
69
+ A Text Generation model, also known as a causal language model, can be trained on code from scratch to help the programmers in their repetitive coding tasks.
70
+ One of the most popular open-source models for code generation is StarCoder, which can generate code in 80+ languages. You can try it <a href="https://huggingface.co/spaces/bigcode/bigcode-playground">here</a>.
71
  </p>
72
+
73
  <h3>Stories Generation</h3>
74
  <p>
75
+ A story generation model can receive an input like "Once upon a time" and proceed to create a story-like text based on those first words.
76
+ You can try <a href="https://huggingface.co/spaces/mosaicml/mpt-7b-storywriter">this application</a> which contains a model trained on story generation, by MosaicML.
77
+ If your generative model training data is different than your use case, you can train a causal language model from scratch.
78
+ Learn how to do it in the free transformers <a href="https://huggingface.co/course/chapter7/6?fw=pt">course</a>!
79
+ </p>
80
+
81
+ <h2>Task Variants</h2>
82
+
83
+ <h3>Completion Generation Models</h3>
84
+ <p>
85
+ A popular variant of Text Generation models predicts the next word given a bunch of words.
86
+ Word by word a longer text is formed that results in for example:
87
+ <ul>
88
+ <li>Given an incomplete sentence, complete it.
89
+ <li>Continue a story given the first sentences.
90
+ <li>Provided a code description, generate the code.
91
+ </ul>
92
+ The most popular models for this task are GPT-based models, Mistral or Llama series.
93
+ These models are trained on data that has no labels, so you just need plain text to train your own model.
94
+ You can train text generation models to generate a wide variety of documents, from code to stories.
95
+ </p>
96
+
97
+ <h3>Text-to-Text Generation Models</h3>
98
+ <p>
99
+ These models are trained to learn the mapping between a pair of texts (e.g. translation from one language to another).
100
+ The most popular variants of these models are NLLB, FLAN-T5, and BART.
101
+ Text-to-Text models are trained with multi-tasking capabilities, they can accomplish a wide range of tasks, including summarization, translation, and text classification.
102
+ </p>
103
+ <h3>Language Model Variants</h3>
104
+ When it comes to text generation, the underlying language model can come in several types:
105
+ <ul>
106
+ <li>Base models: refers to plain language models like Mistral 7B and Meta Llama-3-70b. These models are good for fine-tuning and few-shot prompting.
107
+ <li>Instruction-trained models: these models are trained in a multi-task manner to follow a broad range of instructions like "Write me a recipe for chocolate cake". Models like Qwen 2 7B, Yi 1.5 34B Chat, and Meta Llama 70B Instruct are examples of instruction-trained models. In general, instruction-trained models will produce better responses to instructions than base models.
108
+ <li>Human feedback models: these models extend base and instruction-trained models by incorporating human feedback that rates the quality of the generated text according to criteria like helpfulness, honesty, and harmlessness. The human feedback is then combined with an optimization technique like reinforcement learning to align the original model to be closer with human preferences. The overall methodology is often called Reinforcement Learning from Human Feedback, or RLHF for short. Zephyr ORPO 141B A35B is an open-source model aligned through human feedback.
109
+ </ul>
110
+ <h2>Text Generation from Image and Text</h2>
111
+ <p>
112
+ There are language models that can input both text and image and output text, called vision language models.
113
+ IDEFICS 2 and MiniCPM Llama3 V are good examples.
114
+ They accept the same generation parameters as other language models.
115
+ However, since they also take images as input, you have to use them with the image-to-text pipeline.
116
+ You can find more information about this in the image-to-text task page.
117
  </p>
118
+
119
+ <h2>Inference</h2>
120
+ <p>
121
+ You can use the 🤗 Transformers library <code>text-generation</code> pipeline to do inference
122
+ with text generation models. It takes an input text and generates a continuation of that text.
123
+ </p>
124
+
125
+ <pre style="background: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto;">
126
+ from transformers import pipeline
127
+ generator = pipeline('text-generation', model='gpt2')
128
+ generator("Hello, I'm a language model,", max_length=30, num_return_sequences=3)
129
+ </pre>
130
+
131
+ <h2>Text Generation Inference</h2>
132
+ <p>
133
+ Text Generation Inference (TGI) is an open-source toolkit for serving LLMs tackling challenges such as response time.
134
+ TGI powers inference solutions like Inference Endpoints and Hugging Chat, as well as multiple community projects.
135
+ You can use it to deploy any supported open-source large language model of your choice.
136
+ </p>
137
+ <h2>ChatUI Spaces</h2>
138
+ <p>
139
+ Hugging Face Spaces includes templates to easily deploy your own instance of a specific application.
140
+ ChatUI is an open-source interface that enables serving conversational interface for large language models and can be deployed with few clicks at Spaces.
141
+ TGI powers these Spaces under the hood for faster inference.
142
+ Thanks to the template, you can deploy your own instance based on a large language model with only a few clicks and customize it. Learn more about it here and create your large language model instance here.
143
  </div>
144
  """
145
 
146
  def switch_content(choice):
147
+ if choice == "My Work":
148
+ return YOUR_WORK_HTML
149
+ else:
150
+ return HF_REFERENCE_HTML
151
 
152
+ with gr.Blocks(head="""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  <script>
154
+ document.addEventListener("mouseup", () => {
155
+ const selection = window.getSelection().toString().trim();
156
+ if (selection.length > 0) {
157
+ const textbox = document.querySelector('textarea[data-testid="textbox"]');
158
+ if (textbox) {
159
+ const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
160
+ window.HTMLTextAreaElement.prototype,
161
+ "value"
162
+ ).set;
163
+ nativeInputValueSetter.call(textbox, selection);
164
+ textbox.dispatchEvent(new Event("input", { bubbles: true }));
165
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  }
167
+ });
 
 
 
 
168
  </script>
169
+ """) as demo:
170
+ gr.Markdown("### 📘 Highlight text and ask GPT for help")
171
+
172
+ # Toggle between your work and HF reference
 
 
 
 
 
173
  view_toggle = gr.Radio(
174
  choices=["My Work", "HF Reference"],
175
  value="My Work",
176
  label="View",
177
+ interactive=True
178
  )
179
+
180
  content_display = gr.HTML(YOUR_WORK_HTML)
181
+
182
+ view_toggle.change(
183
+ fn=switch_content,
184
+ inputs=view_toggle,
185
+ outputs=content_display
186
+ )
187
+
188
+ selected_text = gr.Textbox(
189
+ label="Selected text",
190
+ placeholder="Highlight text above...",
191
+ lines=3,
192
+ interactive=True
193
+ )
194
+
195
+ explain_btn = gr.Button("Explain selection 🧠")
196
+ output = gr.Markdown()
197
+
198
+ explain_btn.click(
199
+ fn=explain_text,
200
+ inputs=selected_text,
201
+ outputs=output,
202
+ )
203
 
204
  demo.launch()