ankanpy commited on
Commit
fffe03d
·
verified ·
1 Parent(s): 31ed265

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +48 -0
  2. app.py +280 -0
  3. requirements.txt +1 -0
  4. startup.sh +65 -0
Dockerfile ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Base Image
2
+ FROM python:3.11-slim
3
+
4
+ # Set the volume for Ollama data
5
+ # This is where Ollama will store its models and data
6
+ # VOLUME /root/.ollama
7
+
8
+ # 2. Set Environment Variables
9
+ ENV PYTHONUNBUFFERED=1
10
+ ENV GRADIO_SERVER_NAME="0.0.0.0"
11
+ ENV OLLAMA_HOST="0.0.0.0:11434"
12
+
13
+ # 3. Set Working Directory
14
+ WORKDIR /app
15
+
16
+ # 4. Install System Dependencies
17
+ RUN apt-get update && \
18
+ apt-get install -y --no-install-recommends \
19
+ curl \
20
+ ca-certificates \
21
+ && rm -rf /var/lib/apt/lists/*
22
+
23
+ # 5. Install Ollama
24
+ RUN curl -fsSL https://ollama.com/install.sh | sh
25
+
26
+ # 6. Copy Application Requirements
27
+ COPY requirements.txt .
28
+
29
+ # 7. Install Python Dependencies
30
+ RUN pip install --no-cache-dir -r requirements.txt
31
+
32
+ # 8. Copy Your Application Code
33
+ COPY app.py .
34
+ COPY startup.sh .
35
+
36
+ # 9. Define Models to Pull (as an Argument with a default list)
37
+ ARG OLLAMA_PULL_MODELS="qwen3:4b qwen3:1.7b qwen3:0.6b" # Default models if not overridden
38
+
39
+ # Make the ARG available as an ENVironment variable for startup.sh
40
+ ENV OLLAMA_PULL_MODELS=${OLLAMA_PULL_MODELS}
41
+
42
+ # 10. Expose Ports
43
+ EXPOSE 11434
44
+ EXPOSE 7860
45
+
46
+ # 11. Entrypoint/Startup Script - NOW USING EXEC FORM FOR THE SCRIPT
47
+ # CMD ["./startup.sh"] # <-- CHANGE TO THIS
48
+ ENTRYPOINT ["./startup.sh"]
app.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import time
4
+
5
+ # import os # Not strictly needed in *this* version of app.py as no env vars are read
6
+
7
+ # --- Ollama Helper Functions ---
8
+
9
+
10
+ def check_ollama_running():
11
+ """Checks if the Ollama service is accessible."""
12
+ try:
13
+ subprocess.run(["ollama", "ps"], check=True, capture_output=True, timeout=5)
14
+ return True
15
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
16
+ return False
17
+
18
+
19
+ def get_ollama_models():
20
+ """Gets a list of locally available Ollama models."""
21
+ # Removed the 'if not check_ollama_running(): return []'
22
+ # because it's called after AVAILABLE_MODELS is determined,
23
+ # and check_ollama_running is implicitly done by the initial AVAILABLE_MODELS load.
24
+ # However, in a container, Ollama should be running.
25
+ try:
26
+ result = subprocess.run(["ollama", "list"], check=True, capture_output=True, text=True, timeout=10)
27
+ models = []
28
+ lines = result.stdout.strip().split("\n")
29
+ if len(lines) > 1:
30
+ for line in lines[1:]:
31
+ parts = line.split()
32
+ if parts:
33
+ models.append(parts[0])
34
+ # Ensure models are sorted and unique for consistent dropdown
35
+ return sorted(list(set(models)))
36
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired) as e:
37
+ print(f"Error in get_ollama_models: {e}") # Added a print for debugging
38
+ return []
39
+
40
+
41
+ # --- Core Logic ---
42
+
43
+ # Typing speed simulation
44
+ CHAR_DELAY = 0.02 # Adjust for desired speed (0.01 is fast, 0.05 is slower)
45
+
46
+
47
+ def reasoning_ollama_stream(model_name, prompt, mode): # Renamed prompt_text back to prompt
48
+ """
49
+ Streams response from an Ollama model with simulated typing speed.
50
+ """
51
+ if not model_name:
52
+ yield "Error: No model selected. Please choose a model."
53
+ return
54
+ if not prompt.strip(): # Using original 'prompt' variable name
55
+ yield "Error: Prompt cannot be empty."
56
+ return
57
+
58
+ # This check is good for robustness, even in Docker.
59
+ if not check_ollama_running():
60
+ yield "Error: Ollama service does not seem to be running or accessible. Please start Ollama."
61
+ return
62
+
63
+ # This is a runtime check. The Dockerfile aims to pull models, but this confirms.
64
+ available_models_runtime = get_ollama_models()
65
+ if model_name not in available_models_runtime:
66
+ yield f"Error: Model '{model_name}' selected, but not found by Ollama at runtime. Available: {available_models_runtime}. Please ensure it was pulled."
67
+ return
68
+
69
+ # Using original 'prompt' and 'mode'
70
+ prompt_with_mode = f"{prompt.strip()} /{mode}"
71
+ command = ["ollama", "run", model_name]
72
+
73
+ displayed_response = ""
74
+ try:
75
+ process = subprocess.Popen(
76
+ command,
77
+ stdin=subprocess.PIPE,
78
+ stdout=subprocess.PIPE,
79
+ stderr=subprocess.PIPE,
80
+ text=True,
81
+ bufsize=1,
82
+ universal_newlines=True,
83
+ )
84
+
85
+ process.stdin.write(prompt_with_mode + "\n")
86
+ process.stdin.close()
87
+
88
+ for line_chunk in iter(process.stdout.readline, ""):
89
+ if not line_chunk and process.poll() is not None: # Check if process ended
90
+ break
91
+ for char in line_chunk:
92
+ displayed_response += char
93
+ yield displayed_response
94
+ if char.strip(): # Only sleep for non-whitespace characters
95
+ time.sleep(CHAR_DELAY)
96
+
97
+ process.stdout.close()
98
+ return_code = process.wait(timeout=10) # Added timeout to wait
99
+
100
+ if return_code != 0:
101
+ error_output = process.stderr.read()
102
+ error_message = f"\n\n--- Ollama Error (code {return_code}) ---\n{error_output.strip()}"
103
+ if displayed_response and not displayed_response.endswith(error_message):
104
+ displayed_response += error_message
105
+ elif not displayed_response:
106
+ displayed_response = error_message.strip()
107
+ yield displayed_response
108
+ return
109
+
110
+ if not displayed_response.strip() and return_code == 0:
111
+ yield "Model returned an empty response."
112
+ elif displayed_response:
113
+ yield displayed_response
114
+
115
+ except FileNotFoundError:
116
+ yield "Error: 'ollama' command not found. Please ensure Ollama is installed and in your PATH (or Dockerfile is correct)."
117
+ except subprocess.TimeoutExpired: # Catch timeout from process.wait()
118
+ yield "Error: Ollama process timed out while waiting for completion."
119
+ if displayed_response:
120
+ yield displayed_response
121
+ except Exception as e:
122
+ yield f"An unexpected error occurred: {str(e)}"
123
+ if displayed_response:
124
+ yield displayed_response
125
+
126
+
127
+ # --- Gradio UI ---
128
+
129
+ # This runs once when the script starts.
130
+ # In Docker, this will query the Ollama instance inside the container AFTER models are pulled by CMD.
131
+ AVAILABLE_MODELS = get_ollama_models()
132
+ QWEN_MODELS = [m for m in AVAILABLE_MODELS if "qwen" in m.lower()]
133
+ INITIAL_MODEL = None
134
+
135
+ # Prioritize qwen3:4b if available - This logic is from your original app.py
136
+ if "qwen3:4b" in AVAILABLE_MODELS:
137
+ INITIAL_MODEL = "qwen3:4b"
138
+ elif QWEN_MODELS:
139
+ INITIAL_MODEL = QWEN_MODELS[0]
140
+ elif AVAILABLE_MODELS:
141
+ INITIAL_MODEL = AVAILABLE_MODELS[0]
142
+ # If no models, INITIAL_MODEL remains None, and dropdown will show "No models found..."
143
+
144
+ with gr.Blocks(title="Qwen3 x Ollama", theme=gr.themes.Soft()) as demo:
145
+ gr.HTML(
146
+ """
147
+ <h1 style='text-align: center'>
148
+ Qwen3 Reasoning with Ollama
149
+ </h1>
150
+ """
151
+ )
152
+ gr.HTML(
153
+ """
154
+ <h3 style='text-align: center'>
155
+ <a href='https://opencv.org/university/' target='_blank'>OpenCV Courses</a> | <a href='https://github.com/OpenCV-University' target='_blank'>Github</a>
156
+ </h3>
157
+ """
158
+ )
159
+ gr.Markdown(
160
+ """
161
+ - Interact with a Qwen3 model hosted on Ollama.
162
+ - Switch between `/think` and `/no_think` modes to explore the thinking process.
163
+ - The response will stream with a simulated typing effect.
164
+ """
165
+ )
166
+
167
+ with gr.Row():
168
+ with gr.Column(scale=1):
169
+ model_selector = gr.Dropdown(
170
+ label="Select Model",
171
+ choices=AVAILABLE_MODELS if AVAILABLE_MODELS else ["No models found - check Ollama setup"],
172
+ value=INITIAL_MODEL,
173
+ interactive=True,
174
+ )
175
+ prompt_input = gr.Textbox(
176
+ label="Enter your prompt",
177
+ placeholder="e.g., Explain quantum entanglement in simple terms.",
178
+ lines=5,
179
+ elem_id="prompt-input",
180
+ )
181
+ mode_radio = gr.Radio(
182
+ ["think", "no_think"], # Kept original modes from your app.py
183
+ label="Reasoning Mode",
184
+ value="think",
185
+ info="`/think` encourages step-by-step reasoning. `/no_think` aims for a direct answer.",
186
+ )
187
+ with gr.Row():
188
+ submit_button = gr.Button("Generate Response", variant="primary")
189
+ clear_button = gr.ClearButton()
190
+
191
+ with gr.Column(scale=2):
192
+ status_output = gr.Textbox(
193
+ label="Status",
194
+ interactive=False,
195
+ lines=1,
196
+ placeholder="Awaiting submission...",
197
+ elem_id="status-output",
198
+ )
199
+ response_output = gr.Textbox( # Kept as gr.Textbox as requested
200
+ label="Model Response", lines=20, interactive=False, show_copy_button=True, elem_id="response-output"
201
+ )
202
+
203
+ def handle_submit_wrapper(model, prompt, mode):
204
+ yield {status_output: "Processing... Preparing to stream response.", response_output: ""}
205
+
206
+ final_chunk = ""
207
+ # Using original variable names 'prompt' and 'mode' for reasoning_ollama_stream
208
+ for chunk in reasoning_ollama_stream(model, prompt, mode):
209
+ final_chunk = chunk
210
+ yield {status_output: "Streaming response...", response_output: chunk}
211
+
212
+ if "Error:" in final_chunk or "--- Ollama Error ---" in final_chunk:
213
+ yield {status_output: "Completed with issues.", response_output: final_chunk}
214
+ elif "Model returned an empty response." in final_chunk:
215
+ yield {status_output: "Model returned an empty response.", response_output: final_chunk}
216
+ elif not final_chunk.strip() and ("Error:" not in final_chunk and "--- Ollama Error ---" not in final_chunk):
217
+ yield {status_output: "Completed, but no substantive output received.", response_output: ""}
218
+ else:
219
+ yield {status_output: "Response generated successfully!", response_output: final_chunk}
220
+
221
+ submit_button.click(
222
+ fn=handle_submit_wrapper,
223
+ inputs=[model_selector, prompt_input, mode_radio],
224
+ outputs=[status_output, response_output],
225
+ )
226
+ clear_button.add([prompt_input, response_output, status_output])
227
+
228
+ # Example model determination logic from your original app.py
229
+ # Note: This might select a model not actually available if AVAILABLE_MODELS is empty
230
+ # and the fallback "qwen3:4b" is used.
231
+ # A safer approach is to ensure example_model is from AVAILABLE_MODELS if possible.
232
+ example_model_for_ui = INITIAL_MODEL
233
+ if not example_model_for_ui and AVAILABLE_MODELS:
234
+ example_model_for_ui = AVAILABLE_MODELS[0]
235
+ elif not example_model_for_ui: # Fallback if no models and INITIAL_MODEL is None
236
+ example_model_for_ui = "qwen3:4b" # Default example model
237
+
238
+ gr.Examples(
239
+ examples=[
240
+ [example_model_for_ui, "What are the main pros and cons of using nuclear energy?", "think"],
241
+ # Fallback for the second example if qwen3:4b isn't a primary choice
242
+ [
243
+ (
244
+ example_model_for_ui
245
+ if example_model_for_ui != "qwen3:4b"
246
+ else (INITIAL_MODEL if INITIAL_MODEL and INITIAL_MODEL != "qwen3:4b" else "qwen3:1.7b")
247
+ ),
248
+ "Write a short poem about a rainy day.",
249
+ "no_think",
250
+ ],
251
+ [example_model_for_ui, "Plan a 3-day trip to Paris, focusing on historical sites.", "think"],
252
+ ],
253
+ inputs=[model_selector, prompt_input, mode_radio],
254
+ outputs=[status_output, response_output],
255
+ fn=handle_submit_wrapper,
256
+ cache_examples=False, # Cache examples can be True if inputs are static and fn is pure
257
+ )
258
+ gr.HTML(
259
+ """
260
+ <h3 style='text-align: center'>
261
+ Developed with ❤️ by OpenCV
262
+ </h3>
263
+ """
264
+ )
265
+
266
+ if __name__ == "__main__":
267
+ print("--- Gradio App Starting ---") # Simplified print
268
+ print(f"Attempting to fetch Ollama models (initial load)... Result: {AVAILABLE_MODELS}")
269
+ print(f"Initial model for UI (if any): {INITIAL_MODEL}")
270
+ print(f"Gradio version: {gr.__version__}")
271
+ print(f"---------------------------")
272
+
273
+ # For local Docker testing, server_name="0.0.0.0" is important.
274
+ # For Hugging Face Spaces, demo.launch() is usually enough as it handles proxying.
275
+ demo.queue().launch(
276
+ server_name="0.0.0.0",
277
+ server_port=7860,
278
+ share=False, # Set to True if you need a public link for local testing (requires internet)
279
+ # share=os.getenv("GRADIO_SHARE", "False").lower() == "true" # If using env var for share
280
+ )
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio==5.31.0
startup.sh ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # startup.sh
3
+
4
+ set -e # Exit immediately if a command exits with a non-zero status.
5
+
6
+ echo "Starting Ollama server in the background..."
7
+ ollama serve > /tmp/ollama.log 2>&1 &
8
+ OLLAMA_PID=$! # Get PID of the backgrounded ollama serve
9
+
10
+ echo "Waiting for Ollama to be ready (http://127.0.0.1:11434)..."
11
+ timeout_seconds=120
12
+ start_time=$(date +%s)
13
+ while ! curl -s --fail -o /dev/null http://127.0.0.1:11434; do
14
+ current_time=$(date +%s)
15
+ elapsed_time=$((current_time - start_time))
16
+ if [ "$elapsed_time" -ge "$timeout_seconds" ]; then
17
+ echo "Ollama failed to start within $timeout_seconds seconds. Check /tmp/ollama.log."
18
+ cat /tmp/ollama.log
19
+ exit 1
20
+ fi
21
+ echo -n "."
22
+ sleep 2
23
+ done
24
+ echo ""
25
+ echo "Ollama server started successfully."
26
+
27
+ # OLLAMA_PULL_MODELS will be passed as an environment variable from Dockerfile
28
+ echo "Models to pull from ENV: ${OLLAMA_PULL_MODELS}"
29
+
30
+ for model_name in ${OLLAMA_PULL_MODELS}; do
31
+ echo "Pulling model: ${model_name} (this may take several minutes)..."
32
+ ollama pull "${model_name}"
33
+ if [ $? -eq 0 ]; then
34
+ echo "Model ${model_name} pulled successfully."
35
+ else
36
+ echo "Failed to pull model ${model_name}. Check logs or model name."
37
+ fi
38
+ done
39
+
40
+ # Define a function to clean up (stop Ollama) when the script exits
41
+ cleanup() {
42
+ echo "Caught signal, shutting down Ollama (PID: $OLLAMA_PID)..."
43
+ if kill -0 $OLLAMA_PID > /dev/null 2>&1; then # Check if process exists
44
+ kill $OLLAMA_PID
45
+ wait $OLLAMA_PID # Wait for Ollama to actually terminate
46
+ echo "Ollama shut down."
47
+ else
48
+ echo "Ollama process (PID: $OLLAMA_PID) not found or already stopped."
49
+ fi
50
+ }
51
+
52
+ # Trap signals to call the cleanup function
53
+ # SIGINT is Ctrl+C, SIGTERM is `docker stop`
54
+ trap cleanup SIGINT SIGTERM
55
+
56
+ echo "Starting Gradio application (python app.py)..."
57
+ # Run python app.py in the foreground. It will now be PID 1 (or close to it)
58
+ # relative to this script, and signals will be handled by this script.
59
+ python app.py &
60
+ PYTHON_APP_PID=$!
61
+
62
+ wait $PYTHON_APP_PID # Wait for the python app to exit
63
+ # After python app exits, perform cleanup (this will also be called by trap)
64
+ cleanup
65
+ echo "Gradio application exited."