Josebert commited on
Commit
3f7d704
·
verified ·
1 Parent(s): 4f1f553

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -120
app.py CHANGED
@@ -3,125 +3,132 @@ import gradio as gr
3
  import requests
4
  import json
5
  import logging
6
-
7
- # Retrieve the API token from secrets
8
- api_token = os.getenv("API_TOKEN")
9
- if not api_token:
10
- raise ValueError("API token not found. Make sure 'API_TOKEN' is set in the Secrets.")
11
 
12
  # Configure logging
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
16
- # Use the token in your request headers
17
- API_URL = "https://api-inference.huggingface.co/models/google/gemma-2b"
18
- HEADERS = {"Authorization": f"Bearer {api_token}"}
 
19
 
20
- def generate_exegesis(passage):
21
- if not passage.strip():
22
- return "Please enter a Bible passage."
23
 
24
- prompt = f"""<s>[INST] You are a professional Bible Scholar. Provide a detailed exegesis of the following biblical verse, including:
25
- The original Greek text and transliteration with word-by-word analysis and meanings, historical and cultural context, and theological significance for:
26
- {passage} [/INST] Exegesis:</s>"""
 
 
 
 
 
 
 
 
27
 
 
 
28
  payload = {
29
- "inputs": prompt,
 
 
 
 
30
  }
 
31
  try:
32
  response = requests.post(API_URL, headers=HEADERS, json=payload)
33
  response.raise_for_status()
34
- result = response.json()
35
- logger.debug("Full API Response: %s", json.dumps(result, indent=4))
36
-
37
- if isinstance(result, list) and len(result) > 0:
38
- generated_text = result[0].get("generated_text", "")
39
- marker = "Exegesis:"
40
- if marker in generated_text:
41
- generated_text = generated_text.split(marker, 1)[1].strip()
42
- return generated_text or "Error: No response from model."
43
- else:
44
- return "Error: Unexpected response format."
45
- except requests.exceptions.RequestException as e:
46
- return f"API Error: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  def ask_any_questions(question):
49
- prompt = f"""<s>[INST] You are a professional Bible Scholar. Provide a detailed answer to the following question, including:
50
- Relevant Bible verses, their explanations, and theological significance for:
51
- {question} [/INST] Answer:</s>"""
 
 
 
52
 
53
- payload = {
54
- "inputs": prompt,
55
- }
 
 
 
56
 
57
- try:
58
- response = requests.post(API_URL, headers=HEADERS, json=payload)
59
- response.raise_for_status()
60
- result = response.json()
61
- logger.debug("Full API Response: %s", json.dumps(result, indent=4))
62
-
63
- if isinstance(result, list) and len(result) > 0:
64
- answer_text = result[0].get("generated_text", "")
65
- marker = "Answer:"
66
- if marker in answer_text:
67
- answer_text = answer_text.split(marker, 1)[1].strip()
68
- return answer_text or "Error: No response from model."
69
- else:
70
- return "Error: Unexpected response format."
71
- except requests.exceptions.RequestException as e:
72
- return f"API Error: {e}"
73
 
74
  def generate_sermon(topic):
75
- prompt = f"""<s>[INST] You are a professional Bible Scholar and Pastor. Provide a detailed sermon on the following topic, including:
76
- Relevant Bible verses, their explanations, theological significance, and practical application for:
77
- {topic} [/INST] Sermon:</s>"""
 
 
 
78
 
79
- payload = {
80
- "inputs": prompt,
81
- }
 
 
 
82
 
83
- try:
84
- response = requests.post(API_URL, headers=HEADERS, json=payload)
85
- response.raise_for_status()
86
- result = response.json()
87
- logger.debug("Full API Response: %s", json.dumps(result, indent=4))
88
-
89
- if isinstance(result, list) and len(result) > 0:
90
- sermon_text = result[0].get("generated_text", "")
91
- marker = "Sermon:"
92
- if marker in sermon_text:
93
- sermon_text = sermon_text.split(marker, 1)[1].strip()
94
- return sermon_text or "Error: No response from model."
95
- else:
96
- return "Error: Unexpected response format."
97
- except requests.exceptions.RequestException as e:
98
- return f"API Error: {e}"
99
 
100
  def keyword_search(keyword):
101
- prompt = f"""<s>[INST] You are a professional Bible Scholar. Search for the following keyword in the Bible and provide relevant passages, including:
102
- The original Greek or Hebrew text, transliteration, and translation, as well as an exegesis of the keyword for:
103
- {keyword} [/INST] Search Results:</s>"""
 
 
 
104
 
105
- payload = {
106
- "inputs": prompt,
107
- }
 
 
 
108
 
109
- try:
110
- response = requests.post(API_URL, headers=HEADERS, json=payload)
111
- response.raise_for_status()
112
- result = response.json()
113
- logger.debug("Full API Response: %s", json.dumps(result, indent=4))
114
-
115
- if isinstance(result, list) and len(result) > 0:
116
- search_results = result[0].get("generated_text", "")
117
- marker = "Search Results:"
118
- if marker in search_results:
119
- search_results = search_results.split(marker, 1)[1].strip()
120
- return search_results or "Error: No response from model."
121
- else:
122
- return "Error: Unexpected response format."
123
- except requests.exceptions.RequestException as e:
124
- return f"API Error: {e}"
125
 
126
  # Interface styling
127
  css = """
@@ -138,22 +145,9 @@ css = """
138
  border: 2px solid #ddd !important;
139
  border-radius: 8px !important;
140
  }
141
- .gr-form {
142
- background-color: #f8f9fa !important;
143
- padding: 20px !important;
144
- border-radius: 10px !important;
145
- }
146
- .loading {
147
- display: inline-block;
148
- animation: spin 1s linear infinite;
149
- }
150
- @keyframes spin {
151
- 0% { transform: rotate(0deg); }
152
- 100% { transform: rotate(360deg); }
153
- }
154
  """
155
 
156
- # Create the interface using Blocks
157
  with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
158
  gr.Markdown("# JR Study Bible")
159
 
@@ -170,7 +164,7 @@ with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
170
  label="Exegesis Commentary",
171
  lines=12
172
  ),
173
- description="Enter a Bible passage to receive insightful exegesis commentary"
174
  )
175
 
176
  with gr.Tab("Bible Q&A"):
@@ -200,7 +194,7 @@ with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
200
  label="Sermon Outline",
201
  lines=15
202
  ),
203
- description="Generate a detailed sermon outline on any biblical topic"
204
  )
205
 
206
  with gr.Tab("Bible Search"):
@@ -215,17 +209,8 @@ with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
215
  label="Search Results",
216
  lines=12
217
  ),
218
- description="Search for Bible passages containing specific keywords"
219
  )
220
 
221
  if __name__ == "__main__":
222
- # API health check
223
- try:
224
- test_response = requests.get(API_URL, headers=HEADERS)
225
- if test_response.status_code != 200:
226
- logger.warning("API endpoint might not be responding correctly")
227
- except Exception as e:
228
- logger.error(f"Failed to connect to API: {e}")
229
-
230
- # Launch the app
231
  bible_app.launch(share=True)
 
3
  import requests
4
  import json
5
  import logging
6
+ from datetime import datetime
7
+ import random
 
 
 
8
 
9
  # Configure logging
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # API configuration
14
+ api_token = os.getenv("API_TOKEN")
15
+ if not api_token:
16
+ raise ValueError("API token not found. Make sure 'API_TOKEN' is set in the Secrets.")
17
 
18
+ API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
19
+ HEADERS = {"Authorization": f"Bearer {api_token}"}
 
20
 
21
+ def get_unique_parameters():
22
+ """Generate unique parameters for each request"""
23
+ return {
24
+ "temperature": random.uniform(0.7, 0.9),
25
+ "top_p": random.uniform(0.85, 0.95),
26
+ "timestamp": datetime.now().strftime("%H%M%S"),
27
+ "style": random.choice([
28
+ "analytical", "theological", "pastoral", "historical",
29
+ "contextual", "linguistic", "practical"
30
+ ])
31
+ }
32
 
33
+ def make_api_call(prompt, params):
34
+ """Unified API call handler"""
35
  payload = {
36
+ "inputs": f"{prompt} [ts:{params['timestamp']}]",
37
+ "parameters": {
38
+ "temperature": params["temperature"],
39
+ "top_p": params["top_p"]
40
+ }
41
  }
42
+
43
  try:
44
  response = requests.post(API_URL, headers=HEADERS, json=payload)
45
  response.raise_for_status()
46
+ return response.json()
47
+ except Exception as e:
48
+ logger.error(f"API Error: {e}")
49
+ return None
50
+
51
+ def process_response(result, marker):
52
+ """Process API response"""
53
+ if not result or not isinstance(result, list) or len(result) == 0:
54
+ return "Error: Invalid response from model."
55
+
56
+ text = result[0].get("generated_text", "")
57
+ if marker in text:
58
+ return text.split(marker, 1)[1].strip()
59
+ return text
60
+
61
+ def generate_exegesis(passage):
62
+ if not passage.strip():
63
+ return "Please enter a Bible passage."
64
+
65
+ params = get_unique_parameters()
66
+ prompt = f"""<s>[INST] As a Bible Scholar using a {params['style']} approach, provide an exegesis of:
67
+ {passage}
68
+
69
+ Include:
70
+ 1. Original language analysis
71
+ 2. Historical context
72
+ 3. Theological insights
73
+ 4. Practical application
74
+ [/INST] Exegesis:</s>"""
75
+
76
+ result = make_api_call(prompt, params)
77
+ return process_response(result, "Exegesis:")
78
 
79
  def ask_any_questions(question):
80
+ if not question.strip():
81
+ return "Please enter a question."
82
+
83
+ params = get_unique_parameters()
84
+ prompt = f"""<s>[INST] As a Bible Scholar taking a {params['style']} perspective, answer:
85
+ {question}
86
 
87
+ Provide:
88
+ 1. Clear explanation
89
+ 2. Biblical references
90
+ 3. Key insights
91
+ 4. Application
92
+ [/INST] Answer:</s>"""
93
 
94
+ result = make_api_call(prompt, params)
95
+ return process_response(result, "Answer:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  def generate_sermon(topic):
98
+ if not topic.strip():
99
+ return "Please enter a topic."
100
+
101
+ params = get_unique_parameters()
102
+ prompt = f"""<s>[INST] As a Pastor using a {params['style']} approach, create a sermon on:
103
+ {topic}
104
 
105
+ Include:
106
+ 1. Main theme
107
+ 2. Biblical foundation
108
+ 3. Key points
109
+ 4. Applications
110
+ [/INST] Sermon:</s>"""
111
 
112
+ result = make_api_call(prompt, params)
113
+ return process_response(result, "Sermon:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  def keyword_search(keyword):
116
+ if not keyword.strip():
117
+ return "Please enter a keyword."
118
+
119
+ params = get_unique_parameters()
120
+ prompt = f"""<s>[INST] Using a {params['style']} method, search for passages about:
121
+ {keyword}
122
 
123
+ For each passage provide:
124
+ 1. Reference
125
+ 2. Context
126
+ 3. Meaning
127
+ 4. Application
128
+ [/INST] Search Results:</s>"""
129
 
130
+ result = make_api_call(prompt, params)
131
+ return process_response(result, "Search Results:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  # Interface styling
134
  css = """
 
145
  border: 2px solid #ddd !important;
146
  border-radius: 8px !important;
147
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  """
149
 
150
+ # Create interface
151
  with gr.Blocks(css=css, theme=gr.themes.Default()) as bible_app:
152
  gr.Markdown("# JR Study Bible")
153
 
 
164
  label="Exegesis Commentary",
165
  lines=12
166
  ),
167
+ description="Enter a Bible passage for analysis"
168
  )
169
 
170
  with gr.Tab("Bible Q&A"):
 
194
  label="Sermon Outline",
195
  lines=15
196
  ),
197
+ description="Generate a sermon outline"
198
  )
199
 
200
  with gr.Tab("Bible Search"):
 
209
  label="Search Results",
210
  lines=12
211
  ),
212
+ description="Search Bible passages by keyword"
213
  )
214
 
215
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
216
  bible_app.launch(share=True)