File size: 30,877 Bytes
85cc945 60d4662 cc7228a d425b14 5e93a9c 83c4bb9 5e93a9c 9a358fc 5e93a9c 6165eb2 9a358fc 5e93a9c 83c4bb9 5e93a9c 6165eb2 83c4bb9 6165eb2 5e93a9c d425b14 83c4bb9 6165eb2 d425b14 6165eb2 d425b14 83c4bb9 d425b14 83c4bb9 d425b14 83c4bb9 d425b14 7100105 d425b14 83c4bb9 7100105 5e93a9c d425b14 5e93a9c 83c4bb9 5e93a9c d425b14 cc7228a d425b14 6165eb2 83c4bb9 5e93a9c d425b14 cc7228a d425b14 5e93a9c 83c4bb9 5e93a9c d425b14 5e93a9c 6165eb2 d425b14 6165eb2 83c4bb9 6165eb2 5e93a9c 83c4bb9 d425b14 6165eb2 d425b14 5e93a9c 83c4bb9 d425b14 5e93a9c 6165eb2 d425b14 6165eb2 d425b14 6165eb2 d425b14 6165eb2 d425b14 5e93a9c 83c4bb9 d425b14 5e93a9c 6165eb2 d425b14 6165eb2 d425b14 6165eb2 d425b14 6165eb2 5e93a9c d425b14 5e93a9c d425b14 5e93a9c d425b14 6165eb2 83c4bb9 6165eb2 83c4bb9 d425b14 83c4bb9 d425b14 83c4bb9 d425b14 83c4bb9 d425b14 5e93a9c 6165eb2 5e93a9c 6165eb2 d425b14 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 |
import gradio as gr
import os
import json
import logging
import tempfile
# Optional imports for audio processing
try:
import scipy.io.wavfile
SCIPY_AVAILABLE = True
except ImportError:
SCIPY_AVAILABLE = False
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ MINIMAL AI RESEARCH DEMO - GRADIO 5.0.1 COMPATIBLE
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
try:
from huggingface_hub import InferenceClient
HF_AVAILABLE = True
except ImportError:
HF_AVAILABLE = False
# Simple logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ง SIMPLE CLIENT - VERIFIED WORKING
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def get_client():
"""Get HuggingFace client - exactly like your working example."""
api_token = os.getenv("HF_API_TOKEN")
if not HF_AVAILABLE:
logger.error("โ HuggingFace Hub not available")
return None
if not api_token:
logger.error("โ HF_API_TOKEN not set")
return None
try:
logger.info("๐ Initializing HuggingFace client...")
client = InferenceClient(
provider="hf-inference",
api_key=api_token,
)
# Test with exact same call as your working example
logger.info("๐งช Testing client with fill_mask...")
test_result = client.fill_mask("The capital of France is [MASK].", model="google-bert/bert-base-uncased")
logger.info(f"โ
Client test successful: {type(test_result)}, got {len(test_result) if isinstance(test_result, list) else 'non-list'} results")
return client
except Exception as e:
logger.error(f"โ Client initialization failed: {e}")
return None
CLIENT = get_client()
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ค COMPREHENSIVE AI FUNCTIONS - ALL HUGGINGFACE CAPABILITIES
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def run_chat(message):
"""Chat function - using your exact working model."""
if not CLIENT:
return "โ Client not available"
# Handle None/empty message from Gradio
if not message or str(message).strip() == "":
return "โ Please enter a message"
try:
clean_message = str(message).strip()
messages = [{"role": "user", "content": clean_message}]
logger.info(f"Chat call: message='{clean_message}'")
completion = CLIENT.chat.completions.create(
model="Qwen/Qwen2.5-72B-Instruct",
messages=messages,
)
result = completion.choices[0].message.content
logger.info(f"Chat result: {type(result)}")
return result
except Exception as e:
logger.error(f"Chat error: {e}")
return f"โ Error: {str(e)}\n\n**Debug:** Message: '{message}'"
def run_fill_mask(text):
"""Fill mask - using your exact working approach."""
if not CLIENT:
return "โ Client not available"
# Handle None/empty text from Gradio
if not text or str(text).strip() == "":
return "โ Please enter text with [MASK]"
clean_text = str(text).strip()
if "[MASK]" not in clean_text:
return "โ Text must contain [MASK] token"
try:
logger.info(f"Fill mask call: text='{clean_text}'")
result = CLIENT.fill_mask(clean_text, model="google-bert/bert-base-uncased")
logger.info(f"Fill mask result: {type(result)}")
if isinstance(result, list):
output = "๐ญ **Predictions:**\n"
for i, pred in enumerate(result[:5], 1):
token = pred.get("token_str", "").strip()
score = pred.get("score", 0)
output += f"{i}. **{token}** ({score:.3f})\n"
return output
return str(result)
except Exception as e:
logger.error(f"Fill mask error: {e}")
return f"โ Error: {str(e)}\n\n**Debug:** Text: '{text}'"
def run_question_answering(question, context):
"""Q&A function - Fixed parameter handling."""
if not CLIENT:
return "โ Client not available"
# Handle None/empty values from Gradio
if not question or not context or question.strip() == "" or context.strip() == "":
return "โ Please provide both question and context"
try:
# Ensure we have clean string inputs
clean_question = str(question).strip()
clean_context = str(context).strip()
logger.info(f"Q&A call: question='{clean_question}', context='{clean_context[:50]}...'")
answer = CLIENT.question_answering(
question=clean_question,
context=clean_context,
model="deepset/roberta-base-squad2",
)
logger.info(f"Q&A result: {type(answer)}, {answer}")
if isinstance(answer, dict):
return f"๐ก **Answer:** {answer.get('answer', 'No answer found')}\n๐ **Score:** {answer.get('score', 'N/A')}"
else:
return f"๐ก **Answer:** {str(answer)}"
except Exception as e:
logger.error(f"Q&A error: {e}")
return f"โ Error: {str(e)}\n\n**Debug:** Question: '{question}', Context: '{context[:50] if context else 'None'}...'"
def run_summarization(text):
"""Summarization function - Fixed parameter handling."""
if not CLIENT:
return "โ Client not available"
# Handle None/empty text from Gradio
if not text or str(text).strip() == "":
return "โ Please enter text to summarize"
clean_text = str(text).strip()
if len(clean_text.split()) < 10:
return "โ Text must be at least 10 words long"
try:
logger.info(f"Summarization call: text length={len(clean_text)}")
result = CLIENT.summarization(clean_text, model="facebook/bart-large-cnn")
logger.info(f"Summarization result: {type(result)}")
if isinstance(result, list) and result:
summary = result[0].get('summary_text', str(result[0]))
return f"๐ **Summary:** {summary}"
elif isinstance(result, dict):
summary = result.get('summary_text', str(result))
return f"๐ **Summary:** {summary}"
else:
return f"๐ **Summary:** {str(result)}"
except Exception as e:
logger.error(f"Summarization error: {e}")
return f"โ Error: {str(e)}\n\n**Debug:** Text length: {len(text) if text else 0}"
def run_text_classification(text):
"""Text Classification function."""
if not CLIENT:
return "โ Client not available"
if not text or str(text).strip() == "":
return "โ Please enter text to classify"
clean_text = str(text).strip()
try:
logger.info(f"Text classification call: text='{clean_text[:50]}...'")
result = CLIENT.text_classification(clean_text, model="cardiffnlp/twitter-roberta-base-sentiment-latest")
logger.info(f"Text classification result: {type(result)}")
if isinstance(result, list):
output = "๐ท๏ธ **Classifications:**\n"
for i, pred in enumerate(result[:5], 1):
label = pred.get("label", "Unknown")
score = pred.get("score", 0)
output += f"{i}. **{label}** ({score:.3f})\n"
return output
return str(result)
except Exception as e:
logger.error(f"Text classification error: {e}")
return f"โ Error: {str(e)}"
def run_token_classification(text):
"""Token Classification (NER) function."""
if not CLIENT:
return "โ Client not available"
if not text or str(text).strip() == "":
return "โ Please enter text for entity recognition"
clean_text = str(text).strip()
try:
logger.info(f"Token classification call: text='{clean_text}'")
result = CLIENT.token_classification(clean_text, model="dslim/bert-base-NER")
logger.info(f"Token classification result: {type(result)}")
if isinstance(result, list):
output = "๐ท๏ธ **Named Entities:**\n"
for i, entity in enumerate(result[:10], 1):
word = entity.get("word", "Unknown")
label = entity.get("entity", "Unknown")
score = entity.get("score", 0)
output += f"{i}. **{word}** โ {label} ({score:.3f})\n"
return output
return str(result)
except Exception as e:
logger.error(f"Token classification error: {e}")
return f"โ Error: {str(e)}"
def run_translation(text):
"""Translation function."""
if not CLIENT:
return "โ Client not available"
if not text or str(text).strip() == "":
return "โ Please enter text to translate"
clean_text = str(text).strip()
try:
logger.info(f"Translation call: text='{clean_text[:50]}...'")
result = CLIENT.translation(clean_text, model="Helsinki-NLP/opus-mt-en-fr")
logger.info(f"Translation result: {type(result)}")
if isinstance(result, list) and result:
translation = result[0].get('translation_text', str(result[0]))
return f"๐ **Translation (ENโFR):** {translation}"
elif isinstance(result, dict):
translation = result.get('translation_text', str(result))
return f"๐ **Translation (ENโFR):** {translation}"
else:
return f"๐ **Translation:** {str(result)}"
except Exception as e:
logger.error(f"Translation error: {e}")
return f"โ Error: {str(e)}"
def run_feature_extraction(text):
"""Feature Extraction function."""
if not CLIENT:
return "โ Client not available"
if not text or str(text).strip() == "":
return "โ Please enter text for feature extraction"
clean_text = str(text).strip()
try:
logger.info(f"Feature extraction call: text='{clean_text[:50]}...'")
result = CLIENT.feature_extraction(clean_text, model="intfloat/multilingual-e5-large-instruct")
logger.info(f"Feature extraction result: {type(result)}")
if isinstance(result, list) and result:
dim = len(result[0]) if result[0] else 0
sample = result[0][:5] if dim >= 5 else result[0]
return f"๐งฎ **Feature Vector:** Dimension: {dim}\n**Sample values:** {sample}..."
else:
return f"๐งฎ **Features:** {str(result)[:200]}..."
except Exception as e:
logger.error(f"Feature extraction error: {e}")
return f"โ Error: {str(e)}"
def run_zero_shot_classification(text, labels):
"""Zero Shot Classification function."""
if not CLIENT:
return "โ Client not available"
if not text or str(text).strip() == "":
return "โ Please enter text to classify"
if not labels or str(labels).strip() == "":
return "โ Please enter candidate labels (comma-separated)"
clean_text = str(text).strip()
clean_labels = [label.strip() for label in str(labels).split(",") if label.strip()]
if not clean_labels:
return "โ Please provide valid labels separated by commas"
try:
logger.info(f"Zero shot classification call: text='{clean_text[:50]}...', labels={clean_labels}")
# Use text classification with BART MNLI model for zero-shot
result = CLIENT.text_classification(
clean_text,
model="facebook/bart-large-mnli",
# Note: Some models support candidate_labels parameter
)
logger.info(f"Zero shot classification result: {type(result)}")
if isinstance(result, list):
output = "๐ฏ **Zero-Shot Classification:**\n"
for i, pred in enumerate(result[:5], 1):
label = pred.get("label", "Unknown")
score = pred.get("score", 0)
output += f"{i}. **{label}** ({score:.3f})\n"
return output
elif isinstance(result, dict):
labels_result = result.get('labels', [])
scores = result.get('scores', [])
output = "๐ฏ **Zero-Shot Classification:**\n"
for i, (label, score) in enumerate(zip(labels_result[:5], scores[:5]), 1):
output += f"{i}. **{label}** ({score:.3f})\n"
return output
else:
return f"๐ฏ **Result:** {str(result)}"
except Exception as e:
logger.error(f"Zero shot classification error: {e}")
# Fallback to regular text classification
try:
result = CLIENT.text_classification(clean_text, model="cardiffnlp/twitter-roberta-base-sentiment-latest")
return f"๐ฏ **Classification (fallback):** {str(result)}\n\nโ ๏ธ Note: Zero-shot with custom labels not available, showing sentiment analysis instead."
except:
return f"โ Error: {str(e)}"
def run_image_classification(image):
"""Image Classification function."""
if not CLIENT:
return "โ Client not available"
if image is None:
return "โ Please upload an image"
try:
logger.info(f"Image classification call: image type={type(image)}")
result = CLIENT.image_classification(image, model="google/vit-base-patch16-224")
logger.info(f"Image classification result: {type(result)}")
if isinstance(result, list):
output = "๐ผ๏ธ **Image Classification:**\n"
for i, pred in enumerate(result[:5], 1):
label = pred.get("label", "Unknown")
score = pred.get("score", 0)
output += f"{i}. **{label}** ({score:.1%})\n"
return output
return str(result)
except Exception as e:
logger.error(f"Image classification error: {e}")
return f"โ Error: {str(e)}"
def run_automatic_speech_recognition(audio):
"""Automatic Speech Recognition function."""
if not CLIENT:
return "โ Client not available"
if audio is None:
return "โ Please upload an audio file or record audio"
try:
logger.info(f"ASR call: audio type={type(audio)}")
# Handle different audio input types
if isinstance(audio, tuple):
# Convert numpy array to temporary file
if not SCIPY_AVAILABLE:
return "โ scipy is required for audio processing. Install with: pip install scipy"
import scipy.io.wavfile as wav
sample_rate, audio_array = audio
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
wav.write(tmp_file.name, sample_rate, audio_array)
audio_path = tmp_file.name
else:
audio_path = audio
result = CLIENT.automatic_speech_recognition(audio_path, model="openai/whisper-large-v3")
logger.info(f"ASR result: {type(result)}")
if isinstance(result, dict):
text = result.get('text', str(result))
return f"๐ค **Transcription:** {text}"
else:
return f"๐ค **Transcription:** {str(result)}"
except Exception as e:
logger.error(f"ASR error: {e}")
return f"โ Error: {str(e)}"
def run_text_to_image(prompt):
"""Text to Image function."""
if not CLIENT:
return "โ Client not available"
if not prompt or str(prompt).strip() == "":
return "โ Please enter a text prompt for image generation"
clean_prompt = str(prompt).strip()
try:
logger.info(f"Text to image call: prompt='{clean_prompt}'")
# Note: This returns a PIL Image object
image = CLIENT.text_to_image(clean_prompt, model="black-forest-labs/FLUX.1-schnell")
logger.info(f"Text to image result: {type(image)}")
return f"๐จ **Image Generated Successfully!** \n๐ Prompt: {clean_prompt}\n๐ผ๏ธ Check the generated image above."
except Exception as e:
logger.error(f"Text to image error: {e}")
return f"โ Error: {str(e)}"
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐จ COMPREHENSIVE GRADIO INTERFACE - ALL AI CAPABILITIES
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Create interface with comprehensive AI capabilities
with gr.Blocks(title="๐ Complete AI Research Hub") as demo:
gr.Markdown("# ๐ Complete AI Research Hub\n### **All HuggingFace Inference API Capabilities**")
if CLIENT:
gr.Markdown("โ
**Status:** Connected and tested successfully")
else:
gr.Markdown("โ **Status:** Set HF_API_TOKEN environment variable")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ฌ CHAT & TEXT GENERATION
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐ฌ Chat with AI")
chat_input = gr.Textbox(label="Your Message", placeholder="Ask anything...")
chat_output = gr.Textbox(label="AI Response", lines=5)
chat_btn = gr.Button("Send", variant="primary")
chat_btn.click(run_chat, inputs=chat_input, outputs=chat_output)
gr.Markdown("---")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ญ TEXT UNDERSTANDING & PREDICTION
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐ญ Fill Mask Prediction")
mask_input = gr.Textbox(
label="Text with [MASK]",
value="The capital of France is [MASK].",
placeholder="Enter text with [MASK] token"
)
mask_output = gr.Textbox(label="Predictions", lines=6)
mask_btn = gr.Button("Predict", variant="primary")
mask_btn.click(run_fill_mask, inputs=mask_input, outputs=mask_output)
gr.Markdown("---")
gr.Markdown("## โ Question Answering")
qa_question = gr.Textbox(label="Question", value="What is AI?")
qa_context = gr.Textbox(
label="Context",
lines=3,
value="Artificial Intelligence (AI) is the simulation of human intelligence in machines."
)
qa_output = gr.Textbox(label="Answer", lines=3)
qa_btn = gr.Button("Answer", variant="primary")
qa_btn.click(run_question_answering, inputs=[qa_question, qa_context], outputs=qa_output)
gr.Markdown("---")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ TEXT PROCESSING & ANALYSIS
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐ Text Summarization")
sum_input = gr.Textbox(
label="Text to Summarize",
lines=5,
value="Machine learning is a method of data analysis that automates analytical model building. It is a branch of artificial intelligence based on the idea that systems can learn from data, identify patterns and make decisions with minimal human intervention. The process involves feeding data into algorithms that learn patterns and make predictions or decisions without being explicitly programmed for each specific task."
)
sum_output = gr.Textbox(label="Summary", lines=3)
sum_btn = gr.Button("Summarize", variant="primary")
sum_btn.click(run_summarization, inputs=sum_input, outputs=sum_output)
gr.Markdown("---")
gr.Markdown("## ๐ท๏ธ Text Classification")
tc_input = gr.Textbox(
label="Text to Classify",
value="I love this new AI technology! It's amazing.",
placeholder="Enter text for sentiment/topic classification"
)
tc_output = gr.Textbox(label="Classification Results", lines=4)
tc_btn = gr.Button("Classify", variant="primary")
tc_btn.click(run_text_classification, inputs=tc_input, outputs=tc_output)
gr.Markdown("---")
gr.Markdown("## ๐ฏ Zero-Shot Classification")
zsc_text = gr.Textbox(
label="Text to Classify",
value="I need to return this broken phone and get my money back.",
placeholder="Enter text for classification"
)
zsc_labels = gr.Textbox(
label="Candidate Labels (comma-separated)",
value="refund, complaint, question, compliment",
placeholder="Enter possible labels separated by commas"
)
zsc_output = gr.Textbox(label="Classification Results", lines=4)
zsc_btn = gr.Button("Classify", variant="primary")
zsc_btn.click(run_zero_shot_classification, inputs=[zsc_text, zsc_labels], outputs=zsc_output)
gr.Markdown("---")
gr.Markdown("## ๐ท๏ธ Named Entity Recognition")
ner_input = gr.Textbox(
label="Text for Entity Recognition",
value="My name is John Smith and I work at Google in New York.",
placeholder="Enter text to extract named entities"
)
ner_output = gr.Textbox(label="Named Entities", lines=5)
ner_btn = gr.Button("Extract Entities", variant="primary")
ner_btn.click(run_token_classification, inputs=ner_input, outputs=ner_output)
gr.Markdown("---")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ LANGUAGE & TRANSLATION
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐ Language Translation")
trans_input = gr.Textbox(
label="English Text to Translate",
value="Hello, how are you today? I hope you have a wonderful day.",
placeholder="Enter English text to translate to French"
)
trans_output = gr.Textbox(label="French Translation", lines=3)
trans_btn = gr.Button("Translate to French", variant="primary")
trans_btn.click(run_translation, inputs=trans_input, outputs=trans_output)
gr.Markdown("---")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐งฎ EMBEDDINGS & FEATURES
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐งฎ Feature Extraction (Embeddings)")
fe_input = gr.Textbox(
label="Text for Feature Extraction",
value="Machine learning is transforming the world.",
placeholder="Enter text to generate embeddings"
)
fe_output = gr.Textbox(label="Feature Vector Info", lines=4)
fe_btn = gr.Button("Extract Features", variant="primary")
fe_btn.click(run_feature_extraction, inputs=fe_input, outputs=fe_output)
gr.Markdown("---")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ค AUDIO PROCESSING
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐ค Speech Recognition")
asr_input = gr.Audio(
sources=["upload", "microphone"],
type="numpy",
label="Upload Audio or Record"
)
asr_output = gr.Textbox(label="Transcription", lines=4)
asr_btn = gr.Button("Transcribe Audio", variant="primary")
asr_btn.click(run_automatic_speech_recognition, inputs=asr_input, outputs=asr_output)
gr.Markdown("---")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ผ๏ธ IMAGE PROCESSING
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("## ๐ผ๏ธ Image Classification")
img_input = gr.Image(type="filepath", label="Upload Image")
img_output = gr.Textbox(label="Classification Results", lines=5)
img_btn = gr.Button("Classify Image", variant="primary")
img_btn.click(run_image_classification, inputs=img_input, outputs=img_output)
gr.Markdown("---")
gr.Markdown("## ๐จ Text to Image Generation")
tti_input = gr.Textbox(
label="Image Description",
value="A beautiful sunset over mountains with a lake in the foreground",
placeholder="Describe the image you want to generate"
)
tti_output_img = gr.Image(label="Generated Image")
tti_output_text = gr.Textbox(label="Generation Status", lines=2)
tti_btn = gr.Button("Generate Image", variant="primary")
def run_text_to_image_with_display(prompt):
status = run_text_to_image(prompt)
try:
if CLIENT and prompt and str(prompt).strip():
image = CLIENT.text_to_image(str(prompt).strip(), model="black-forest-labs/FLUX.1-schnell")
return image, status
else:
return None, status
except Exception as e:
return None, f"โ Error: {str(e)}"
tti_btn.click(run_text_to_image_with_display, inputs=tti_input, outputs=[tti_output_img, tti_output_text])
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๐ SETUP & INFO
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
gr.Markdown("---")
gr.Markdown("""
## ๐ง Setup Instructions
**For full functionality:**
```bash
# Install dependencies
pip install gradio huggingface_hub scipy
# Set API token
export HF_API_TOKEN="your_token_here"
```
**Get your token:** https://huggingface.co/settings/tokens
**๐ Dependency Status:**
- ๐ค HuggingFace Hub: {}
- ๐ต Scipy (for audio): {}
**๐ฏ Available Capabilities:**
- ๐ฌ **Chat** - Conversational AI with Qwen-2.5-72B
- ๐ญ **Fill Mask** - Text completion with BERT
- โ **Q&A** - Question answering with RoBERTa
- ๐ **Summarization** - Text summarization with BART
- ๐ท๏ธ **Text Classification** - Sentiment analysis
- ๐ฏ **Zero-Shot Classification** - Custom label classification
- ๐ท๏ธ **NER** - Named entity recognition with BERT
- ๐ **Translation** - English to French with Helsinki-NLP
- ๐งฎ **Feature Extraction** - Text embeddings with E5
- ๐ค **Speech Recognition** - Audio transcription with Whisper
- ๐ผ๏ธ **Image Classification** - Visual analysis with ViT
- ๐จ **Text to Image** - AI image generation with FLUX
**๐ Perfect for research, education, and development!**
""".format(
"โ
Available" if HF_AVAILABLE else "โ Missing",
"โ
Available" if SCIPY_AVAILABLE else "โ ๏ธ Optional (needed for audio)"
))
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
)
|