import gradio as gr
import subprocess
import re
import tempfile
import webbrowser
import os

def run_ollama_prompt(prompt, model):
    """Runs a prompt using Ollama CLI and returns the response."""
    command = ["ollama", "run", model, prompt]

    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True, encoding="utf-8")
        response = result.stdout.strip()
        # Remove <think>...</think> tags if present
        response = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()
        return response
    except subprocess.CalledProcessError as e:
        return f"Error running Ollama: {e}"

# Function to handle HTML output
def save_and_open_html(response):
    if response.strip().lower().startswith("<!doctype html>") or "<html" in response.lower():
        with tempfile.NamedTemporaryFile(delete=False, suffix=".html", mode="w", encoding="utf-8") as temp_file:
            temp_file.write(response)
            temp_file_path = temp_file.name
        webbrowser.open(f"file://{temp_file_path}")
        return "HTML preview opened in a new tab."
    return "No valid HTML detected in the response."

# Gradio Interface
def generate_response(prompt, model):
    return run_ollama_prompt(prompt, model)

models = ["deepseek-r1:1.5b", "deepseek-r1:14b", "deepseek-r1:32b", "phi4:latest", "llama2:7b"]

with gr.Blocks() as app:
    gr.Markdown("# Ollama Chat App")
    
    with gr.Row():
        model_selector = gr.Dropdown(models, label="Select Model", value="deepseek-r1:1.5b")
    
    with gr.Row():
        prompt_input = gr.Textbox(label="Enter your prompt", placeholder="Type something...")
    
    with gr.Row():
        submit_button = gr.Button("Generate Response")
        html_preview_button = gr.Button("Open HTML Preview")
    
    response_output = gr.Textbox(label="Response", interactive=False)
    
    submit_button.click(fn=generate_response, inputs=[prompt_input, model_selector], outputs=response_output)
    html_preview_button.click(fn=save_and_open_html, inputs=response_output, outputs=response_output)

app.launch()