import gradio as gr
import subprocess
import re
import tempfile
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 save HTML and return a file path
def save_html_file(response):
    if "```html" in response.lower():
        match = re.search(r'```html\n(.*?)```', response, re.DOTALL)
        if match:
            html_content = match.group(1).strip()
        else:
            return None
    elif response.strip().lower().startswith("<!doctype html>") or "<html" in response.lower():
        html_content = response
    else:
        return None

    temp_file_path = os.path.join(tempfile.gettempdir(), "output.html")
    with open(temp_file_path, "w", encoding="utf-8") as temp_file:
        temp_file.write(html_content)
    
    return temp_file_path

# Gradio Interface
def generate_response(prompt, model):
    return run_ollama_prompt(prompt, model)

def generate_html_download(response):
    file_path = save_html_file(response)
    if file_path:
        return file_path
    return None

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")
    
    response_output = gr.Textbox(label="Response", interactive=False)

    with gr.Row():
        html_download = gr.File(label="Download HTML File")
        html_preview_button = gr.Button("Generate HTML File")

    submit_button.click(fn=generate_response, inputs=[prompt_input, model_selector], outputs=response_output)
    html_preview_button.click(fn=generate_html_download, inputs=response_output, outputs=html_download)

app.launch()
