Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,53 +1,140 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
from google import generativeai as genai
|
3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
#
|
12 |
-
|
13 |
-
|
14 |
-
def chat_with_business(message, history):
|
15 |
-
# 1️⃣ Read business info
|
16 |
-
with open(business_file, "r", encoding="utf-8") as f:
|
17 |
-
business_info = f.read().strip()
|
18 |
-
|
19 |
-
# 2️⃣ Build system prompt
|
20 |
-
system_prompt = (
|
21 |
-
"You are a helpful customer-care assistant. "
|
22 |
-
"Use only the information below to answer questions. "
|
23 |
-
"If the answer is not present, reply 'Yeh information abhi available nahi hai.'\n\n"
|
24 |
-
f"{business_info}\n\n"
|
25 |
-
)
|
26 |
-
|
27 |
-
# 3️⃣ Call Gemini 2.5 Flash
|
28 |
-
model = genai.GenerativeModel(model_name="gemini-2.5-flash-preview-04-17")
|
29 |
-
response = model.generate_content(system_prompt + "User: " + message) # :contentReference[oaicite:3]{index=3}
|
30 |
-
|
31 |
-
# 4️⃣ Return text
|
32 |
-
return response.text
|
33 |
-
|
34 |
-
# — Build Gradio UI with Blocks and messages format
|
35 |
-
with gr.Blocks(theme="soft") as demo:
|
36 |
-
gr.Markdown("## 🌿 My Business Bot")
|
37 |
-
gr.Markdown("*Ask anything about your business in Hindi-English*")
|
38 |
-
chatbot = gr.Chatbot(elem_id="chatbox", height=400, type="messages") # use messages format :contentReference[oaicite:4]{index=4}
|
39 |
-
user_input = gr.Textbox(placeholder="Type your question here...", show_label=False)
|
40 |
-
|
41 |
-
def handle(msg, hist):
|
42 |
-
reply = chat_with_business(msg, hist)
|
43 |
-
# Append OpenAI-style dicts, not tuples :contentReference[oaicite:5]{index=5}
|
44 |
-
hist = hist + [
|
45 |
-
{"role": "user", "content": msg},
|
46 |
-
{"role": "assistant", "content": reply}
|
47 |
-
]
|
48 |
-
return hist, ""
|
49 |
-
|
50 |
-
user_input.submit(handle, [user_input, chatbot], [chatbot, user_input])
|
51 |
|
|
|
52 |
if __name__ == "__main__":
|
53 |
-
demo.launch()
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import hashlib
|
5 |
+
from functools import lru_cache
|
6 |
+
from docx import Document
|
7 |
+
import PyPDF2
|
8 |
+
import textract
|
9 |
+
|
10 |
+
# Check if the API key exists in environment variables
|
11 |
+
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
12 |
+
if not GROQ_API_KEY:
|
13 |
+
raise ValueError("GROQ_API_KEY not found in environment variables. Please add it to Hugging Face Secrets.")
|
14 |
+
|
15 |
+
# Function to generate hash of data directory contents
|
16 |
+
def get_data_hash():
|
17 |
+
data_dir = "data"
|
18 |
+
if not os.path.exists(data_dir):
|
19 |
+
return ""
|
20 |
+
hasher = hashlib.sha256()
|
21 |
+
try:
|
22 |
+
for root, dirs, files in os.walk(data_dir):
|
23 |
+
for file in sorted(files):
|
24 |
+
filepath = os.path.join(root, file)
|
25 |
+
if os.path.isfile(filepath):
|
26 |
+
with open(filepath, 'rb') as f:
|
27 |
+
hasher.update(f.read())
|
28 |
+
return hasher.hexdigest()
|
29 |
+
except Exception as e:
|
30 |
+
print(f"Error hashing files: {e}")
|
31 |
+
return ""
|
32 |
+
|
33 |
+
# Cache business info processing with hash-based invalidation
|
34 |
+
@lru_cache(maxsize=1)
|
35 |
+
def read_business_info(data_hash):
|
36 |
+
business_info = []
|
37 |
+
data_dir = "data"
|
38 |
+
|
39 |
+
if not os.path.exists(data_dir):
|
40 |
+
return "Data directory not found. Please upload a 'data' folder with relevant files."
|
41 |
+
|
42 |
+
supported_extensions = ['.txt', '.pdf', '.docx', '.doc']
|
43 |
+
|
44 |
+
for filename in os.listdir(data_dir):
|
45 |
+
filepath = os.path.join(data_dir, filename)
|
46 |
+
ext = os.path.splitext(filename)[1].lower()
|
47 |
+
|
48 |
+
if ext not in supported_extensions:
|
49 |
+
continue # Skip unsupported files
|
50 |
+
|
51 |
+
try:
|
52 |
+
if ext == '.txt':
|
53 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
54 |
+
business_info.append(f.read())
|
55 |
+
elif ext == '.pdf':
|
56 |
+
with open(filepath, 'rb') as f:
|
57 |
+
reader = PyPDF2.PdfReader(f)
|
58 |
+
text = '\n'.join([page.extract_text() for page in reader.pages])
|
59 |
+
business_info.append(text)
|
60 |
+
elif ext == '.docx':
|
61 |
+
doc = Document(filepath)
|
62 |
+
text = '\n'.join([para.text for para in doc.paragraphs])
|
63 |
+
business_info.append(text)
|
64 |
+
elif ext == '.doc':
|
65 |
+
text = textract.process(filepath).decode('utf-8')
|
66 |
+
business_info.append(text)
|
67 |
+
except Exception as e:
|
68 |
+
business_info.append(f"Error reading {filename}: {str(e)}")
|
69 |
+
|
70 |
+
if not business_info:
|
71 |
+
return "No valid files found in the data directory."
|
72 |
+
|
73 |
+
return '\n\n'.join(business_info)
|
74 |
+
|
75 |
+
# Function to generate response using Groq's LLaMA 3 70B API
|
76 |
+
def generate_response(message, chat_history):
|
77 |
+
current_hash = get_data_hash()
|
78 |
+
business_info = read_business_info(current_hash)
|
79 |
+
|
80 |
+
# Create system prompt including business information
|
81 |
+
system_prompt = f"""You are a helpful business assistant that answers questions about a specific business.
|
82 |
+
|
83 |
+
Business Information:
|
84 |
+
{business_info}
|
85 |
+
Answer ONLY using information from the business information above. If the question cannot be answered using the provided business information, respond with "Yeh information abhi available nahi hai."
|
86 |
+
You can respond in Hindi-English mix (Hinglish) if the user asks in that format. Be concise and helpful."""
|
87 |
+
|
88 |
+
# Prepare conversation history for the API
|
89 |
+
messages = [{"role": "system", "content": system_prompt}]
|
90 |
+
|
91 |
+
# Add conversation history
|
92 |
+
for user_msg, assistant_msg in chat_history:
|
93 |
+
messages.append({"role": "user", "content": user_msg})
|
94 |
+
if assistant_msg: # Only add if not None
|
95 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
96 |
+
|
97 |
+
# Add the current message
|
98 |
+
messages.append({"role": "user", "content": message})
|
99 |
+
|
100 |
+
# Make API call to Groq
|
101 |
+
try:
|
102 |
+
response = requests.post(
|
103 |
+
"https://api.groq.com/openai/v1/chat/completions",
|
104 |
+
headers={
|
105 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
106 |
+
"Content-Type": "application/json"
|
107 |
+
},
|
108 |
+
json={
|
109 |
+
"model": "llama3-70b-8192",
|
110 |
+
"messages": messages,
|
111 |
+
"temperature": 0.7,
|
112 |
+
"max_tokens": 500
|
113 |
+
},
|
114 |
+
timeout=60
|
115 |
+
)
|
116 |
+
|
117 |
+
if response.status_code == 200:
|
118 |
+
return response.json()["choices"][0]["message"]["content"]
|
119 |
+
else:
|
120 |
+
return f"Error: {response.status_code} - {response.text}"
|
121 |
+
except Exception as e:
|
122 |
+
return f"An error occurred: {str(e)}"
|
123 |
+
|
124 |
+
# Create a simple Gradio chat interface
|
125 |
+
def respond(message, history):
|
126 |
+
response = generate_response(message, history)
|
127 |
+
return response
|
128 |
|
129 |
+
demo = gr.ChatInterface(
|
130 |
+
fn=respond,
|
131 |
+
title="🌿 My Business Bot",
|
132 |
+
description="Ask anything about your business in Hindi-English",
|
133 |
+
theme=gr.themes.Soft(),
|
134 |
+
examples=["What are your business hours?", "कीमत क्या है?", "Tell me about your products", "Return policy kya hai?"],
|
135 |
+
cache_examples=False # Disable Gradio's example caching
|
136 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
|
138 |
+
# Launch the app
|
139 |
if __name__ == "__main__":
|
140 |
+
demo.launch()
|