Josebert commited on
Commit
0ff902b
·
verified ·
1 Parent(s): 4d779a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -42
app.py CHANGED
@@ -3,9 +3,6 @@ import gradio as gr
3
  import requests
4
  import json
5
  import logging
6
- import asyncio
7
- import aiohttp
8
- from cachetools import TTLCache
9
 
10
  # Retrieve the API token from secrets
11
  api_token = os.getenv("API_TOKEN")
@@ -20,92 +17,72 @@ logger = logging.getLogger(__name__)
20
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
21
  HEADERS = {"Authorization": f"Bearer {api_token}"}
22
 
23
- # Cache with a TTL of 10 minutes
24
- cache = TTLCache(maxsize=100, ttl=600)
 
25
 
26
- async def query(payload):
27
- async with aiohttp.ClientSession() as session:
28
- async with session.post(API_URL, headers=HEADERS, json=payload) as response:
29
- return await response.json()
30
-
31
- async def generate_exegesis(passage):
32
  if not passage.strip():
33
  return "Please enter a Bible passage."
34
- if passage in cache:
35
- return cache[passage]
36
  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} [/INST] Exegesis:</s>"""
37
  try:
38
- response = await query({"inputs": prompt})
39
  if isinstance(response, list) and response:
40
  generated_text = response[0]["generated_text"]
41
  marker = "Exegesis:"
42
  if marker in generated_text:
43
- result = generated_text.split(marker, 1)[1].strip()
44
- cache[passage] = result
45
- return result
46
  return generated_text
47
  return "Error: Invalid response from model."
48
  except Exception as e:
49
  logger.error(f"Generation Error: {e}")
50
  return f"Generation Error: {e}"
51
 
52
- async def ask_any_questions(question):
53
  if not question.strip():
54
  return "Please enter a question."
55
- if question in cache:
56
- return cache[question]
57
  prompt = f"""<s>[INST] You are a professional Bible Scholar. Provide a detailed answer to the following question, including: Relevant Bible verses, their explanations, and theological significance for: {question} [/INST] Answer:</s>"""
58
  try:
59
- response = await query({"inputs": prompt})
60
  if isinstance(response, list) and response:
61
  answer_text = response[0]["generated_text"]
62
  marker = "Answer:"
63
  if marker in answer_text:
64
- result = answer_text.split(marker, 1)[1].strip()
65
- cache[question] = result
66
- return result
67
  return answer_text
68
  return "Error: Invalid response from model."
69
  except Exception as e:
70
  logger.error(f"Generation Error: {e}")
71
  return f"Generation Error: {e}"
72
 
73
- async def generate_sermon(topic):
74
  if not topic.strip():
75
  return "Please enter a topic."
76
- if topic in cache:
77
- return cache[topic]
78
  prompt = f"""<s>[INST] You are a highly knowledgeable Bible Scholar and Pastor. Generate a detailed sermon on the following topic: {topic}. Include relevant Bible verses and theological insights. [/INST] Sermon:</s>"""
79
  try:
80
- response = await query({"inputs": prompt})
81
  if isinstance(response, list) and response:
82
  sermon_text = response[0]["generated_text"]
83
  marker = "Sermon:"
84
  if marker in sermon_text:
85
- result = sermon_text.split(marker, 1)[1].strip()
86
- cache[topic] = result
87
- return result
88
  return sermon_text
89
  return "Error: Invalid response from model."
90
  except Exception as e:
91
  logger.error(f"Generation Error: {e}")
92
  return f"Generation Error: {e}"
93
 
94
- async def keyword_search(keyword):
95
  if not keyword.strip():
96
  return "Please enter a keyword."
97
- if keyword in cache:
98
- return cache[keyword]
99
  prompt = f"""<s>[INST] You are a Bible Scholar. Find relevant Bible passages containing the keyword: {keyword} [/INST] Search Results:</s>"""
100
  try:
101
- response = await query({"inputs": prompt})
102
  if isinstance(response, list) and response:
103
  search_results = response[0]["generated_text"]
104
  marker = "Search Results:"
105
  if marker in search_results:
106
- result = search_results.split(marker, 1)[1].strip()
107
- cache[keyword] = result
108
- return result
109
  return search_results
110
  return "Error: Invalid response from model."
111
  except Exception as e:
@@ -114,28 +91,28 @@ async def keyword_search(keyword):
114
 
115
  # Gradio interface definitions
116
  exegesis_demo = gr.Interface(
117
- fn=lambda passage: asyncio.run(generate_exegesis(passage)),
118
  inputs=gr.Textbox(label="Enter Bible Passage for Exegesis", placeholder="e.g., John 3:16"),
119
  outputs=gr.Textbox(label="Exegesis Commentary"),
120
  title="JR Study Bible",
121
  description="Enter a Bible passage to receive insightful exegesis commentary.")
122
 
123
  lookup_demo = gr.Interface(
124
- fn=lambda question: asyncio.run(ask_any_questions(question)),
125
  inputs=gr.Textbox(label="Ask Any Bible Question", placeholder="e.g., What does John 3:16 mean?"),
126
  outputs=gr.Textbox(label="Answer"),
127
  title="Bible Question Answering",
128
  description="Enter a Bible-related question to receive a detailed answer.")
129
 
130
  sermon_demo = gr.Interface(
131
- fn=lambda topic: asyncio.run(generate_sermon(topic)),
132
  inputs=gr.Textbox(label="Generate Sermon", placeholder="e.g., Faith"),
133
  outputs=gr.Textbox(label="Sermon"),
134
  title="Bible Sermon Generator",
135
  description="Enter a topic to generate a detailed sermon.")
136
 
137
  keyword_search_demo = gr.Interface(
138
- fn=lambda keyword: asyncio.run(keyword_search(keyword)),
139
  inputs=gr.Textbox(label="Keyword Search", placeholder="e.g., love"),
140
  outputs=gr.Textbox(label="Search Results"),
141
  title="Bible Keyword Search",
 
3
  import requests
4
  import json
5
  import logging
 
 
 
6
 
7
  # Retrieve the API token from secrets
8
  api_token = os.getenv("API_TOKEN")
 
17
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
18
  HEADERS = {"Authorization": f"Bearer {api_token}"}
19
 
20
+ def query(payload):
21
+ response = requests.post(API_URL, headers=HEADERS, json=payload)
22
+ return response.json()
23
 
24
+ def generate_exegesis(passage):
 
 
 
 
 
25
  if not passage.strip():
26
  return "Please enter a Bible passage."
 
 
27
  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} [/INST] Exegesis:</s>"""
28
  try:
29
+ response = query({"inputs": prompt})
30
  if isinstance(response, list) and response:
31
  generated_text = response[0]["generated_text"]
32
  marker = "Exegesis:"
33
  if marker in generated_text:
34
+ return generated_text.split(marker, 1)[1].strip()
 
 
35
  return generated_text
36
  return "Error: Invalid response from model."
37
  except Exception as e:
38
  logger.error(f"Generation Error: {e}")
39
  return f"Generation Error: {e}"
40
 
41
+ def ask_any_questions(question):
42
  if not question.strip():
43
  return "Please enter a question."
 
 
44
  prompt = f"""<s>[INST] You are a professional Bible Scholar. Provide a detailed answer to the following question, including: Relevant Bible verses, their explanations, and theological significance for: {question} [/INST] Answer:</s>"""
45
  try:
46
+ response = query({"inputs": prompt})
47
  if isinstance(response, list) and response:
48
  answer_text = response[0]["generated_text"]
49
  marker = "Answer:"
50
  if marker in answer_text:
51
+ return answer_text.split(marker, 1)[1].strip()
 
 
52
  return answer_text
53
  return "Error: Invalid response from model."
54
  except Exception as e:
55
  logger.error(f"Generation Error: {e}")
56
  return f"Generation Error: {e}"
57
 
58
+ def generate_sermon(topic):
59
  if not topic.strip():
60
  return "Please enter a topic."
 
 
61
  prompt = f"""<s>[INST] You are a highly knowledgeable Bible Scholar and Pastor. Generate a detailed sermon on the following topic: {topic}. Include relevant Bible verses and theological insights. [/INST] Sermon:</s>"""
62
  try:
63
+ response = query({"inputs": prompt})
64
  if isinstance(response, list) and response:
65
  sermon_text = response[0]["generated_text"]
66
  marker = "Sermon:"
67
  if marker in sermon_text:
68
+ return sermon_text.split(marker, 1)[1].strip()
 
 
69
  return sermon_text
70
  return "Error: Invalid response from model."
71
  except Exception as e:
72
  logger.error(f"Generation Error: {e}")
73
  return f"Generation Error: {e}"
74
 
75
+ def keyword_search(keyword):
76
  if not keyword.strip():
77
  return "Please enter a keyword."
 
 
78
  prompt = f"""<s>[INST] You are a Bible Scholar. Find relevant Bible passages containing the keyword: {keyword} [/INST] Search Results:</s>"""
79
  try:
80
+ response = query({"inputs": prompt})
81
  if isinstance(response, list) and response:
82
  search_results = response[0]["generated_text"]
83
  marker = "Search Results:"
84
  if marker in search_results:
85
+ return search_results.split(marker, 1)[1].strip()
 
 
86
  return search_results
87
  return "Error: Invalid response from model."
88
  except Exception as e:
 
91
 
92
  # Gradio interface definitions
93
  exegesis_demo = gr.Interface(
94
+ fn=generate_exegesis,
95
  inputs=gr.Textbox(label="Enter Bible Passage for Exegesis", placeholder="e.g., John 3:16"),
96
  outputs=gr.Textbox(label="Exegesis Commentary"),
97
  title="JR Study Bible",
98
  description="Enter a Bible passage to receive insightful exegesis commentary.")
99
 
100
  lookup_demo = gr.Interface(
101
+ fn=ask_any_questions,
102
  inputs=gr.Textbox(label="Ask Any Bible Question", placeholder="e.g., What does John 3:16 mean?"),
103
  outputs=gr.Textbox(label="Answer"),
104
  title="Bible Question Answering",
105
  description="Enter a Bible-related question to receive a detailed answer.")
106
 
107
  sermon_demo = gr.Interface(
108
+ fn=generate_sermon,
109
  inputs=gr.Textbox(label="Generate Sermon", placeholder="e.g., Faith"),
110
  outputs=gr.Textbox(label="Sermon"),
111
  title="Bible Sermon Generator",
112
  description="Enter a topic to generate a detailed sermon.")
113
 
114
  keyword_search_demo = gr.Interface(
115
+ fn=keyword_search,
116
  inputs=gr.Textbox(label="Keyword Search", placeholder="e.g., love"),
117
  outputs=gr.Textbox(label="Search Results"),
118
  title="Bible Keyword Search",