Josebert commited on
Commit
7d42faa
·
verified ·
1 Parent(s): 05e84a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -26
app.py CHANGED
@@ -1,35 +1,38 @@
1
  import os
 
 
2
  import gradio as gr
3
  import requests
4
- import json
5
 
6
- # Retrieve the API token from secrets
7
  api_token = os.getenv("API_TOKEN")
8
  if not api_token:
9
- raise ValueError("API token not found. Make sure 'API_TOKEN' is set in the Secrets.")
10
 
11
- # Use the token in your request headers
12
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
13
  HEADERS = {"Authorization": f"Bearer {api_token}"}
14
 
15
  def analyze_figure_of_speech(verse):
 
 
 
 
16
  if not verse.strip():
17
  return "Please enter a Bible verse."
18
 
19
- # Construct a prompt to instruct the model to analyze figures of speech in the verse.
20
- prompt = f"""<s>[INST] You are JR-Sacred Syntax, an expert biblical scholar specializing in the analysis of Bible verses.
21
- Analyze the following Bible verse to identify any figures of speech (e.g., Metaphor, Synecdoche, Hyperbole, Simile, Paradox and others).
22
- Return your answer as a JSON array where each element contains:
23
- - VERSES: show the verse in NKJV,
24
- - FIGURE: the type of figure of speech,
25
- - PHRASE: the exact phrase in the verse,
26
- - EXPLANATION: a brief explanation of why it qualifies as that figure in a biblical context.
27
  Bible Verse: "{verse}"
28
  [/INST] Figures:</s>"""
29
 
30
- payload = {
31
- "inputs": prompt,
32
- }
33
 
34
  try:
35
  response = requests.post(API_URL, headers=HEADERS, json=payload)
@@ -38,7 +41,7 @@ Bible Verse: "{verse}"
38
 
39
  if isinstance(result, list) and len(result) > 0:
40
  generated_text = result[0].get("generated_text", "")
41
- marker = "Figures:" # Marker to help extract the output
42
  if marker in generated_text:
43
  generated_text = generated_text.split(marker, 1)[1].strip()
44
  try:
@@ -51,17 +54,61 @@ Bible Verse: "{verse}"
51
  except requests.exceptions.RequestException as e:
52
  return f"API Error: {e}"
53
 
54
- demo = gr.Interface(
55
- fn=analyze_figure_of_speech,
56
- inputs=gr.Textbox(
57
- label="Enter Bible Verse",
58
- placeholder="e.g., 'I am the vine, you are the branches' - John 15:5",
59
- lines=3
60
- ),
61
- outputs=gr.Textbox(label="Figures of Speech Analysis (JSON)"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  title="JR-Sacred Syntax: Bible Figures of Speech Detector",
63
- description="Enter a Bible verse to detect and analyze figures of speech with detailed biblical explanations."
64
  )
65
 
66
  if __name__ == "__main__":
67
- demo.launch()
 
1
  import os
2
+ import json
3
+ import tempfile
4
  import gradio as gr
5
  import requests
6
+ from docx import Document
7
 
8
+ # Retrieve the API token from the environment
9
  api_token = os.getenv("API_TOKEN")
10
  if not api_token:
11
+ raise ValueError("API token not found. Please set the API_TOKEN environment variable.")
12
 
13
+ # Define the API URL and headers for the Hugging Face Inference API
14
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
15
  HEADERS = {"Authorization": f"Bearer {api_token}"}
16
 
17
  def analyze_figure_of_speech(verse):
18
+ """
19
+ Send the Bible verse to the LLM for analysis of figures of speech.
20
+ The prompt instructs the model to analyze the verse and return a JSON array.
21
+ """
22
  if not verse.strip():
23
  return "Please enter a Bible verse."
24
 
25
+ prompt = f"""<s>[INST] You are JR-Sacred Syntax, an expert biblical scholar specializing in Bible analysis.
26
+ Analyze the following Bible verse to identify any figures of speech (e.g., Metaphor, Synecdoche, Hyperbole, Simile, Paradox).
27
+ Return your answer as a JSON array where each element includes:
28
+ - "verses": the Bible verse reference,
29
+ - "figure": the type of figure of speech,
30
+ - "phrase": the exact phrase from the verse,
31
+ - "explanation": a brief explanation in biblical context.
 
32
  Bible Verse: "{verse}"
33
  [/INST] Figures:</s>"""
34
 
35
+ payload = {"inputs": prompt}
 
 
36
 
37
  try:
38
  response = requests.post(API_URL, headers=HEADERS, json=payload)
 
41
 
42
  if isinstance(result, list) and len(result) > 0:
43
  generated_text = result[0].get("generated_text", "")
44
+ marker = "Figures:"
45
  if marker in generated_text:
46
  generated_text = generated_text.split(marker, 1)[1].strip()
47
  try:
 
54
  except requests.exceptions.RequestException as e:
55
  return f"API Error: {e}"
56
 
57
+ def generate_docx(analysis_json):
58
+ """
59
+ Parse the analysis JSON and create a formatted DOCX file.
60
+ Each entry is added with headings and bullet points.
61
+ Returns the file path of the generated DOCX.
62
+ """
63
+ try:
64
+ analysis_data = json.loads(analysis_json)
65
+ except json.JSONDecodeError:
66
+ # If not valid JSON, treat the entire text as one entry.
67
+ analysis_data = [{"verses": "", "figure": "", "phrase": "", "explanation": analysis_json}]
68
+
69
+ document = Document()
70
+ document.add_heading("Bible Figures of Speech Analysis", level=1)
71
+
72
+ for item in analysis_data:
73
+ verses = item.get("verses", "Unknown Verse")
74
+ figure = item.get("figure", "Unknown Figure")
75
+ phrase = item.get("phrase", "Unknown Phrase")
76
+ explanation = item.get("explanation", "No explanation provided.")
77
+
78
+ document.add_heading(f"Verse: {verses}", level=2)
79
+ document.add_paragraph(f"Figure: {figure}", style='List Bullet')
80
+ document.add_paragraph(f"Phrase: {phrase}", style='List Bullet')
81
+ document.add_paragraph(f"Explanation: {explanation}", style='List Bullet')
82
+ document.add_paragraph("") # Add an empty paragraph for spacing
83
+
84
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".docx")
85
+ document.save(temp_file.name)
86
+ return temp_file.name
87
+
88
+ def process_and_download(verse):
89
+ """
90
+ Process the Bible verse:
91
+ 1. Get the analysis result as JSON.
92
+ 2. Generate a formatted DOCX file from the analysis.
93
+ Returns both the JSON result (as text) and the DOCX file path.
94
+ """
95
+ analysis = analyze_figure_of_speech(verse)
96
+ docx_file = generate_docx(analysis)
97
+ return analysis, docx_file
98
+
99
+ # Create the Gradio Interface with two outputs: JSON analysis and a DOCX download.
100
+ iface = gr.Interface(
101
+ fn=process_and_download,
102
+ inputs=gr.Textbox(label="Enter Bible Verse",
103
+ placeholder="E.g., 'I am the vine, you are the branches' - John 15:5",
104
+ lines=3),
105
+ outputs=[
106
+ gr.Textbox(label="Figures of Speech Analysis (JSON)"),
107
+ gr.File(label="Download Analysis (.docx)")
108
+ ],
109
  title="JR-Sacred Syntax: Bible Figures of Speech Detector",
110
+ description="Enter a Bible verse to detect and analyze figures of speech with detailed biblical explanations. Download the formatted analysis as a DOCX file."
111
  )
112
 
113
  if __name__ == "__main__":
114
+ iface.launch()