Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import pipeline | |
| theme = gr.themes.ThemeClass.from_hub("mkill33/master_chief") | |
| image_classifier = pipeline( | |
| "image-classification", | |
| model="google/vit-base-patch16-224" | |
| ) | |
| """" | |
| (Tried UI design code from google) | |
| import customtkinter as ctk | |
| # Set UX theme preferences | |
| ctk.set_appearance_mode("dark") # Modes: "System", "Dark", "Light" | |
| ctk.set_default_color_theme("blue") | |
| # Create the main window | |
| app = ctk.CTk() | |
| app.geometry("400x200") | |
| app.title("Modern Python UI") | |
| # Add a text label (UI element) | |
| label = ctk.CTkLabel(app, text="Hello, User!", font=("Arial", 20)) | |
| label.pack(pady=20) | |
| # Add an interactive button (UX element) | |
| def on_click(): | |
| label.configure(text="Button Clicked!") | |
| button = ctk.CTkButton(app, text="Click Me", command=on_click) | |
| button.pack(pady=10) | |
| # Run the application loop | |
| app.mainloop() | |
| import torch | |
| model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval() | |
| import requests | |
| from PIL import Image | |
| from torchvision import transforms | |
| # Download human-readable labels for ImageNet. | |
| response = requests.get("https://git.io/JJkYN") | |
| labels = response.text.split("\n") | |
| def predict(inp): | |
| inp = transforms.ToTensor()(inp).unsqueeze(0) | |
| with torch.no_grad(): | |
| prediction = torch.nn.functional.softmax(model(inp)[0], dim=0) | |
| confidences = {labels[i]: float(prediction[i]) for i in range(1000)} | |
| return confidences | |
| gr.Interface(fn=predict, | |
| inputs=gr.Image(type="pil"), | |
| outputs=gr.Label(num_top_classes=3), | |
| examples=["lion.jpg", "cheetah.jpg"]).launch() | |
| """ | |
| from huggingface_hub import InferenceClient | |
| from sentence_transformers import SentenceTransformer | |
| client = InferenceClient("Qwen/Qwen2.5-7B-Instruct") | |
| with open("recycling_text.txt", "r", encoding="utf-8") as file: | |
| # Read the entire contents of the file and store it in a variable | |
| recycling_text = file.read() | |
| with open("aqi_text.txt", "r", encoding="utf-8") as file: | |
| # Read the entire contents of the file and store it in a variable | |
| aqi_text = file.read() | |
| #image_classifier = pipeline("image-classification", model="google/vit-base-patch16-224") | |
| def preprocess_text(text): | |
| # Strip extra whitespace from the beginning and the end of the text | |
| cleaned_text = text.strip() | |
| # Split the cleaned_text by every newline character (\n) | |
| chunks = cleaned_text.split("\n") | |
| # Create an empty list to store cleaned chunks | |
| cleaned_chunks = [] | |
| # Write your for-in loop below to clean each chunk and add it to the cleaned_chunks list | |
| for chunk in chunks: | |
| stripped_chunk = chunk.strip() | |
| if len(stripped_chunk) > 0: | |
| cleaned_chunks.append(stripped_chunk) | |
| return cleaned_chunks | |
| combined_text = recycling_text + "\n" + aqi_text | |
| cleaned_chunks = preprocess_text(combined_text) | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| def create_embeddings(text_chunks): | |
| chunk_embeddings = model.encode(text_chunks, convert_to_tensor=True) | |
| print(chunk_embeddings) | |
| # Print the shape of chunk_embeddings | |
| print(chunk_embeddings.shape) | |
| # Return the chunk_embeddings | |
| return chunk_embeddings | |
| # Call the create_embeddings function and store the result in a new chunk_embeddings variable | |
| chunk_embeddings = create_embeddings(cleaned_chunks) | |
| def get_top_chunks(query, chunk_embeddings, text_chunks): | |
| # Convert the query text into a vector embedding | |
| query_embedding = model.encode(query, convert_to_tensor=True) # Complete this line | |
| # Normalize the query embedding to unit length for accurate similarity comparison | |
| query_embedding_normalized = query_embedding / query_embedding.norm() | |
| # Normalize all chunk embeddings to unit length for consistent comparison | |
| chunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True) | |
| # Calculate cosine similarity between query and all chunks using matrix multiplication | |
| similarities = torch.matmul(chunk_embeddings_normalized,query_embedding_normalized) # Complete this line | |
| # Print the similarities | |
| print(similarities) | |
| # Find the indices of the 3 chunks with highest similarity scores | |
| top_indices = torch.topk(similarities, k=3).indices | |
| # Print the top indices | |
| print(top_indices) | |
| # Create an empty list to store the most relevant chunks | |
| top_chunks = [] | |
| # Loop through the top indices and retrieve the corresponding text chunks | |
| for i in top_indices: | |
| chunk=text_chunks[i] | |
| top_chunks.append(chunk) | |
| # Return the list of most relevant chunks | |
| return top_chunks | |
| def respond(message, history): | |
| messages = [{"role": "system", "content": "You are a friendly chatbot."}] | |
| if history: | |
| messages.extend(history) | |
| messages.append({"role": "user", "content": message}) | |
| response = client.chat_completion( | |
| messages, | |
| max_tokens=1000 | |
| ) | |
| return response.choices[0].message.content.strip() | |
| chatbot = gr.ChatInterface(respond, type="messages") | |
| def classify_image(image): | |
| if image is None: | |
| return "Upload an image" | |
| results=image_classifier(image) | |
| output="" | |
| for result in results[:3]: | |
| label=result["label"] | |
| score=round(result["score"]*100,2) | |
| output += f"{label}: {score}%\n" | |
| return output | |
| with gr.Blocks(theme=theme) as chatbot: | |
| gr.Image(value="enviff.png", show_label=False, interactive=False) | |
| with gr.Tab("Chatbot"): | |
| gr.ChatInterface(respond, title="From Waste To Wisdom, From Air To Action.") | |
| with gr.Tab("Image Classifier"): | |
| image_input = gr.Image(type="pil") | |
| image_output = gr.Textbox() | |
| classify_button = gr.Button("Classify Image") | |
| classify_button.click( | |
| fn=classify_image, | |
| inputs=image_input, | |
| outputs=image_output | |
| ) | |
| chatbot.launch() |