capradeepgujaran commited on
Commit
dd791f7
β€’
1 Parent(s): a56833a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -65
app.py CHANGED
@@ -12,8 +12,8 @@ from llama_index.llms.openai import OpenAI
12
  from llama_index.core import get_response_synthesizer
13
  from dotenv import load_dotenv
14
  from sentence_transformers import SentenceTransformer, util
15
- from openai_tts_tool import text_to_speech_openai # Importing updated TTS tool
16
  import logging
 
17
 
18
  # Set up logging configuration
19
  logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s')
@@ -24,7 +24,6 @@ load_dotenv()
24
  # Initialize global variables
25
  vector_index = None
26
  query_log = []
27
- answer_state = gr.State() # State object to hold answer
28
  sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
29
 
30
  langs = os.popen('tesseract --list-langs').read().split('\n')[1:-1]
@@ -127,12 +126,8 @@ def calculate_similarity(response, ground_truth):
127
 
128
  return similarity_percentage
129
 
130
- def process_tts(api_key, text, model_name, voice_type, voice_speed, language, output_option, summary_length, additional_prompt):
131
- audio_path = "output_audio.wav" # Define the output path for the audio
132
- return text_to_speech_openai(text, audio_path, voice_type, voice_speed)
133
-
134
- def query_app(query, model_name, use_similarity_check, openai_api_key):
135
- global vector_index, query_log, answer_state
136
 
137
  if vector_index is None:
138
  logging.error("No documents indexed yet. Please upload documents first.")
@@ -158,7 +153,6 @@ def query_app(query, model_name, use_similarity_check, openai_api_key):
158
  return f"Error during query processing: {e}", None
159
 
160
  generated_response = response.response
161
- answer_state.value = generated_response # Update the answer state
162
  query_log.append({
163
  "query_id": str(len(query_log) + 1),
164
  "query": query,
@@ -179,72 +173,51 @@ def query_app(query, model_name, use_similarity_check, openai_api_key):
179
  logging.error(f"Error during similarity calculation: {e}")
180
  metrics['error'] = f"Error during similarity calculation: {e}"
181
 
 
 
 
 
 
182
  return generated_response, metrics if use_similarity_check else None
183
 
 
 
 
184
  def main():
185
- with gr.Blocks(title="Document Processing App") as demo:
186
- gr.Markdown("# πŸ“„ Document Processing and Querying App")
187
 
 
188
  with gr.Tab("πŸ“€ Upload Documents"):
189
- gr.Markdown("### Enter your OpenAI API Key and Upload PDF, DOCX, or TXT files to index")
190
-
191
  api_key_input = gr.Textbox(label="Enter OpenAI API Key", placeholder="Paste your OpenAI API Key here")
192
-
193
- with gr.Row():
194
- file_upload = gr.File(label="Upload Files", file_count="multiple", type="filepath")
195
- lang_dropdown = gr.Dropdown(choices=langs, label="Select OCR Language", value='eng')
196
  upload_button = gr.Button("Upload and Index")
197
  upload_status = gr.Textbox(label="Status", interactive=False)
 
198
 
199
- upload_button.click(
200
- fn=process_upload,
201
- inputs=[api_key_input, file_upload, lang_dropdown],
202
- outputs=[upload_status]
203
- )
204
-
205
  with gr.Tab("❓ Ask a Question"):
206
- gr.Markdown("### Query the indexed documents")
207
- with gr.Column():
208
- query_input = gr.Textbox(label="Enter your question", placeholder="Type your question here...")
209
- model_dropdown = gr.Dropdown(
210
- choices=["gpt-4o", "gpt-4o-mini"],
211
- value="gpt-4o",
212
- label="Select Model"
213
- )
214
- similarity_checkbox = gr.Checkbox(label="Use Similarity Check", value=False)
215
- query_button = gr.Button("Ask")
216
- with gr.Column():
217
- answer_output = gr.Textbox(label="Answer", interactive=False)
218
- metrics_output = gr.JSON(label="Metrics")
219
-
220
- query_button.click(
221
- fn=query_app,
222
- inputs=[query_input, model_dropdown, similarity_checkbox, api_key_input],
223
- outputs=[answer_output, metrics_output]
224
- )
225
-
226
- with gr.Tab("πŸ—£οΈ Generate Audio/Text"):
227
- gr.Markdown("### Convert your text to audio or generate text summary with audio narration")
228
- with gr.Row():
229
- text_input = gr.Textbox(label="Enter text for generation", value=answer_state)
230
- model_dropdown = gr.Dropdown(choices=["tts-1-hd"], value="tts-1-hd", label="Select TTS Model")
231
- voice_type = gr.Textbox(label="Voice Type", value="female") # Example of setting default values
232
- voice_speed = gr.Slider(0.5, 2.0, 1.0, label="Voice Speed")
233
- with gr.Row():
234
- generate_button = gr.Button("Generate")
235
- audio_output = gr.Audio(label="Generated Audio")
236
- text_output = gr.Textbox(label="Generated Text", interactive=False)
237
-
238
- generate_button.click(
239
- fn=process_tts,
240
- inputs=[api_key_input, text_input, model_dropdown, voice_type, voice_speed, "en", "Both", None, ""],
241
- outputs=[text_output, audio_output]
242
- )
243
-
244
- gr.Markdown("""
245
- ---
246
- **Note:** Ensure you upload documents before attempting to query. Enter a valid OpenAI API Key to interact with the models.
247
- """)
248
 
249
  demo.launch()
250
 
 
12
  from llama_index.core import get_response_synthesizer
13
  from dotenv import load_dotenv
14
  from sentence_transformers import SentenceTransformer, util
 
15
  import logging
16
+ from openai_tts_tool import generate_audio_and_text # Importing the TTS tool
17
 
18
  # Set up logging configuration
19
  logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s')
 
24
  # Initialize global variables
25
  vector_index = None
26
  query_log = []
 
27
  sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
28
 
29
  langs = os.popen('tesseract --list-langs').read().split('\n')[1:-1]
 
126
 
127
  return similarity_percentage
128
 
129
+ def query_app(query, model_name, use_similarity_check, openai_api_key, answer_state):
130
+ global vector_index, query_log
 
 
 
 
131
 
132
  if vector_index is None:
133
  logging.error("No documents indexed yet. Please upload documents first.")
 
153
  return f"Error during query processing: {e}", None
154
 
155
  generated_response = response.response
 
156
  query_log.append({
157
  "query_id": str(len(query_log) + 1),
158
  "query": query,
 
173
  logging.error(f"Error during similarity calculation: {e}")
174
  metrics['error'] = f"Error during similarity calculation: {e}"
175
 
176
+ if answer_state is None:
177
+ answer_state = gr.State()
178
+
179
+ answer_state.value = generated_response
180
+
181
  return generated_response, metrics if use_similarity_check else None
182
 
183
+ def process_tts(api_key, text, model_name, voice_type, voice_speed, language, output_option, summary_length, additional_prompt):
184
+ return generate_audio_and_text(api_key, text, model_name, voice_type, voice_speed, language, output_option, summary_length, additional_prompt)
185
+
186
  def main():
187
+ with gr.Blocks(title="Document Processing and TTS App") as demo:
188
+ gr.Markdown("# πŸ“„ Document Processing, Text & Audio Generation App")
189
 
190
+ # Upload documents and chat functionality
191
  with gr.Tab("πŸ“€ Upload Documents"):
 
 
192
  api_key_input = gr.Textbox(label="Enter OpenAI API Key", placeholder="Paste your OpenAI API Key here")
193
+ file_upload = gr.File(label="Upload Files", file_count="multiple", type="filepath")
194
+ lang_dropdown = gr.Dropdown(choices=langs, label="Select OCR Language", value='eng')
 
 
195
  upload_button = gr.Button("Upload and Index")
196
  upload_status = gr.Textbox(label="Status", interactive=False)
197
+ upload_button.click(fn=process_upload, inputs=[api_key_input, file_upload, lang_dropdown], outputs=[upload_status])
198
 
199
+ answer_state = gr.State() # Initialize answer state here
 
 
 
 
 
200
  with gr.Tab("❓ Ask a Question"):
201
+ query_input = gr.Textbox(label="Enter your question")
202
+ model_dropdown = gr.Dropdown(choices=["gpt-4o", "gpt-4o-mini"], label="Select Model", value="gpt-4o")
203
+ similarity_checkbox = gr.Checkbox(label="Use Similarity Check", value=False)
204
+ query_button = gr.Button("Ask")
205
+ answer_output = gr.Textbox(label="Answer", interactive=False)
206
+ metrics_output = gr.JSON(label="Metrics")
207
+ query_button.click(fn=query_app, inputs=[query_input, model_dropdown, similarity_checkbox, api_key_input, answer_state], outputs=[answer_output, metrics_output])
208
+
209
+ with gr.Tab("πŸ—£οΈ Generate Audio and Text"):
210
+ text_input = gr.Textbox(label="Enter text for generation", value=answer_state)
211
+ voice_type = gr.Dropdown(choices=["alloy", "echo", "fable", "onyx"], label="Voice Type", value="alloy")
212
+ voice_speed = gr.Dropdown(choices=["normal", "slow", "fast"], label="Voice Speed", value="normal")
213
+ language = gr.Dropdown(choices=["en", "ar", "de", "hi"], label="Language", value="en")
214
+ output_option = gr.Radio(choices=["audio", "summary_text", "both"], label="Output Option", value="both")
215
+ summary_length = gr.Number(label="Summary Length", value=100)
216
+ additional_prompt = gr.Textbox(label="Additional Prompt (Optional)")
217
+ generate_button = gr.Button("Generate")
218
+ audio_output = gr.Audio(label="Generated Audio", interactive=False)
219
+ summary_output = gr.Textbox(label="Generated Summary Text", interactive=False)
220
+ generate_button.click(fn=process_tts, inputs=[api_key_input, text_input, model_dropdown, voice_type, voice_speed, language, output_option, summary_length, additional_prompt], outputs=[audio_output, summary_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  demo.launch()
223