TheHickman commited on
Commit
a5a4e31
·
verified ·
1 Parent(s): 6be3f7b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +165 -131
app.py CHANGED
@@ -1,164 +1,198 @@
1
  import gradio as gr
2
  from openai import OpenAI
 
3
 
4
- client = OpenAI()
5
-
6
- CONTENT_PARAGRAPHS = [
7
- "Text generation is the task of producing natural language text given an input prompt. It is commonly used for chatbots, creative writing, summarization, and code generation.",
8
- "Most modern text generation models are based on the transformer architecture and are trained using next-token prediction. The transformer uses self-attention mechanisms to weigh the importance of different words in a sequence when making predictions.",
9
- "During inference, the model repeatedly samples the most likely next token until a stopping condition is reached. This process is called autoregressive generation. Parameters like temperature and top-p sampling control the randomness and diversity of the output.",
10
- "Large language models (LLMs) like GPT-4, Claude, and Llama are trained on vast corpora of text from the internet, books, and other sources. This gives them broad world knowledge and language understanding.",
11
- "Instruction-tuned models are further trained to follow user instructions, using techniques like supervised fine-tuning (SFT) and reinforcement learning from human feedback (RLHF). This makes them much more useful as assistants compared to base language models.",
12
- ]
13
-
14
- INITIAL_HTML = "\n".join(
15
- f'<p class="content-para" id="para-{i}">{p}</p>'
16
- for i, p in enumerate(CONTENT_PARAGRAPHS)
17
- )
18
-
19
- def explain_text(selected_text, current_html):
20
- if not selected_text or not selected_text.strip():
21
- return current_html, "⚠️ Please select some text first."
22
 
 
 
 
 
23
  selected_text = selected_text.strip()
24
-
 
 
25
  try:
26
  response = client.chat.completions.create(
27
- model="gpt-4o-mini",
28
  messages=[
29
  {
30
  "role": "system",
31
- "content": "You are an ML instructor who explains concepts clearly and simply for beginners."
32
  },
33
  {
34
  "role": "user",
35
- "content": f"Explain this text in 2-3 clear, simple sentences:\n\n\"{selected_text}\""
36
  }
37
  ],
38
- max_tokens=300,
39
  temperature=0.7,
 
40
  )
41
-
42
- explanation = response.choices[0].message.content.strip()
43
-
44
  except Exception as e:
45
- return current_html, f"Error: {str(e)}"
46
-
47
- replacement = (
48
- f'<mark class="explained-original">{selected_text}</mark>'
49
- f'<span class="explanation-block">💡 {explanation}</span>'
50
- )
51
-
52
- new_html = current_html.replace(selected_text, replacement, 1)
53
-
54
- if new_html == current_html:
55
- return current_html, "⚠️ Could not find selected text in the document."
56
-
57
- return new_html, "✅ Explanation added."
58
-
59
-
60
- def reset_content():
61
- return f'<div id="reader-content">{INITIAL_HTML}</div>', "", "Document reset."
62
-
63
-
64
- CSS = """
65
- body { background: #faf8f4 !important; }
66
- #reader-content {
67
- font-family: Georgia, serif;
68
- font-size: 1.05rem;
69
- line-height: 1.85;
70
- color: #2c2010;
71
- background: #faf8f4;
72
- padding: 28px 32px;
73
- border-radius: 10px;
74
- border: 1px solid #e8dfc8;
75
- min-height: 320px;
76
- }
77
- .content-para { margin-bottom: 1.4em; }
78
- mark.explained-original {
79
- background: #f5e6a3;
80
- text-decoration: line-through;
81
- opacity: 0.7;
82
- }
83
- .explanation-block {
84
- display: inline-block;
85
- background: #fffbee;
86
- border-left: 3px solid #d4a800;
87
- padding: 6px 12px;
88
- margin: 4px 2px;
89
- }
90
  """
91
 
92
- JS_CAPTURE_SELECTION = """
93
- function setupSelectionCapture() {
94
- document.addEventListener("mouseup", function() {
95
- const selection = window.getSelection().toString().trim();
96
- if (selection.length > 2) {
97
- const textarea = document.querySelector('.selected-box textarea');
98
- if (textarea) {
99
- const nativeSetter = Object.getOwnPropertyDescriptor(
100
- window.HTMLTextAreaElement.prototype, "value"
101
- ).set;
102
- nativeSetter.call(textarea, selection);
103
- textarea.dispatchEvent(new Event("input", { bubbles: true }));
104
- }
105
- }
106
- });
107
- }
108
- setupSelectionCapture();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  """
110
 
111
- with gr.Blocks(title="ML Reader — Highlight & Explain") as demo:
112
 
113
- gr.HTML("""
114
- <div style="max-width:720px; margin:0 auto; padding:32px 16px 0;">
115
- <h1>Text Generation</h1>
116
- <p style="color:#888; font-size:0.9rem;">
117
- Highlight text below and click Explain.
118
- </p>
119
- </div>
120
- """)
121
 
122
- # Wrap content in a styled HTML container instead of elem_style
123
- gr.HTML('<div style="max-width:720px; margin:0 auto; padding:0 16px 60px;">')
124
 
125
- content_html = gr.HTML(
126
- value=f'<div id="reader-content">{INITIAL_HTML}</div>'
 
 
 
 
 
127
  )
128
-
 
 
 
 
 
 
 
 
129
  selected_text = gr.Textbox(
130
  label="Selected text",
131
- lines=2,
132
- elem_classes=["selected-box"],
133
  )
134
-
135
- with gr.Row():
136
- explain_btn = gr.Button("✦ Explain Selection")
137
- reset_btn = gr.Button("↺ Reset")
138
-
139
- status = gr.Textbox(label="", interactive=False)
140
-
141
- html_state = gr.State(f'<div id="reader-content">{INITIAL_HTML}</div>')
142
-
143
  explain_btn.click(
144
  fn=explain_text,
145
- inputs=[selected_text, html_state],
146
- outputs=[html_state, status],
147
- ).then(
148
- lambda h: h,
149
- inputs=[html_state],
150
- outputs=[content_html],
151
  )
152
 
153
- reset_btn.click(
154
- fn=reset_content,
155
- outputs=[html_state, selected_text, status],
156
- ).then(
157
- lambda h: h,
158
- inputs=[html_state],
159
- outputs=[content_html],
160
- )
161
-
162
- gr.HTML('</div>')
163
-
164
- demo.launch(css=CSS, js=JS_CAPTURE_SELECTION)
 
1
  import gradio as gr
2
  from openai import OpenAI
3
+ import os
4
 
5
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
  {
20
  "role": "system",
21
+ "content": "You are an expert machine learning instructor. Explain concepts clearly and intuitively for learners with basic ML knowledge. Keep explanations concise and educational."
22
  },
23
  {
24
  "role": "user",
25
+ "content": f"Explain this text from a learning resource:\n\n\"\"\"\n{selected_text}\n\"\"\""
26
  }
27
  ],
 
28
  temperature=0.7,
29
+ max_tokens=500
30
  )
31
+ return response.choices[0].message.content
 
 
32
  except Exception as e:
33
+ return f"Error: {str(e)}"
34
+
35
+
36
+ # ---- Your work content (UNCHANGED) ----
37
+ YOUR_WORK_HTML = """
38
+ <div id="content" style="max-width: 800px; margin: auto; font-size: 16px; line-height: 1.6;">
39
+ <h1>Text Generation</h1>
40
+ <p>
41
+ Text generation is the task of producing natural language text given an input prompt.
42
+ It is commonly used for chatbots, creative writing, summarization, and code generation.
43
+ </p>
44
+ <p>
45
+ Most modern text generation models are based on the transformer architecture and are
46
+ trained using next-token prediction.
47
+ </p>
48
+ <p>
49
+ During inference, the model repeatedly samples the most likely next token until a
50
+ stopping condition is reached.
51
+ </p>
52
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  """
54
 
55
+
56
+ # ---- Hugging Face reference content (FULL ORIGINAL TEXT RESTORED) ----
57
+ HF_REFERENCE_HTML = """
58
+ <div id="hf-content" style="max-width: 800px; margin: auto; font-size: 16px; line-height: 1.6;">
59
+ <h1>Text Generation (Hugging Face Reference)</h1>
60
+ <h1>About Text Generation</h1>
61
+ <p>
62
+ 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.
63
+ Popular large language models that are used for chats or following instructions are also covered in this task.
64
+ 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.
65
+ </p>
66
+
67
+ <h2>Use Cases</h2>
68
+
69
+ <h3>Instruction Models</h3>
70
+ <p>
71
+ A model trained for text generation can be later adapted to follow instructions.
72
+ 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>.
73
+ </p>
74
+
75
+ <h3>Code Generation</h3>
76
+ <p>
77
+ 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.
78
+ 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>.
79
+ </p>
80
+
81
+ <h3>Stories Generation</h3>
82
+ <p>
83
+ 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.
84
+ 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.
85
+ If your generative model training data is different than your use case, you can train a causal language model from scratch.
86
+ Learn how to do it in the free transformers <a href="https://huggingface.co/course/chapter7/6?fw=pt">course</a>!
87
+ </p>
88
+
89
+ <h2>Task Variants</h2>
90
+
91
+ <h3>Completion Generation Models</h3>
92
+ <p>
93
+ A popular variant of Text Generation models predicts the next word given a bunch of words.
94
+ Word by word a longer text is formed that results in for example:
95
+ <ul>
96
+ <li>Given an incomplete sentence, complete it.
97
+ <li>Continue a story given the first sentences.
98
+ <li>Provided a code description, generate the code.
99
+ </ul>
100
+ The most popular models for this task are GPT-based models, Mistral or Llama series.
101
+ These models are trained on data that has no labels, so you just need plain text to train your own model.
102
+ You can train text generation models to generate a wide variety of documents, from code to stories.
103
+ </p>
104
+
105
+ <h3>Text-to-Text Generation Models</h3>
106
+ <p>
107
+ These models are trained to learn the mapping between a pair of texts (e.g. translation from one language to another).
108
+ The most popular variants of these models are NLLB, FLAN-T5, and BART.
109
+ Text-to-Text models are trained with multi-tasking capabilities, they can accomplish a wide range of tasks, including summarization, translation, and text classification.
110
+ </p>
111
+
112
+ <h3>Language Model Variants</h3>
113
+ When it comes to text generation, the underlying language model can come in several types:
114
+ <ul>
115
+ <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.
116
+ <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.
117
+ <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.
118
+ </ul>
119
+
120
+ <h2>Text Generation from Image and Text</h2>
121
+ <p>
122
+ There are language models that can input both text and image and output text, called vision language models.
123
+ IDEFICS 2 and MiniCPM Llama3 V are good examples.
124
+ They accept the same generation parameters as other language models.
125
+ However, since they also take images as input, you have to use them with the image-to-text pipeline.
126
+ You can find more information about this in the image-to-text task page.
127
+ </p>
128
+
129
+ <h2>Inference</h2>
130
+ <p>
131
+ You can use the 🤗 Transformers library <code>text-generation</code> pipeline to do inference
132
+ with text generation models. It takes an input text and generates a continuation of that text.
133
+ </p>
134
+
135
+ <pre style="background: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto;">
136
+ from transformers import pipeline
137
+ generator = pipeline('text-generation', model='gpt2')
138
+ generator("Hello, I'm a language model,", max_length=30, num_return_sequences=3)
139
+ </pre>
140
+
141
+ <h2>Text Generation Inference</h2>
142
+ <p>
143
+ Text Generation Inference (TGI) is an open-source toolkit for serving LLMs tackling challenges such as response time.
144
+ TGI powers inference solutions like Inference Endpoints and Hugging Chat, as well as multiple community projects.
145
+ You can use it to deploy any supported open-source large language model of your choice.
146
+ </p>
147
+
148
+ <h2>ChatUI Spaces</h2>
149
+ <p>
150
+ Hugging Face Spaces includes templates to easily deploy your own instance of a specific application.
151
+ ChatUI is an open-source interface that enables serving conversational interface for large language models and can be deployed with few clicks at Spaces.
152
+ TGI powers these Spaces under the hood for faster inference.
153
+ 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.
154
+ </p>
155
+ </div>
156
  """
157
 
 
158
 
159
+ def switch_content(choice):
160
+ if choice == "My Work":
161
+ return YOUR_WORK_HTML
162
+ else:
163
+ return HF_REFERENCE_HTML
 
 
 
164
 
 
 
165
 
166
+ with gr.Blocks() as demo:
167
+ gr.Markdown("### 📘 Highlight text and ask GPT for help")
168
+
169
+ view_toggle = gr.Radio(
170
+ choices=["My Work", "HF Reference"],
171
+ value="My Work",
172
+ label="View"
173
  )
174
+
175
+ content_display = gr.HTML(YOUR_WORK_HTML)
176
+
177
+ view_toggle.change(
178
+ fn=switch_content,
179
+ inputs=view_toggle,
180
+ outputs=content_display
181
+ )
182
+
183
  selected_text = gr.Textbox(
184
  label="Selected text",
185
+ placeholder="Highlight text above...",
186
+ lines=3
187
  )
188
+
189
+ explain_btn = gr.Button("Explain selection 🧠")
190
+ output = gr.Markdown()
191
+
 
 
 
 
 
192
  explain_btn.click(
193
  fn=explain_text,
194
+ inputs=selected_text,
195
+ outputs=output,
 
 
 
 
196
  )
197
 
198
+ demo.launch()