Manishkumaryadav commited on
Commit
f0f34af
Β·
verified Β·
1 Parent(s): 901523e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -56
app.py CHANGED
@@ -1,70 +1,85 @@
1
  import gradio as gr
2
- import os
3
- import spacy
4
- import torch
5
- from transformers import pipeline
6
- import speech_recognition as sr
7
- from gtts import gTTS
8
- import tempfile
9
- import base64
10
 
11
- # Install required Spacy model
12
- os.system("python -m spacy download en_core_web_sm")
13
- nlp = spacy.load("en_core_web_sm")
 
14
 
15
- # Load Hugging Face model (Example: Bloom or other LLM from Hugging Face)
16
- chat_model = pipeline("text-generation", model="bigscience/bloom-560m")
 
 
17
 
18
- # Speech-to-Text function
19
- def transcribe_audio(audio_path):
20
- recognizer = sr.Recognizer()
21
- with sr.AudioFile(audio_path) as source:
22
- audio_data = recognizer.record(source)
23
- try:
24
- return recognizer.recognize_google(audio_data)
25
- except sr.UnknownValueError:
26
- return "Could not understand the audio."
27
 
28
- # AI Chat Response
29
- def chat_with_ai(user_input):
30
- response = chat_model(user_input, max_length=150, do_sample=True, temperature=0.7)
31
- return response[0]['generated_text']
32
 
33
- # Text-to-Speech function
34
- def generate_speech(text):
35
- tts = gTTS(text=text, lang='en')
36
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
37
- tts.save(temp_file.name)
38
- with open(temp_file.name, "rb") as audio_file:
39
- encoded_audio = base64.b64encode(audio_file.read()).decode("utf-8")
40
- os.unlink(temp_file.name)
41
- return encoded_audio
42
 
43
- # Chat Interface
44
- def chat_interface(user_input, audio_file=None):
45
- if audio_file is not None:
46
- user_input = transcribe_audio(audio_file)
47
 
48
- ai_response = chat_with_ai(user_input)
49
- audio_response = generate_speech(ai_response)
50
 
51
- return ai_response, f"data:audio/mp3;base64,{audio_response}"
 
 
 
 
 
 
52
 
53
- # Create Gradio UI
54
- gui = gr.Interface(
55
- fn=chat_interface,
56
- inputs=[
57
- gr.Textbox(lines=2, placeholder="Type your message here..."),
58
- gr.Audio(sources=["microphone", "upload"], type="filepath")
 
 
 
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  ],
61
- outputs=[
62
- gr.Textbox(label="AI Response"),
63
- gr.Audio(label="AI Voice Response")
64
- ],
65
- title="AI Chat Assistant",
66
- description="An AI-powered chat assistant with text & voice input/output.",
67
- theme="huggingface"
68
  )
69
 
70
- gui.launch()
 
 
1
  import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration, M2M100ForConditionalGeneration, M2M100Tokenizer
5
+ from datasets import load_dataset
6
+ from deep_translator import GoogleTranslator
 
 
 
7
 
8
+ # Load Chatbot (BlenderBot 3B)
9
+ model_name = "facebook/blenderbot-3B"
10
+ tokenizer = BlenderbotTokenizer.from_pretrained(model_name)
11
+ chatbot_model = BlenderbotForConditionalGeneration.from_pretrained(model_name)
12
 
13
+ # Load Translation Model (Multilingual)
14
+ translate_model_name = "facebook/m2m100_418M"
15
+ translate_tokenizer = M2M100Tokenizer.from_pretrained(translate_model_name)
16
+ translate_model = M2M100ForConditionalGeneration.from_pretrained(translate_model_name)
17
 
18
+ # Load Hugging Face Dataset (Amazon Reviews)
19
+ dataset = load_dataset("amazon_us_reviews", split="train")
20
+ df = pd.DataFrame(dataset)
 
 
 
 
 
 
21
 
22
+ # Keep necessary columns
23
+ df = df[["product_category", "product_title", "star_rating", "review_body"]].dropna()
24
+ df["star_rating"] = df["star_rating"].astype(float)
 
25
 
26
+ # Function to translate text
27
+ def translate_text(text, target_lang="en"):
28
+ if target_lang == "en":
29
+ return text # No translation needed for English
30
+ inputs = translate_tokenizer(text, return_tensors="pt", src_lang="en")
31
+ translated_tokens = translate_model.generate(**inputs, forced_bos_token_id=translate_tokenizer.get_lang_id(target_lang))
32
+ return translate_tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)[0]
 
 
33
 
34
+ # Function to recommend products based on user input with filters
35
+ def recommend_products(user_query, min_rating=3.5):
36
+ keywords = user_query.lower().split()
 
37
 
38
+ # Filter based on keywords & minimum rating
39
+ recommended = df[(df["product_category"].str.lower().isin(keywords)) & (df["star_rating"] >= min_rating)]
40
 
41
+ if recommended.empty:
42
+ return "No recommendations found. Try searching for 'Electronics', 'Books', or 'Beauty products'."
43
+
44
+ # Sort by highest rating
45
+ recommended = recommended.sort_values(by="star_rating", ascending=False).head(5)
46
+
47
+ return recommended[["product_title", "star_rating"]].to_string(index=False)
48
 
49
+ # Chatbot Response Function with improved answers
50
+ def chatbot_response(user_input, language="en", min_rating=3.5):
51
+ # Translate input if not in English
52
+ if language != "en":
53
+ user_input = translate_text(user_input, target_lang="en")
54
+
55
+ # Generate chatbot response
56
+ inputs = tokenizer([user_input], return_tensors="pt")
57
+ reply_ids = chatbot_model.generate(**inputs, max_length=100)
58
+ response = tokenizer.decode(reply_ids[0], skip_special_tokens=True)
59
 
60
+ # Get product recommendations
61
+ recommendations = recommend_products(user_input, min_rating)
62
+
63
+ # Translate output if needed
64
+ if language != "en":
65
+ response = translate_text(response, target_lang=language)
66
+ recommendations = translate_text(recommendations, target_lang=language)
67
+
68
+ return f"πŸ€– AI: {response}\n\nπŸ” Recommended Products:\n{recommendations}"
69
+
70
+ # Gradio UI with Filters & Multi-Language
71
+ iface = gr.Interface(
72
+ fn=chatbot_response,
73
+ inputs=[
74
+ gr.Textbox(label="Ask me about products!"),
75
+ gr.Dropdown(["en", "es", "fr", "de", "hi"], label="Language", value="en"), # Supports English, Spanish, French, German, Hindi
76
+ gr.Slider(1, 5, value=3.5, step=0.5, label="Minimum Star Rating")
77
  ],
78
+ outputs="text",
79
+ title="πŸ›οΈ AI Shopping Assistant",
80
+ description="Chat with an AI to get product recommendations with filters & multilingual support!",
81
+ theme="default"
 
 
 
82
  )
83
 
84
+ # Launch the App
85
+ iface.launch()