Spaces:
Build error
Build error
| import gradio as gr | |
| import requests | |
| import json | |
| from sentence_transformers import SentenceTransformer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| import numpy as np | |
| # API configuration | |
| API_URL = "https://subham9126-hfflow.hf.space/api/v1/prediction/ca481ff1-baa3-499c-9416-453edcdc391c" | |
| # Load a pre-trained sentence transformer model | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| # Sample data (replace with your actual data) | |
| data = [{"id": "ADDRESS CONFIRMATION", "description": "This intent is designed to handle user requests related to verifying or confirming their delivery address. This includes users asking to see their delivery address, or confirming its accuracy. The intent captures various ways users might phrase their need to ensure their address details are correct for delivery purposes."}, {"id": "BANK ACCOUNT RELATED", "description": "This intent is focused on user requests related to bank account verification and management. It includes users expressing issues or questions about their bank accounts."}, {"id": "FLIPKART ACCOUNT RELATED", "description": "This intent pertains to user queries/requests regarding their Flipkart accounts."}, {"id": "PLACE NEW ORDER", "description": "This intent captures the user's desire to initiate a purchase or reorder a product. This includes scenarios where the user expresses difficulty in placing an order, requests assistance with the ordering process, or directly states their intention to buy a specific item."}, {"id": "ORDER PENDING/ON HOLD", "description": "This intent addresses customer inquiries and concerns regarding the status of their orders that are currently pending or on hold."}, {"id": "NEGATIVE CUSTOMER SENTIMENT/FEEDBACK", "description": "This intent captures negative customer sentiments and feedback related to their experiences with Flipkart's services and products."}, {"id": "POSITIVE CUSTOMER SENTIMENT/FEEDBACK", "description": "This intent captures positive customer sentiments and feedbacks related to their experiences with Flipkart's services and products."}, {"id": "COMPLAINT/ESCALATION", "description": "The intent is to express desire to file a formal complaint or escalation. The customers mention various avenues for lodging the complaint, including contacting the office, police, consumer court."}, {"id": "PII VALUE", "description": "The intent collects personal identifiable information (PII), specifically phone numbers, postal PIN codes, and other defined PII values, without other context."}, {"id": "CALL CONNECTION/DISCONNECTION ISSUES", "description": "This intent encompasses various scenarios where customers face difficulties in connecting to or maintaining a call with an agent. This includes instances where the call is cut off by the agent, the number is unreachable, switched off, or not working, and situations where the call gets disconnected or is rejected automatically."}, {"id": "ORDER RECEIVED", "description": "This intent encompasses scenarios where the user mentions, directly or indirectly, that they have received their order."}, {"id": "APOLOGY", "description": "This intent captures user\u2019s intent to apologize"}, {"id": "LANGUAGE SPECIFICATION/PREFERENCE", "description": "This intent captures the user's preference for communication in a specific language."}, {"id": "UPLOAD MEDIA", "description": "This intent involves users experiencing difficulties or seeking assistance with uploading images or photos. Users may need to upload pictures for various reasons, such as product verification, customer care requests,and so on. Common issues include error messages, non-functional upload links, and general confusion about the upload process."}, {"id": "SPECIFIC_DATE_TIME", "description": "Requests where customer asks for \ndelivery on a specific date/time. The date/ time could be before or after a specific date/time."}, {"id": "STATUS_CHECK_EARLY_DELIVERY", "description": "Requests where the customer is asking for faster delivery without specifying any date/time"}, {"id": "STATUS_CHECK", "description": "Requests where the customer is asking for the status of the order like when would it be delivered, or when would it be shipped."}, {"id": "DELAY_REPROMISE_REASON", "description": "Customer asking about why the re-promise in the delivery date was made. Or why the delivery date was changed."}, {"id": "DELAY_IN_DELIVERY", "description": "Customer asking why the order getting delayed"}, {"id": "FE_CALLBACK_REQUEST", "description": "Requests where the buyer is asking us to ask the FE to call them back."}, {"id": "FE_DETAILS_REQUIRED", "description": "Customer asking for details of the wishmaster"}, {"id": "DELIVERY_AGENT_ISSUES", "description": "Where the buyer is complaining/raising issues about the delivery agent."}, {"id": "DENY_DELIVERY_WM", "description": "Wishmaster/delivery agent denying delivery."}, {"id": "WISH_MASTER_NOT_RESPONDING", "description": "Delivery agent is not responding to the user's call."}, {"id": "VENDOR_DETAILS_REQUIRED", "description": "Customer wants to know the details of the courier partner shipping details and tracking id"}, {"id": "ADDRESS_CHANGE", "description": "Customer asking to update the delivery address"}, {"id": "REATTEMPT_OF_DELIVERY", "description": "Customer misses delivery/did not receive a call from FE/Receives update that delivery was attempted when it was not. Asking for a reattempt."}, {"id": "RESCHEDULE_REQUEST", "description": "Requests where the customer is asking to reschedule the delivery, without providing any specific date/time."}, {"id": "NO_PROGRESS", "description": "Customer is asking about no progress in the order status and is not being updated.Like it is in the nearest hub for few days . It is stuck in the same hub. It has not moved. It has not shipped."}, {"id": "PRODUCT_NOT_RECEIVED_BUT_SHOWS_DELIVERED", "description": "Customer hasn\u2019t received the order but the order status is delivered."}, {"id": "DELIVERY_CHARGES", "description": "Customer asking related to the delivery charges.\nwhy the delivery charge? why so high?, why in spite of being Flipkart plus?"}, {"id": "GIFT_WRAP", "description": "Customer asking that can the product can be gift wrapped/remove invoice/remove bill from the package"}, {"id": "INSTALLATION", "description": "Any installation related query (delay, timing, change of time etc)"}, {"id": "PRODUCT_RELATED_ENQUIRY", "description": "Customer asking queries related to product."}, {"id": "PRODUCT_SAFETY", "description": "Customer asking if receiving the product is safe due to COVID"}, {"id": "OUT_OF_STOCK", "description": "Customer asking about the stock status of the product."}, {"id": "WARRANTY", "description": "Customer queries related to the warranty of the product"}, {"id": "PRODUCT_REVIEW_RELATED", "description": "Customer wants to give review/feedback about a product."}, {"id": "PRICE_DROP_AFTER_PURCHASE", "description": "Queries about the price decrease after the customer has placed an order."}, {"id": "SERVICE_CENTRE_COMPLAINTS", "description": "Any queries or problems linked to service centers: how to find closest service center, service center denied or charged for service"}, {"id": "OFFERS", "description": "Customer asking about the offer details that could be availed and/or issues related to the offers."}, {"id": "ORDER_CANCELLATION", "description": "Customer requesting/asking for order cancellation."}, {"id": "CANCELLATION_REASON", "description": "Customer asking about the order cancellation reason from Flipkart/ Seller\u2019s end."}, {"id": "CANCEL_OPTION_UNAVAILABLE", "description": "Customer telling that there is no cancel option or asking why the cancel option is not coming."}, {"id": "REINSTATE_CANCELLED_ORDER", "description": "Customer asking for reinstating the canceled order."}, {"id": "RETURN_REQUEST", "description": "Product issue with damage/size/color. Customer directly/indirectly asking for a return."}, {"id": "REPLACEMENT_NOT_REFUND", "description": "Customer is explicitly saying that they want a refund and not replacement or replacement instead of refund (basically they are getting only one option in returning and they are not happy with that)."}, {"id": "RETURN_REQUEST_CANCELLATION", "description": "Customer asking for canceling the return request."}, {"id": "RETURN_REQUEST_REJECTION", "description": "Customer asking about why the return request had been canceled/rejected."}, {"id": "RETURN_POLICY_INFO_CANCELLATION", "description": "Customer is asking how many days return policy or what is the cancellation policy. This is customer looking for policy details"}, {"id": "RETURN_ADDRESS_CHANGE", "description": "Customer specifically mentions in text that they want to change the reverse pickup address or return address."}, {"id": "RETURN_AT_SPECIFIC_TIME", "description": "Customer mentions in text a specific time for the return."}, {"id": "RETURN_STATUS", "description": "Customer asking about the status of the return request. Only related to return request and not pickup."}, {"id": "PICKUP_STATUS", "description": "Customer is asking about the pickup status of the return."}, {"id": "PICKUP_DENIED", "description": "Customer mentioning that the pickup was denied by the wishmaster/delivery agent."}, {"id": "DELAY_IN_PICKUP", "description": "Customer mentioning that there was a delay in the pickup, or asking why is there delay in the pickup"}, {"id": "RETURN_OPTION_UNAVAILABLE", "description": "Customer telling that there is no return option or asking why the return option is not coming"}, {"id": "PREXO_RELATED", "description": "FE denied prexo, customer wants prexo but not applicable on phone etc"}, {"id": "TECH_VISIT", "description": "Any questions related to tech visit. When will it happen? Customers are waiting for it or they want to reschedule it etc."}, {"id": "REFUND_STATUS", "description": "Customer asking about the status of the refund amount for the order."}, {"id": "ORDER_PAYMENT_CONFIRMATION", "description": "Requests where the buyer is asking whether the payment was confirmed for the given order. This is not to be confused with order confirmation requests, which need to be tagged under Status Check."}, {"id": "ADONC", "description": "Customer asking queries related to the situation where the amount got debited but the order was not confirmed."}, {"id": "CHANGE_PAYMENT_MODE", "description": "Customers querying related to changing the payment mode."}, {"id": "CASH_ON_DELIVERY_RELATED", "description": "Questions related to COD."}, {"id": "PAY_LATER_RELATED", "description": "Any pay later related query: KYC, eligibility, blocked , limits etc"}, {"id": "CASHBACK", "description": "Queries related to CashBack."}, {"id": "EMI", "description": "Customers asking queries related to EMI options."}, {"id": "GIFTCARD", "description": "Any gift card related query: PIN, expiry, unable to apply etc"}, {"id": "PAYMENT_RELATED", "description": "Any payment related queries that doesn't come under Adonc, order payment confirmation, change payment mode, Paylater, COD, EMI, cashback"}, {"id": "CALL_ME_BACK", "description": "The customer is asking us to call them back . This is not to be confused with requests for FE number, or requests for the FE to call them"}, {"id": "AGENT_TRANSFER", "description": "Customer is asking to talk to the customer executive. Transfer to agent."}, {"id": "PHONE_NUMBER_UPDATE", "description": "Requests to update the phone number or add an alternate phone number (can be account or order related or just alternate number)"}, {"id": "INFO_CHANGE_EMAIL", "description": "Requests to update the email address of the customer"}, {"id": "CLEAR_ORDER_HISTORY", "description": "Customer asking for clearing the order history."}, {"id": "INVOICE", "description": "Any invoice related query (edit, send, download etc)"}, {"id": "GREETING", "description": "Greetings from the customer , Hello, Hi."}, {"id": "THANK_YOU", "description": "variations of thanks, tq, thank you etc"}, {"id": "ACKNOWLEDGEMENT", "description": "Yes,Ok,Done"}, {"id": "CONFIRMATION_OF_INFORMATION", "description": "The customer is confirming already provided information."}, {"id": "CUSTOMER_ABUSE", "description": "Abusive language used by customers. Cheats, fraud etc"}, {"id": "FLIPKART_WALLET_RELATED", "description": "Customers asking about Flipkart Wallet related queries."}, {"id": "FOLLOWUP_EXISTING_INCIDENT", "description": "Customer asking queries related to an existing incident."}, {"id": "HELP", "description": "customer says that he needs help, but doesn't specify exact issue."}, {"id": "NO_INTENT", "description": "Customer says \"No\", \"I don't want\" ."}, {"id": "ORDER_MODIFICATION", "description": "customer wants to add or remove item from an existing order."}, {"id": "OTP_ISSUES", "description": "Any OTP related query: did not get, want to change number to which it is sent etc"}, {"id": "SPOTIFY_RELATED", "description": "Spotify related queries."}, {"id": "SUPERCOIN", "description": "Super coins related queries."}, {"id": "YOUTUBE_PREMIUM_RELATED", "description": "Youtube premium related queries."}, {"id": "GIBBERISH", "description": "Random characters"}, {"id": "OTHERS", "description": "When the query cannot be tagged as any of the above 75 intents"}] | |
| # Precompute embeddings for all descriptions | |
| embeddings = model.encode([item['description'] for item in data]) | |
| def query_api(question, api_key): | |
| headers = {"Authorization": f"Bearer {api_key}"} | |
| payload = {"question": question} | |
| response = requests.post(API_URL, json=payload, headers=headers) | |
| return response.json() | |
| def similarity_search(query_embedding, top_k=5): | |
| similarities = cosine_similarity([query_embedding], embeddings)[0] | |
| top_indices = np.argsort(similarities)[-top_k:][::-1] | |
| return [data[i] for i in top_indices] | |
| def process_query(api_key, query): | |
| try: | |
| # Query the API | |
| api_response = query_api(query, api_key) | |
| # Extract the 'text' field from the API response | |
| response_text = api_response.get('text', 'No text found in API response') | |
| return response_text | |
| except Exception as e: | |
| return f"An error occurred: {str(e)}" | |
| def perform_similarity_search(edited_text): | |
| try: | |
| # Perform similarity search | |
| query_embedding = model.encode(edited_text) | |
| similar_items = similarity_search(query_embedding) | |
| # Prepare the output | |
| output = "Top 5 similar items:\n" | |
| for item in similar_items: | |
| output += f"ID: {item['id']}, Description: {item['description']}\n" | |
| return output | |
| except Exception as e: | |
| return f"An error occurred during similarity search: {str(e)}" | |
| # Create Gradio interface | |
| with gr.Blocks() as iface: | |
| gr.Markdown("# Query and Similarity Search") | |
| gr.Markdown("Enter your API key and a query to send to the API. You can then edit the response before performing a similarity search.") | |
| with gr.Row(): | |
| api_key_input = gr.Textbox(placeholder="Enter your API key here...", label="API Key") | |
| query_input = gr.Textbox(lines=2, placeholder="Enter your query here...", label="Query") | |
| query_button = gr.Button("Send Query to API") | |
| api_response_text = gr.Textbox(label="API Response (Editable)", lines=5) | |
| search_button = gr.Button("Perform Similarity Search") | |
| similarity_results = gr.Textbox(label="Similarity Search Results", lines=10) | |
| query_button.click(process_query, inputs=[api_key_input, query_input], outputs=api_response_text) | |
| search_button.click(perform_similarity_search, inputs=api_response_text, outputs=similarity_results) | |
| iface.launch() |