import gradio as gr
from googlesearch import search
import requests
from bs4 import BeautifulSoup
from gradio_client import Client
import groq

api_key = os.getenv('groq')
client = groq.Client(api_key=api_key)

def llm(message):   
    try:        
        completion = client.chat.completions.create(
            model="Mixtral-8x7b-32768",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": f"{message}. antworte immer auf deutsch"}
            ],
        )       
        return completion.choices[0].message.content
    except Exception as e:
        return f"Error in response generation: {str(e)}"

def google_search(query):       
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    }    
    # Führt die Suche durch und erhält das erste Ergebnis
    for result in search(query, num_results=1):
        url = result
        break
        
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')  
    #first_div = soup.find('div', class_='MjjYud')
    first_div = soup.find('body')
    
    return first_div.text.strip()

demo = gr.Interface(
    fn=google_search,
    inputs=gr.Textbox(lines=1, placeholder="Geben Sie Ihre Suchanfrage ein..."),
    #outputs="text",
    outputs=gr.Markdown(),
    title="google websearch",
    description="Geben Sie eine Suchanfrage ein..."
)

demo.launch()