|
|
| import os |
| import gradio as gr |
| from transformers import pipeline |
|
|
| print("\n#### Example: Deploying a Simple LLM with Gradio to Hugging Face Spaces") |
| print("The following code demonstrates a simple LLM inference application using Gradio, which can be easily deployed to Hugging Face Spaces. For this example, we'll use a small, efficient model.") |
|
|
|
|
| |
| |
| |
| print("\nLoading text generation pipeline...") |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| try: |
| |
| generator = pipeline("text-generation", model="distilgpt2", device=0) |
| print("Using distilgpt2 for text generation.") |
| except Exception as e: |
| print(f"Could not load distilgpt2 for text-generation, falling back to fill-mask: {e}") |
| generator = pipeline("fill-mask", model="distilbert-base-uncased") |
| print("Using distilbert-base-uncased for fill-mask.") |
|
|
| print("Model loaded.") |
|
|
| |
| def llm_inference(prompt): |
| if generator.task == "text-generation": |
| response = generator(prompt, max_new_tokens=50, num_return_sequences=1) |
| return response[0]['generated_text'] |
| elif generator.task == "fill-mask": |
| response = generator(prompt) |
| |
| top_prediction = response[0] |
| return f"{prompt.replace('[MASK]', f'**{top_prediction['token_str']}**')} (Score: {top_prediction['score']:.2f})" |
|
|
| |
| print("\nBuilding Gradio interface...") |
| if generator.task == "text-generation": |
| interface = gr.Interface( |
| fn=llm_inference, |
| inputs=gr.Textbox(lines=2, placeholder="Enter your prompt here..."), |
| outputs=gr.Textbox(lines=5), |
| title="Simple LLM Chatbot (distilgpt2)", |
| description="Enter a prompt and get text generated by a small LLM." |
| ) |
| else: |
| interface = gr.Interface( |
| fn=llm_inference, |
| inputs=gr.Textbox(lines=2, placeholder="Enter a sentence with [MASK] to fill, e.g., 'The capital of France is [MASK].'"), |
| outputs=gr.Textbox(lines=5), |
| title="Masked Language Model (distilbert)", |
| description="Enter a sentence with a [MASK] token to see the model's prediction." |
| ) |
|
|
| |
|
|
| import gradio as gr |
| from transformers import pipeline |
| import os |
| from huggingface_hub import login |
|
|
| |
| hf_token = os.getenv("HF_TOKEN") |
| if hf_token: |
| login(token=hf_token) |
|
|
| |
|
|
| generator = pipeline("text-generation", model="distilgpt2", token=hf_token) |
|
|
| def generate_text(prompt): |
| result = generator(prompt, max_length=50, num_return_sequences=1) |
| return result[0]["generated_text"] |
|
|
| demo = gr.Interface( |
| fn=generate_text, |
| inputs="text", |
| outputs="text", |
| title="Simple LLM Demo", |
| description="A lightweight text generation app using DistilGPT2." |
| ) |
|
|
| |
| demo.launch(server_name="0.0.0.0", server_port=7860) |
|
|
|
|
|
|
|
|