Salmetov commited on
Commit
6446e33
·
verified ·
1 Parent(s): 06038df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -37
app.py CHANGED
@@ -3,53 +3,73 @@ from huggingface_hub import InferenceClient
3
  import gspread
4
  from google.oauth2.service_account import Credentials
5
 
6
- # Google Sheets integration setup
7
- SERVICE_ACCOUNT_FILE = "path_to_your_service_account.json"
8
- SPREADSHEET_ID = "your_spreadsheet_id"
9
  scopes = ["https://www.googleapis.com/auth/spreadsheets"]
10
  credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=scopes)
11
- client = gspread.authorize(credentials)
12
- worksheet = client.open_by_key(SPREADSHEET_ID).sheet1
 
13
 
 
 
 
 
14
  def get_apartment_data(query):
15
- """Fetches relevant apartment data from Google Sheets."""
16
  rows = worksheet.get_all_records()
17
  results = []
18
  for row in rows:
19
  if query.lower() in row["district"].lower() or query.lower() in row["developer"].lower():
20
  results.append(row)
21
- return results if results else "Sorry, no matching apartments found."
22
-
23
- # Hugging Face model setup
24
- hf_client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
25
-
26
- def process_query(message, history):
27
- """Processes the user's query and returns a response."""
28
- # Check for specific queries (e.g., related to apartments)
29
- if "apartment" in message.lower() or "district" in message.lower():
30
- result = get_apartment_data(message)
31
- return {"role": "assistant", "content": str(result)}
32
-
33
- # Default: Handle with Hugging Face model
34
- messages = [{"role": "system", "content": "You are a helpful assistant."}]
35
- for msg in history:
36
- messages.append(msg)
37
- messages.append({"role": "user", "content": message})
38
-
39
- # Fetch response from the Hugging Face model
40
- response = ""
41
- for res in hf_client.chat_completion(messages, stream=True):
42
- token = res.choices[0].delta.content
43
- response += token
44
-
45
- return {"role": "assistant", "content": response}
46
-
47
- # Gradio ChatInterface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  chat_interface = gr.ChatInterface(
49
- process_query,
50
- chatbot=gr.Chatbot(label="Your Assistant"),
51
- title="Apartment Finder Bot",
52
- description="Ask about available apartments or anything else.",
53
  )
54
 
55
  if __name__ == "__main__":
 
3
  import gspread
4
  from google.oauth2.service_account import Credentials
5
 
6
+ # Connecting to Google Sheets
7
+ SERVICE_ACCOUNT_FILE = "sheet-integration-agent@bold-physics-445007-g4.iam.gserviceaccount.com.json"
 
8
  scopes = ["https://www.googleapis.com/auth/spreadsheets"]
9
  credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=scopes)
10
+ client_gs = gspread.authorize(credentials)
11
+ spreadsheet = client_gs.open_by_key("1LHgb4eYDM2ImFY3e3h4kPUnDh6oRHpVz2PA29lQ3Xxg")
12
+ worksheet = spreadsheet.sheet1
13
 
14
+ # Connecting to the zephyr-7b-beta model via Inference API
15
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
16
+
17
+ # Function to retrieve data from Google Sheets
18
  def get_apartment_data(query):
 
19
  rows = worksheet.get_all_records()
20
  results = []
21
  for row in rows:
22
  if query.lower() in row["district"].lower() or query.lower() in row["developer"].lower():
23
  results.append(row)
24
+ if results:
25
+ return "\n".join(
26
+ [f"District: {row['district']}, Developer: {row['developer']}, Area: {row['apt_area']} m²"
27
+ for row in results]
28
+ )
29
+ else:
30
+ return "Sorry, no matching options found."
31
+
32
+ # Function to handle queries
33
+ def respond(message, history):
34
+ print("Query received:", message)
35
+ print("Chat history:", history)
36
+
37
+ if not history:
38
+ history = []
39
+
40
+ try:
41
+ # If the query is related to districts or developers
42
+ if "district" in message.lower() or "developer" in message.lower():
43
+ response = get_apartment_data(message)
44
+ else:
45
+ # Process the query through the model
46
+ messages = [{"role": "user", "content": message}]
47
+ for h in history:
48
+ messages.append(h)
49
+ generated_response = client.chat_completion(
50
+ messages=messages,
51
+ max_tokens=512,
52
+ temperature=0.7,
53
+ top_p=0.95,
54
+ )
55
+ response = generated_response["choices"][0]["message"]["content"]
56
+
57
+ # Forming the correct chat history
58
+ history.append({"role": "user", "content": message})
59
+ history.append({"role": "assistant", "content": response})
60
+ return response, history
61
+
62
+ except Exception as e:
63
+ print(f"Error processing query: {e}")
64
+ history.append({"role": "assistant", "content": "An error occurred while processing your query."})
65
+ return "An error occurred while processing your query.", history
66
+
67
+ # Gradio Interface
68
  chat_interface = gr.ChatInterface(
69
+ respond,
70
+ chatbot_label="Apartment Agent",
71
+ input_label="Your Question",
72
+ output_label="Response",
73
  )
74
 
75
  if __name__ == "__main__":