Josebert commited on
Commit
a263608
·
verified ·
1 Parent(s): c3ed62d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -15
app.py CHANGED
@@ -14,10 +14,28 @@ logging.basicConfig(
14
  logger = logging.getLogger(__name__)
15
 
16
  # API configuration
17
- API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-3.3-70B-Instruct"
18
- HEADERS = {"Authorization": f"Bearer {os.getenv('HUGGINGFACEHUB_API_TOKEN')}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  def query(payload):
 
21
  try:
22
  response = requests.post(API_URL, headers=HEADERS, json=payload)
23
  response.raise_for_status()
@@ -27,45 +45,126 @@ def query(payload):
27
  return None
28
 
29
  def process_response(response, marker):
30
- """Helper function to process model responses"""
31
  if not response or not isinstance(response, list):
32
  return "Error: Invalid response from model."
33
 
34
- generated_text = response[0]["generated_text"]
35
- if marker in generated_text:
36
- return generated_text.split(marker, 1)[1].strip()
37
- return generated_text
 
 
 
 
38
 
39
  def generate_exegesis(passage):
 
40
  if not passage.strip():
41
  return "Please enter a Bible passage."
42
 
43
  timestamp = datetime.now().strftime("%H%M%S")
44
- prompt = f"""<s>[INST] You are a professional Bible Scholar. Provide a detailed exegesis of the following biblical verse, including: The original Greek text and transliteration with word-by-word analysis and meanings, historical and cultural context, and theological significance for: {passage} [ts:{timestamp}] [/INST] Exegesis:</s>"""
 
 
 
 
 
 
45
 
46
  try:
47
  response = query({"inputs": prompt})
48
  return process_response(response, "Exegesis:")
49
  except Exception as e:
50
- logger.error(f"Generation Error: {e}")
51
  return f"Generation Error: {e}"
52
 
53
- # ... similar improvements for other functions ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- # Enhance the interface with better styling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  css = """
57
  .gradio-container {
58
  font-family: 'Arial', sans-serif !important;
 
 
59
  }
60
  .gr-button {
61
  background-color: #2e5090 !important;
 
62
  }
63
  .gr-input {
64
  border: 2px solid #ddd !important;
 
 
 
 
 
 
65
  }
66
  """
67
 
68
- # Create the interface using Blocks for better organization
69
  with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
70
  gr.Markdown("# JR Study Bible")
71
 
@@ -80,15 +179,58 @@ with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
80
  ),
81
  outputs=gr.Textbox(
82
  label="Exegesis Commentary",
83
- lines=10
84
  ),
85
  description="Enter a Bible passage to receive insightful exegesis commentary"
86
  )
87
 
88
- # ... similar improvements for other tabs ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  if __name__ == "__main__":
91
- # Add basic API check
92
  try:
93
  test_response = requests.get(API_URL, headers=HEADERS)
94
  if test_response.status_code != 200:
@@ -96,4 +238,5 @@ if __name__ == "__main__":
96
  except Exception as e:
97
  logger.error(f"Failed to connect to API: {e}")
98
 
 
99
  bible_app.launch(share=True)
 
14
  logger = logging.getLogger(__name__)
15
 
16
  # API configuration
17
+ def setup_api():
18
+ """Set up API configuration with proper error handling"""
19
+ token = os.getenv('HUGGINGFACEHUB_API_TOKEN')
20
+ if not token:
21
+ logger.error("No API token found")
22
+ raise ValueError(
23
+ "API token not found. Please set 'HUGGINGFACEHUB_API_TOKEN' "
24
+ "in your environment variables."
25
+ )
26
+
27
+ return {
28
+ "url": "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3",
29
+ "headers": {"Authorization": f"Bearer {token}"}
30
+ }
31
+
32
+ # Initialize API configuration
33
+ api_config = setup_api()
34
+ API_URL = api_config["url"]
35
+ HEADERS = api_config["headers"]
36
 
37
  def query(payload):
38
+ """Make API requests with error handling"""
39
  try:
40
  response = requests.post(API_URL, headers=HEADERS, json=payload)
41
  response.raise_for_status()
 
45
  return None
46
 
47
  def process_response(response, marker):
48
+ """Process model responses"""
49
  if not response or not isinstance(response, list):
50
  return "Error: Invalid response from model."
51
 
52
+ try:
53
+ generated_text = response[0]["generated_text"]
54
+ if marker in generated_text:
55
+ return generated_text.split(marker, 1)[1].strip()
56
+ return generated_text
57
+ except (KeyError, IndexError) as e:
58
+ logger.error(f"Error processing response: {e}")
59
+ return "Error: Failed to process model response."
60
 
61
  def generate_exegesis(passage):
62
+ """Generate biblical exegesis"""
63
  if not passage.strip():
64
  return "Please enter a Bible passage."
65
 
66
  timestamp = datetime.now().strftime("%H%M%S")
67
+ prompt = f"""<s>[INST] As a Bible Scholar, provide a detailed exegesis of: {passage}
68
+ Include:
69
+ 1. Original Greek/Hebrew text with transliteration
70
+ 2. Word-by-word analysis
71
+ 3. Historical and cultural context
72
+ 4. Theological significance
73
+ [ts:{timestamp}] [/INST] Exegesis:</s>"""
74
 
75
  try:
76
  response = query({"inputs": prompt})
77
  return process_response(response, "Exegesis:")
78
  except Exception as e:
79
+ logger.error(f"Exegesis Error: {e}")
80
  return f"Generation Error: {e}"
81
 
82
+ def ask_any_questions(question):
83
+ """Answer Bible-related questions"""
84
+ if not question.strip():
85
+ return "Please enter a question."
86
+
87
+ timestamp = datetime.now().strftime("%H%M%S")
88
+ prompt = f"""<s>[INST] As a Bible Scholar, answer this question: {question}
89
+ Include:
90
+ 1. Clear explanation
91
+ 2. Biblical references
92
+ 3. Theological context
93
+ 4. Practical application
94
+ [ts:{timestamp}] [/INST] Answer:</s>"""
95
+
96
+ try:
97
+ response = query({"inputs": prompt})
98
+ return process_response(response, "Answer:")
99
+ except Exception as e:
100
+ logger.error(f"Question Error: {e}")
101
+ return f"Generation Error: {e}"
102
 
103
+ def generate_sermon(topic):
104
+ """Generate sermon content"""
105
+ if not topic.strip():
106
+ return "Please enter a topic."
107
+
108
+ timestamp = datetime.now().strftime("%H%M%S")
109
+ prompt = f"""<s>[INST] As a Pastor, create a sermon about: {topic}
110
+ Include:
111
+ 1. Main points
112
+ 2. Biblical references
113
+ 3. Illustrations
114
+ 4. Application
115
+ [ts:{timestamp}] [/INST] Sermon:</s>"""
116
+
117
+ try:
118
+ response = query({"inputs": prompt})
119
+ return process_response(response, "Sermon:")
120
+ except Exception as e:
121
+ logger.error(f"Sermon Error: {e}")
122
+ return f"Generation Error: {e}"
123
+
124
+ def keyword_search(keyword):
125
+ """Search Bible passages by keyword"""
126
+ if not keyword.strip():
127
+ return "Please enter a keyword."
128
+
129
+ timestamp = datetime.now().strftime("%H%M%S")
130
+ prompt = f"""<s>[INST] Find Bible passages containing: {keyword}
131
+ Include:
132
+ 1. Verse references
133
+ 2. Context
134
+ 3. Explanations
135
+ 4. Key themes
136
+ [ts:{timestamp}] [/INST] Search Results:</s>"""
137
+
138
+ try:
139
+ response = query({"inputs": prompt})
140
+ return process_response(response, "Search Results:")
141
+ except Exception as e:
142
+ logger.error(f"Search Error: {e}")
143
+ return f"Generation Error: {e}"
144
+
145
+ # Interface styling
146
  css = """
147
  .gradio-container {
148
  font-family: 'Arial', sans-serif !important;
149
+ max-width: 1200px !important;
150
+ margin: auto !important;
151
  }
152
  .gr-button {
153
  background-color: #2e5090 !important;
154
+ color: white !important;
155
  }
156
  .gr-input {
157
  border: 2px solid #ddd !important;
158
+ border-radius: 8px !important;
159
+ }
160
+ .gr-form {
161
+ background-color: #f8f9fa !important;
162
+ padding: 20px !important;
163
+ border-radius: 10px !important;
164
  }
165
  """
166
 
167
+ # Create the interface using Blocks
168
  with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
169
  gr.Markdown("# JR Study Bible")
170
 
 
179
  ),
180
  outputs=gr.Textbox(
181
  label="Exegesis Commentary",
182
+ lines=12
183
  ),
184
  description="Enter a Bible passage to receive insightful exegesis commentary"
185
  )
186
 
187
+ with gr.Tab("Bible Q&A"):
188
+ gr.Interface(
189
+ fn=ask_any_questions,
190
+ inputs=gr.Textbox(
191
+ label="Ask Any Bible Question",
192
+ placeholder="e.g., What does John 3:16 mean?",
193
+ lines=2
194
+ ),
195
+ outputs=gr.Textbox(
196
+ label="Answer",
197
+ lines=12
198
+ ),
199
+ description="Ask any Bible-related question"
200
+ )
201
+
202
+ with gr.Tab("Sermon Generator"):
203
+ gr.Interface(
204
+ fn=generate_sermon,
205
+ inputs=gr.Textbox(
206
+ label="Generate Sermon",
207
+ placeholder="e.g., Faith, Love, Forgiveness",
208
+ lines=2
209
+ ),
210
+ outputs=gr.Textbox(
211
+ label="Sermon Outline",
212
+ lines=15
213
+ ),
214
+ description="Generate a detailed sermon outline on any biblical topic"
215
+ )
216
+
217
+ with gr.Tab("Bible Search"):
218
+ gr.Interface(
219
+ fn=keyword_search,
220
+ inputs=gr.Textbox(
221
+ label="Search the Bible",
222
+ placeholder="e.g., love, faith, hope",
223
+ lines=1
224
+ ),
225
+ outputs=gr.Textbox(
226
+ label="Search Results",
227
+ lines=12
228
+ ),
229
+ description="Search for Bible passages containing specific keywords"
230
+ )
231
 
232
  if __name__ == "__main__":
233
+ # API health check
234
  try:
235
  test_response = requests.get(API_URL, headers=HEADERS)
236
  if test_response.status_code != 200:
 
238
  except Exception as e:
239
  logger.error(f"Failed to connect to API: {e}")
240
 
241
+ # Launch the app
242
  bible_app.launch(share=True)