rjarun20 commited on
Commit
cc7228a
Β·
1 Parent(s): 16b6ad1

multi task app demo

Browse files
Files changed (2) hide show
  1. app.py +247 -60
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,64 +1,251 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ import json
3
+ import logging
4
+ from huggingface_hub import InferenceClient, InferenceApiError
5
+
6
+ # ── CONFIG & SETUP ──────────────────────────────────────────────────────────
7
+ API_TOKEN = os.getenv("HF_API_TOKEN")
8
+ if not API_TOKEN:
9
+ raise ValueError("HF_API_TOKEN environment variable is not set.")
10
+
11
+ CLIENT = InferenceClient(provider="hf-inference", api_key=API_TOKEN)
12
+
13
+ # Configure logging
14
+ logging.basicConfig(
15
+ format="%(asctime)s %(levelname)s %(message)s",
16
+ level=logging.INFO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  )
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # Common timeout for HTTP calls (in seconds)
21
+ REQUEST_TIMEOUT = 30
22
+
23
+
24
+ # ── GENERIC CALL WRAPPER ────────────────────────────────────────────────────
25
+ def safe_call(fn, *args, **kwargs):
26
+ """Run an inference call, catch errors and log them."""
27
+ try:
28
+ return fn(*args, **kwargs)
29
+ except InferenceApiError as e:
30
+ logger.error(f"Inference API error: {e}")
31
+ return {"error": f"Inference API error: {e}"}
32
+ except json.JSONDecodeError as e:
33
+ logger.error(f"JSON decode error: {e}")
34
+ return {"error": "Invalid JSON input."}
35
+ except Exception:
36
+ logger.exception("Unexpected error")
37
+ return {"error": "An unexpected error occurred. Please try again."}
38
+
39
+
40
+ # ── TASK FUNCTIONS ──────────────────────────────────────────────────────────
41
+
42
+ def asr_task(audio_path):
43
+ if not audio_path:
44
+ return "Please upload an audio file."
45
+ return safe_call(
46
+ CLIENT.automatic_speech_recognition,
47
+ audio_path,
48
+ model="openai/whisper-large-v3",
49
+ timeout=REQUEST_TIMEOUT
50
+ )
51
+
52
+
53
+ def chat_task(messages_str):
54
+ if not messages_str.strip():
55
+ return "Enter messages in JSON format."
56
+ try:
57
+ messages = json.loads(messages_str)
58
+ if not isinstance(messages, list):
59
+ raise ValueError("Messages must be a JSON list.")
60
+ except Exception as e:
61
+ logger.warning(f"Invalid chat input: {e}")
62
+ return "Invalid input. Please provide a JSON list of `{role,content}` objects."
63
+
64
+ response = safe_call(
65
+ CLIENT.chat.completions.create,
66
+ model="gpt2",
67
+ messages=messages,
68
+ timeout=REQUEST_TIMEOUT
69
+ )
70
+ return response.choices[0].message if hasattr(response, "choices") else response
71
+
72
+
73
+ def fill_mask_task(text):
74
+ if "[MASK]" not in text:
75
+ return "Your input must contain the token `[MASK]`."
76
+ return safe_call(
77
+ CLIENT.fill_mask,
78
+ text,
79
+ model="google-bert/bert-base-uncased",
80
+ timeout=REQUEST_TIMEOUT
81
+ )
82
+
83
+
84
+ def qa_task(question, context):
85
+ if not question or not context:
86
+ return "Both question and context are required."
87
+ return safe_call(
88
+ CLIENT.question_answering,
89
+ question=question,
90
+ context=context,
91
+ model="deepset/roberta-base-squad2",
92
+ timeout=REQUEST_TIMEOUT
93
+ )
94
+
95
+
96
+ def summarization_task(text):
97
+ if len(text.split()) < 5:
98
+ return "Please provide at least 5 words to summarize."
99
+ return safe_call(
100
+ CLIENT.summarization,
101
+ text,
102
+ model="facebook/bart-large-cnn",
103
+ timeout=REQUEST_TIMEOUT
104
+ )
105
+
106
+
107
+ def text_gen_task(prompt):
108
+ if not prompt.strip():
109
+ return "Prompt cannot be empty."
110
+ resp = safe_call(
111
+ CLIENT.chat.completions.create,
112
+ model="gpt2",
113
+ messages=[{"role": "user", "content": prompt}],
114
+ timeout=REQUEST_TIMEOUT
115
+ )
116
+ return resp.choices[0].message if hasattr(resp, "choices") else resp
117
+
118
+
119
+ def image_classification_task(image_path):
120
+ if not image_path:
121
+ return "Please upload an image."
122
+ return safe_call(
123
+ CLIENT.image_classification,
124
+ image_path,
125
+ model="Falconsai/nsfw_image_detection",
126
+ timeout=REQUEST_TIMEOUT
127
+ )
128
+
129
+
130
+ def feature_extraction_task(text):
131
+ if not text.strip():
132
+ return "Input text is empty."
133
+ return safe_call(
134
+ CLIENT.feature_extraction,
135
+ text,
136
+ model="intfloat/multilingual-e5-large-instruct",
137
+ timeout=REQUEST_TIMEOUT
138
+ )
139
+
140
+
141
+ # ── GRADIO INTERFACE ────────────────────────────────────────────────────────
142
+ with gr.Blocks() as demo:
143
+ gr.Markdown("## πŸš€ HF Inference Multi-Task Demo (CPU Space)")
144
+
145
+ with gr.Tabs():
146
+
147
+ with gr.TabItem("ASR"):
148
+ asr_input = gr.Audio(source="upload", type="filepath", label="Upload Audio")
149
+ asr_output = gr.Textbox(label="Transcript")
150
+ # Example audio files (replace with actual files in your repo)
151
+ gr.Examples(
152
+ examples=["sample1.flac", "sample2.wav"],
153
+ inputs=asr_input,
154
+ outputs=asr_output
155
+ )
156
+ asr_input.change(asr_task, asr_input, asr_output)
157
+
158
+ with gr.TabItem("Chat (LLM)"):
159
+ chat_in = gr.Textbox(
160
+ label="Messages (JSON list)",
161
+ placeholder='[{"role":"user","content":"Hello"}]',
162
+ lines=3
163
+ )
164
+ chat_out = gr.Textbox(label="Bot Reply")
165
+ gr.Examples(
166
+ examples=[
167
+ '[{"role":"user","content":"What is AI?"}]',
168
+ '[{"role":"system","content":"You are a helpful assistant."},'
169
+ '{"role":"user","content":"Tell me a joke."}]'
170
+ ],
171
+ inputs=chat_in,
172
+ outputs=chat_out,
173
+ fn=chat_task
174
+ )
175
+
176
+ with gr.TabItem("Fill Mask"):
177
+ mask_in = gr.Textbox(
178
+ label="Text with [MASK]",
179
+ placeholder="The capital of France is [MASK]."
180
+ )
181
+ mask_out = gr.JSON(label="Fill Mask Results")
182
+ gr.Examples(
183
+ examples=[
184
+ "The Eiffel Tower is located in [MASK].",
185
+ "Machine learning models are [MASK] and powerful."
186
+ ],
187
+ inputs=mask_in,
188
+ outputs=mask_out,
189
+ fn=fill_mask_task
190
+ )
191
+
192
+ with gr.TabItem("Q&A"):
193
+ qa_q = gr.Textbox(label="Question")
194
+ qa_ctx = gr.Textbox(label="Context", lines=4)
195
+ qa_out = gr.Textbox(label="Answer")
196
+ gr.Examples(
197
+ examples=[
198
+ ["Who wrote 'Pride and Prejudice'?", "Jane Austen was an English novelist known for ..."],
199
+ ["What is photosynthesis?", "Photosynthesis is the process by which green plants ..."]
200
+ ],
201
+ inputs=[qa_q, qa_ctx],
202
+ outputs=qa_out,
203
+ fn=qa_task
204
+ )
205
+
206
+ with gr.TabItem("Summarization"):
207
+ sum_in = gr.Textbox(label="Text to Summarize", lines=4)
208
+ sum_out = gr.Textbox(label="Summary")
209
+ gr.Examples(
210
+ examples=[
211
+ "The Industrial Revolution began in Britain in the late 18th century..."
212
+ ],
213
+ inputs=sum_in,
214
+ outputs=sum_out,
215
+ fn=summarization_task
216
+ )
217
+
218
+ with gr.TabItem("Text Generation"):
219
+ gen_in = gr.Textbox(label="Prompt", lines=2)
220
+ gen_out = gr.Textbox(label="Generated Text")
221
+ gr.Examples(
222
+ examples=[
223
+ "Once upon a time in a mystical land",
224
+ "In the future, humans will live on Mars because"
225
+ ],
226
+ inputs=gen_in,
227
+ outputs=gen_out,
228
+ fn=text_gen_task
229
+ )
230
+
231
+ with gr.TabItem("Image Classification"):
232
+ img_in = gr.Image(type="filepath", label="Upload Image")
233
+ img_out = gr.JSON(label="Classes")
234
+ gr.Examples(
235
+ examples=["cat.jpg", "dog.png"],
236
+ inputs=img_in,
237
+ outputs=img_out,
238
+ fn=image_classification_task
239
+ )
240
 
241
+ with gr.TabItem("Feature Extraction"):
242
+ fe_in = gr.Textbox(label="Input Text", lines=2)
243
+ fe_out = gr.Dataframe(label="Embeddings")
244
+ gr.Examples(
245
+ examples=["Machine learning is fascinating."],
246
+ inputs=fe_in,
247
+ outputs=fe_out,
248
+ fn=feature_extraction_task
249
+ )
250
 
251
+ demo.launch(server_name="0.0.0.0", server_port=7860)
 
requirements.txt CHANGED
@@ -1 +1,2 @@
1
- huggingface_hub==0.25.2
 
 
1
+ huggingface_hub==0.25.2
2
+ gradio