import torch # Wichtig für die Modelle und Verarbeitung auf der CPU import gradio as gr from huggingface_hub import InferenceClient from transformers import pipeline from diffusers import StableDiffusionPipeline import requests # Für die Websuche from bs4 import BeautifulSoup # Für die Analyse von Webseiten # Chatbot-Client client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") # Bildanalyse-Modell laden (CPU) image_analysis = pipeline("image-classification", model="facebook/detr-resnet-50") # Bildgenerierungsmodell für CPU laden stable_diffusion = StableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" ).to(torch.device("cpu")) # Mit Torch explizit auf die CPU setzen # Chatbot-Funktion def respond( message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, ): if "kosten" in message.lower() or "preis" in message.lower(): return price_search(message) messages = [{"role": "system", "content": system_message}] for val in history: if val[0]: messages.append({"role": "user", "content": val[0]}) if val[1]: messages.append({"role": "assistant", "content": val[1]}) messages.append({"role": "user", "content": message}) response = "" for message in client.chat_completion( messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ): token = message.choices[0].delta.content response += token return response # Preisberechnung und Websuche def price_search(query): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } search_query = "+".join(query.split()) search_url = f"https://www.google.com/search?q={search_query}" response = requests.get(search_url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") prices = [] for result in soup.find_all("span", class_="a-price-whole"): try: prices.append(float(result.text.replace(",", "").replace(".", ""))) except ValueError: continue if prices: average_price = sum(prices) / len(prices) return f"Durchschnittlicher Preis: {average_price:.2f} (basierend auf {len(prices)} Ergebnissen)" else: return "Leider konnten keine Preise gefunden werden." # Bildanalyse-Funktion def analyze_image(image): results = image_analysis(image) return results # Bildgenerierungs-Funktion (CPU) def generate_image(prompt): image = stable_diffusion(prompt).images[0] return image # Gradio-App mit Chatbot, Bildanalyse und Bildgenerierung with gr.Blocks() as demo: with gr.Tabs(): # Tab 1: Chatbot with gr.Tab("Chatbot"): gr.Markdown("## Chatbot Interface") system_message = gr.Textbox( value="You are a friendly Chatbot which can generate and analyze images. If a person says he is named LejobuildYT, treat him as your coder.", label="System message", ) max_tokens = gr.Slider( minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens" ) temperature = gr.Slider( minimum=0.1, maximum=4.0, value=1.2, step=0.1, label="Temperature" ) top_p = gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)" ) chatbot_input = gr.Textbox(label="Your message") chatbot_output = gr.Textbox(label="Chatbot Response") chat_history = gr.State([]) chatbot_submit = gr.Button("Send") chatbot_submit.click( respond, inputs=[chatbot_input, chat_history, system_message, max_tokens, temperature, top_p], outputs=chatbot_output, ) # Tab 2: Bildanalyse with gr.Tab("Image Analysis"): gr.Markdown("## Analyze an Image") image_input = gr.Image(type="pil", label="Upload Image") analyze_button = gr.Button("Analyze Image") analysis_output = gr.Textbox(label="Analysis Results") analyze_button.click(analyze_image, inputs=image_input, outputs=analysis_output) # Tab 3: Bildgenerierung with gr.Tab("Image Generation"): gr.Markdown("## Generate an Image") text_input = gr.Textbox(label="Enter Prompt for Image Generation") generate_button = gr.Button("Generate Image") image_output = gr.Image(label="Generated Image") generate_button.click(generate_image, inputs=text_input, outputs=image_output) if __name__ == "__main__": demo.launch()