Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import json
|
4 |
+
|
5 |
+
# Define the URL for the local Ollama API and the model name
|
6 |
+
OLLAMA_API_URL = "http://localhost:11434/api/generate"
|
7 |
+
MODEL_NAME = "gemma-unsloth" # This must match the name used in `ollama create` in run.sh
|
8 |
+
|
9 |
+
def generate_text(prompt, max_new_tokens=256, temperature=0.7):
|
10 |
+
"""
|
11 |
+
Function to send a prompt to the Ollama API and get a response.
|
12 |
+
"""
|
13 |
+
payload = {
|
14 |
+
"model": MODEL_NAME,
|
15 |
+
"prompt": prompt,
|
16 |
+
"stream": False, # We want the full response at once
|
17 |
+
"options": {
|
18 |
+
"num_predict": max_new_tokens,
|
19 |
+
"temperature": temperature,
|
20 |
+
}
|
21 |
+
}
|
22 |
+
try:
|
23 |
+
# Send a POST request to the Ollama API.
|
24 |
+
# Increased timeout for potentially slow CPU inference.
|
25 |
+
response = requests.post(OLLAMA_API_URL, json=payload, timeout=600) # 10 minutes timeout
|
26 |
+
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
|
27 |
+
result = response.json()
|
28 |
+
return result.get("response", "No response from model.")
|
29 |
+
except requests.exceptions.RequestException as e:
|
30 |
+
return f"Error communicating with Ollama: {e}"
|
31 |
+
|
32 |
+
# Create the Gradio interface
|
33 |
+
iface = gr.Interface(
|
34 |
+
fn=generate_text,
|
35 |
+
inputs=[
|
36 |
+
gr.Textbox(lines=5, label="Enter your prompt", placeholder="Type your message here..."),
|
37 |
+
gr.Slider(minimum=1, maximum=1024, value=256, label="Max New Tokens", info="Maximum number of tokens to generate."),
|
38 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.7, label="Temperature", info="Controls randomness in generation. Lower values are less random.")
|
39 |
+
],
|
40 |
+
outputs="text",
|
41 |
+
title=f"Ollama {MODEL_NAME} on Hugging Face Spaces (CPU-only)",
|
42 |
+
description="Interact with a Gemma 3.4B IT QAT GGUF model served by Ollama on CPU. Please be patient, as CPU inference can be slow."
|
43 |
+
)
|
44 |
+
|
45 |
+
# Launch the Gradio application
|
46 |
+
# server_name="0.0.0.0" makes it accessible from outside the container.
|
47 |
+
# server_port=7860 is the default port for Gradio apps on Hugging Face Spaces.
|
48 |
+
if __name__ == "__main__":
|
49 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|