Please modify the gradio code in this code according to this error: Traceback (most…
- User
Please modify the gradio code in this code according to this error: Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Finetuned_Language_models\content\gradio_bert.py", line 40, in inputs=gr.inputs.Textbox(lines=2, placeholder="Enter a question here..."), # Textbox for entering the question AttributeError: module 'gradio' has no attribute 'inputs' code: import gradio as gr import torch from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification
Load the fine-tuned model and the tokenizer
model_dir = "DistilBert-GSM2K" tokenizer = DistilBertTokenizerFast.from_pretrained(model_dir) model = DistilBertForSequenceClassification.from_pretrained(model_dir) model.eval() # Set the model to inference mode
Make sure to have a GPU or CPU device ready for inference
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device)
Assuming you have <=model_dir>/config.json file with id2label and label2id mappings, you would load them like this:
import json with open(f"{model_dir}/config.json") as f: config = json.load(f) answer_to_id = config.get("label2id") id_to_answer = {int(id): label for label, id in answer_to_id.items()}
Function to get an answer given a question
def answer_question(question): inputs = tokenizer(question, return_tensors="pt", padding=True, truncation=True, max_length=512) inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad(): output = model(**inputs) # Get the predicted label ID label_id = torch.argmax(output.logits).item() # Get the corresponding label (answer) for the predicted ID answer = id_to_answer[label_id] return answerDefine the interface
iface = gr.Interface( fn=answer_question, # The function to wrap inputs=gr.inputs.Textbox(lines=2, placeholder="Enter a question here..."), # Textbox for entering the question outputs=gr.outputs.Textbox(label="Predicted Answer") # Output component )
Start the Gradio app
iface.launch(share=True)
- Assistant
It seems the Gradio library has had some updates which might have changed how inputs and outputs are structured. The reported error indicates that
gr.inputsis not found, which means we need to adapt the code based on the current version of Gradio.Here is how you could modify your Gradio code to match the newer Gradio API: