Spaces:
Build error
Build error
Download app.py from oulmokhtar/test: direct link, hf CLI and curl.
- Browser
- Download file 1.7 kB
-
https://huggingface.co/spaces/oulmokhtar/test/resolve/main/app.py
- Command line
-
hf download hf://spaces/oulmokhtar/test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/oulmokhtar/test/resolve/main/app.py
1.7 kB
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| import torch | |
| import gradio as gr | |
| # Load the model and tokenizer | |
| model_name_or_path = "oulmokhtar/kie-semantics" | |
| model = AutoModelForSequenceClassification.from_pretrained(model_name_or_path) | |
| tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) | |
| # Ensure the model is in evaluation mode | |
| model.eval() | |
| def predict(text): | |
| # Tokenize the input text | |
| inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True) | |
| # Get model predictions | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| logits = outputs.logits | |
| # Convert logits to probabilities using softmax | |
| probabilities = torch.softmax(logits, dim=-1).squeeze().tolist() | |
| # Map probabilities to class labels | |
| class_probabilities = {model.config.id2label[i]: prob for i, prob in enumerate(probabilities)} | |
| # Sort probabilities in descending order | |
| sorted_probabilities = sorted(class_probabilities.items(), key=lambda item: item[1], reverse=True) | |
| # Prepare HTML output for display | |
| output_html = "<div style='font-family: Arial, sans-serif;'>" | |
| for label, prob in sorted_probabilities: | |
| output_html += f"<div style='margin-bottom: 5px;'>{label}: <div style='display: inline-block; width: {prob * 100:.1f}%; background-color: #9b59b6; height: 12px;'></div> {prob:.4f}</div>" | |
| output_html += "</div>" | |
| return output_html | |
| # Create a Gradio interface | |
| iface = gr.Interface( | |
| fn=predict, | |
| inputs="text", | |
| outputs=gr.HTML(label="Classification Results"), | |
| title="Text Classification Demo with Probabilities" | |
| ) | |
| # Launch the interface | |
| iface.launch() | |