Josebert commited on
Commit
a576072
·
verified ·
1 Parent(s): 2a7b8d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -96
app.py CHANGED
@@ -1,122 +1,80 @@
1
  import os
2
- import json
3
- import tempfile
4
  import gradio as gr
5
  import requests
6
- from docx import Document
7
- import subprocess
8
- import sys
9
-
10
- try:
11
- from docx import Document
12
- except ModuleNotFoundError:
13
- subprocess.check_call([sys.executable, "-m", "pip", "install", "python-docx"])
14
- from docx import Document
15
 
16
- # Retrieve the API token from the environment
17
  api_token = os.getenv("API_TOKEN")
18
  if not api_token:
19
- raise ValueError("API token not found. Please set the API_TOKEN environment variable.")
20
 
21
- # Define the API URL and headers for the Hugging Face Inference API
22
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
23
  HEADERS = {"Authorization": f"Bearer {api_token}"}
24
 
25
  def analyze_figure_of_speech(verse):
26
- """
27
- Send the Bible verse to the LLM for analysis of figures of speech.
28
- The prompt instructs the model to analyze the verse and return a JSON array.
29
- """
30
  if not verse.strip():
31
- return "Please enter a Bible verse."
32
 
33
- prompt = f"""<s>[INST] You are JR-Sacred Syntax, an expert biblical scholar specializing in Bible analysis.
34
- Analyze the following Bible verse to identify any figures of speech (e.g., Metaphor, Synecdoche, Hyperbole, Simile, Paradox).
35
- Return your answer as a JSON array where each element includes:
36
- - "verses": the Bible verse reference,
37
- - "figure": the type of figure of speech,
38
- - "phrase": the exact phrase from the verse,
39
- - "explanation": a brief explanation in biblical context.
40
- Bible Verse: "{verse}"
41
- [/INST] Figures:</s>"""
 
42
 
43
  payload = {"inputs": prompt}
44
 
45
  try:
46
- response = requests.post(API_URL, headers=HEADERS, json=payload)
47
  response.raise_for_status()
48
  result = response.json()
49
 
50
- if isinstance(result, list) and len(result) > 0:
51
- generated_text = result[0].get("generated_text", "")
52
- marker = "Figures:"
53
- if marker in generated_text:
54
- generated_text = generated_text.split(marker, 1)[1].strip()
55
- try:
56
- output_json = json.loads(generated_text)
57
- return json.dumps(output_json, indent=2)
58
- except json.JSONDecodeError:
59
- return generated_text
60
- else:
61
- return "Error: Unexpected response format."
62
- except requests.exceptions.RequestException as e:
63
- return f"API Error: {e}"
64
-
65
- def generate_docx(analysis_json):
66
- """
67
- Parse the analysis JSON and create a formatted DOCX file.
68
- Each entry is added with headings and bullet points.
69
- Returns the file path of the generated DOCX.
70
- """
71
- try:
72
- analysis_data = json.loads(analysis_json)
73
- except json.JSONDecodeError:
74
- # If not valid JSON, treat the entire text as one entry.
75
- analysis_data = [{"verses": "", "figure": "", "phrase": "", "explanation": analysis_json}]
76
-
77
- document = Document()
78
- document.add_heading("Bible Figures of Speech Analysis", level=1)
79
-
80
- for item in analysis_data:
81
- verses = item.get("verses", "Unknown Verse")
82
- figure = item.get("figure", "Unknown Figure")
83
- phrase = item.get("phrase", "Unknown Phrase")
84
- explanation = item.get("explanation", "No explanation provided.")
85
 
86
- document.add_heading(f"Verse: {verses}", level=2)
87
- document.add_paragraph(f"Figure: {figure}", style='List Bullet')
88
- document.add_paragraph(f"Phrase: {phrase}", style='List Bullet')
89
- document.add_paragraph(f"Explanation: {explanation}", style='List Bullet')
90
- document.add_paragraph("") # Add an empty paragraph for spacing
91
-
92
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".docx")
93
- document.save(temp_file.name)
94
- return temp_file.name
 
 
 
 
 
 
 
 
95
 
96
- def process_and_download(verse):
97
- """
98
- Process the Bible verse:
99
- 1. Get the analysis result as JSON.
100
- 2. Generate a formatted DOCX file from the analysis.
101
- Returns both the JSON result (as text) and the DOCX file path.
102
- """
103
- analysis = analyze_figure_of_speech(verse)
104
- docx_file = generate_docx(analysis)
105
- return analysis, docx_file
106
 
107
- # Create the Gradio Interface with two outputs: JSON analysis and a DOCX download.
108
- iface = gr.Interface(
109
- fn=process_and_download,
110
- inputs=gr.Textbox(label="Enter Bible Verse",
111
- placeholder="E.g., 'I am the vine, you are the branches' - John 15:5",
112
- lines=3),
113
- outputs=[
114
- gr.Textbox(label="Figures of Speech Analysis (JSON)"),
115
- gr.File(label="Download Analysis (.docx)")
116
- ],
117
- title="JR-Sacred Syntax: Bible Figures of Speech Detector",
118
- description="Enter a Bible verse to detect and analyze figures of speech with detailed biblical explanations. Download the formatted analysis as a DOCX file."
119
  )
120
 
121
  if __name__ == "__main__":
122
- iface.launch()
 
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. Ensure 'API_TOKEN' is set in environment variables.")
10
 
 
11
  API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
12
  HEADERS = {"Authorization": f"Bearer {api_token}"}
13
 
14
  def analyze_figure_of_speech(verse):
15
+ """Analyze a Bible verse for figures of speech using a language model."""
 
 
 
16
  if not verse.strip():
17
+ return "Error: Please enter a Bible verse."
18
 
19
+ # Enhanced prompt with strict JSON instructions
20
+ prompt = f"""
21
+ <s>[INST] You are JR-Sacred Syntax, a biblical scholar. Analyze the verse for figures of speech (Metaphor, Simile, Hyperbole, etc.). Return ONLY a JSON array with entries containing:
22
+ - "figure": figure type,
23
+ - "phrase": exact phrase,
24
+ - "explanation": concise biblical context explanation.
25
+
26
+ Verse: "{verse}"
27
+ [/INST]</s>
28
+ """
29
 
30
  payload = {"inputs": prompt}
31
 
32
  try:
33
+ response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=15)
34
  response.raise_for_status()
35
  result = response.json()
36
 
37
+ # Check for API errors
38
+ if isinstance(result, dict) and 'error' in result:
39
+ return f"API Error: {result['error']}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ if not isinstance(result, list) or not result:
42
+ return "Error: Invalid API response format."
43
+
44
+ generated_text = result[0].get("generated_text", "").strip()
45
+
46
+ try:
47
+ output_json = json.loads(generated_text)
48
+ except json.JSONDecodeError:
49
+ return f"Error parsing JSON: {generated_text}"
50
+
51
+ if not isinstance(output_json, list) or len(output_json) == 0:
52
+ return "No figures of speech detected in the verse."
53
+
54
+ return json.dumps(output_json, indent=2, ensure_ascii=False)
55
+
56
+ except requests.exceptions.RequestException as e:
57
+ return f"Connection Error: {str(e)}"
58
 
59
+ # Improved Gradio interface with examples and better formatting
60
+ examples = [
61
+ ["I am the vine, you are the branches - John 15:5"],
62
+ ["The Lord is my shepherd - Psalm 23:1"],
63
+ ["All things are possible with God - Mark 10:27"]
64
+ ]
 
 
 
 
65
 
66
+ demo = gr.Interface(
67
+ fn=analyze_figure_of_speech,
68
+ inputs=gr.Textbox(
69
+ label="Enter Bible Verse",
70
+ placeholder="e.g., 'I am the vine...' - John 15:5",
71
+ lines=3
72
+ ),
73
+ outputs=gr.Code(label="Analysis Results (JSON)", language="json", lines=12),
74
+ title="JR-Sacred Syntax Analyzer",
75
+ description="Analyze biblical figures of speech. Enter a verse and get structured explanations.",
76
+ examples=examples
 
77
  )
78
 
79
  if __name__ == "__main__":
80
+ demo.launch()