sikandarciv101 commited on
Commit
355ce95
Β·
verified Β·
1 Parent(s): a8bbabb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -18
app.py CHANGED
@@ -1,52 +1,81 @@
1
  import os
2
  import docx
3
  import requests
4
- import pandas as pd
5
  import gradio as gr
 
6
 
7
  # βœ… API Key from Hugging Face Secrets
8
  API_KEY = os.getenv("GEMINI_API_KEY") # Set this in Hugging Face secrets!
9
 
10
- # βœ… Set the File Path (Downloaded from Google Drive)
11
- FILE_PATH = "/content/drive/MyDrive/Structure analysis/CEP SA 22 (G1).docx" # This should match the file downloaded in `download_file.py`
 
 
 
 
 
 
 
12
 
13
  # βœ… Function to Load and Read File Contents
14
- def load_data():
15
  """Read content from the downloaded file."""
16
- if not os.path.exists(FILE_PATH):
17
- return "❌ File not found! Run `download_file.py` first."
 
18
 
19
- doc = docx.Document(FILE_PATH)
20
- return "\n".join([para.text for para in doc.paragraphs if para.text.strip()])
 
 
 
21
 
22
  # βœ… Function to Call Google AI Gemini API
23
- def call_gemini_api(user_input):
24
  """Send user query + document content to Google AI."""
25
  if not API_KEY:
26
  return "❌ Error: API Key not found! Add it as GEMINI_API_KEY in Hugging Face secrets."
27
 
28
  # Read document content
29
- document_content = load_data()
 
 
 
 
 
 
30
 
31
  # Construct API request
32
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={API_KEY}"
33
  headers = {"Content-Type": "application/json"}
34
- payload = {"contents": [{"parts": [{"text": f"Document Context: {document_content[:4000]}\nUser Query: {user_input}"}]}]}
 
 
 
 
 
 
 
 
35
 
36
  # Make API call
37
- response = requests.post(url, json=payload, headers=headers)
38
- if response.status_code == 200:
 
39
  return response.json().get("candidates", [{}])[0].get("content", "No response from API")
40
- else:
41
- return f"❌ API Error: {response.status_code}, {response.text}"
42
 
43
  # βœ… Gradio Interface
44
  iface = gr.Interface(
45
  fn=call_gemini_api,
46
- inputs=gr.Textbox(label="Ask a question"),
 
 
 
47
  outputs="text",
48
- title="πŸ“„ AI Chatbot with Document Context",
49
- description="This chatbot answers questions based on the document fetched from Google Drive."
50
  )
51
 
52
  iface.launch()
 
1
  import os
2
  import docx
3
  import requests
 
4
  import gradio as gr
5
+ from io import BytesIO
6
 
7
  # βœ… API Key from Hugging Face Secrets
8
  API_KEY = os.getenv("GEMINI_API_KEY") # Set this in Hugging Face secrets!
9
 
10
+ # βœ… Function to Download File from Link
11
+ def download_file_from_link(file_link):
12
+ """Download a file from the provided link."""
13
+ try:
14
+ response = requests.get(file_link)
15
+ response.raise_for_status() # Raise an error for bad status codes
16
+ return BytesIO(response.content) # Return file content as a BytesIO object
17
+ except Exception as e:
18
+ return f"❌ Error downloading file: {e}"
19
 
20
  # βœ… Function to Load and Read File Contents
21
+ def load_data(file_link):
22
  """Read content from the downloaded file."""
23
+ file_content = download_file_from_link(file_link)
24
+ if isinstance(file_content, str): # If an error message is returned
25
+ return file_content
26
 
27
+ try:
28
+ doc = docx.Document(file_content)
29
+ return "\n".join([para.text for para in doc.paragraphs if para.text.strip()])
30
+ except Exception as e:
31
+ return f"❌ Error reading file: {e}"
32
 
33
  # βœ… Function to Call Google AI Gemini API
34
+ def call_gemini_api(file_link, user_input):
35
  """Send user query + document content to Google AI."""
36
  if not API_KEY:
37
  return "❌ Error: API Key not found! Add it as GEMINI_API_KEY in Hugging Face secrets."
38
 
39
  # Read document content
40
+ document_content = load_data(file_link)
41
+ if document_content.startswith("❌"):
42
+ return document_content # Return error message if file loading failed
43
+
44
+ # Truncate document content to avoid exceeding API limits
45
+ max_context_length = 4000 # Adjust based on API limits
46
+ truncated_content = document_content[:max_context_length]
47
 
48
  # Construct API request
49
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={API_KEY}"
50
  headers = {"Content-Type": "application/json"}
51
+ payload = {
52
+ "contents": [
53
+ {
54
+ "parts": [
55
+ {"text": f"Document Context: {truncated_content}\nUser Query: {user_input}"}
56
+ ]
57
+ }
58
+ ]
59
+ }
60
 
61
  # Make API call
62
+ try:
63
+ response = requests.post(url, json=payload, headers=headers)
64
+ response.raise_for_status() # Raise an error for bad status codes
65
  return response.json().get("candidates", [{}])[0].get("content", "No response from API")
66
+ except Exception as e:
67
+ return f"❌ API Error: {e}"
68
 
69
  # βœ… Gradio Interface
70
  iface = gr.Interface(
71
  fn=call_gemini_api,
72
+ inputs=[
73
+ gr.Textbox(label="File Link", placeholder="Paste the file link here (e.g., Google Drive link)"),
74
+ gr.Textbox(label="Ask a question")
75
+ ],
76
  outputs="text",
77
+ title="πŸ“„ AI Chatbot with Real-Time Document Context",
78
+ description="This chatbot answers questions based on the document fetched from the provided link."
79
  )
80
 
81
  iface.launch()