JaishnaCodz commited on
Commit
eab3a5f
·
verified ·
1 Parent(s): e5db2cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -20
app.py CHANGED
@@ -19,18 +19,17 @@ if not api_key:
19
 
20
  genai.configure(api_key=api_key)
21
 
22
- # Use gemini-1.5-flash for faster and more accessible text analysis
23
  try:
24
  model = genai.GenerativeModel('gemini-1.5-flash')
25
  except Exception as e:
26
- # Fallback: List available models if the specified model is not found
27
  print(f"Error initializing model: {str(e)}")
28
  print("Available models:")
29
  for m in genai.list_models():
30
  print(m.name)
31
  raise ValueError("Failed to initialize gemini-1.5-flash. Check available models above and update the model name.")
32
 
33
- # Prompt for Gemini to analyze text with specified output format
34
  PROMPT = """
35
  You are an AI content reviewer. Analyze the provided text for the following:
36
  1. *Grammar Issues*: Identify and suggest corrections for grammatical errors.
@@ -74,17 +73,18 @@ async def fetch_url_content(url):
74
  response = requests.get(url, timeout=10)
75
  response.raise_for_status()
76
  soup = BeautifulSoup(response.text, 'html.parser')
77
- # Extract text from common content tags
78
  content = ' '.join([p.get_text(strip=True) for p in soup.find_all(['p', 'article', 'div'])])
79
  return content if content else "No readable content found on the page."
80
  except Exception as e:
81
  return f"Error fetching URL: {str(e)}"
82
 
83
  async def review_blog(text_input, url_input):
84
- # Start loading effect immediately
85
  button_text = "Processing..."
 
 
86
 
87
- # Determine input type based on which field is populated
88
  if text_input and not url_input:
89
  input_type = "Text"
90
  input_text = text_input
@@ -99,17 +99,22 @@ async def review_blog(text_input, url_input):
99
  return "Review Blog", "Error: No input provided.", gr.update(visible=False)
100
 
101
  try:
102
- # Use asyncio.wait_for for timeout in Python 3.10
103
  async def process_with_timeout():
 
 
104
  # Handle URL input
105
  if input_type == "URL":
106
  button_text = "Fetching content..."
107
- input_text = await fetch_url_content(input_text)
108
- if input_text.startswith("Error"):
109
- return "Review Blog", input_text, gr.update(visible=False)
 
 
 
110
 
111
  # Tokenize input for analysis
112
- sentences = sent_tokenize(input_text)
113
  analysis_text = "\n".join(sentences)
114
 
115
  # Update button for API call
@@ -117,11 +122,9 @@ async def review_blog(text_input, url_input):
117
  try:
118
  response = await asyncio.to_thread(model.generate_content, PROMPT + "\n\nText to analyze:\n" + analysis_text)
119
  report = response.text.strip()
120
- # Ensure the response is markdown by removing any code fences
121
- report = re.sub(r'^markdown\n|$', '', report, flags=re.MULTILINE)
122
  except Exception as e:
123
  report = f"Error analyzing content with Gemini: {str(e)}. Please check your API key, network connection, or model availability."
124
- # Fallback: List available models for debugging
125
  print("Available models:")
126
  for m in genai.list_models():
127
  print(m.name)
@@ -131,18 +134,19 @@ async def review_blog(text_input, url_input):
131
  try:
132
  with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as temp_file:
133
  temp_file.write(report)
134
- temp_file_path = temp_file.name
135
- # Add note to scroll to report
136
  report = f"**Report generated, please scroll down to view.**\n\n{report}"
137
- return "Review Blog", report, gr.update(visible=True, value=temp_file_path)
138
  except Exception as e:
139
  return "Review Blog", f"Error creating temporary file: {str(e)}", gr.update(visible=False)
140
 
141
- # Run the process with a 30-second timeout
142
  return await asyncio.wait_for(process_with_timeout(), timeout=30)
143
 
144
  except asyncio.TimeoutError:
145
- return "Timeout", "Error: Process timed out after 30 seconds.", gr.update(visible=False)
 
 
146
 
147
  # Custom CSS for hover effect, loading state, and Inter font
148
  custom_css = """
@@ -217,4 +221,4 @@ with gr.Blocks(theme=gr.themes.Monochrome(), css=custom_css) as demo:
217
  outputs=[status_button, report_output, download_btn]
218
  )
219
 
220
- demo.launch()
 
19
 
20
  genai.configure(api_key=api_key)
21
 
22
+ # Use gemini-1.5-flash for faster text analysis
23
  try:
24
  model = genai.GenerativeModel('gemini-1.5-flash')
25
  except Exception as e:
 
26
  print(f"Error initializing model: {str(e)}")
27
  print("Available models:")
28
  for m in genai.list_models():
29
  print(m.name)
30
  raise ValueError("Failed to initialize gemini-1.5-flash. Check available models above and update the model name.")
31
 
32
+ # Prompt for Gemini to analyze text
33
  PROMPT = """
34
  You are an AI content reviewer. Analyze the provided text for the following:
35
  1. *Grammar Issues*: Identify and suggest corrections for grammatical errors.
 
73
  response = requests.get(url, timeout=10)
74
  response.raise_for_status()
75
  soup = BeautifulSoup(response.text, 'html.parser')
 
76
  content = ' '.join([p.get_text(strip=True) for p in soup.find_all(['p', 'article', 'div'])])
77
  return content if content else "No readable content found on the page."
78
  except Exception as e:
79
  return f"Error fetching URL: {str(e)}"
80
 
81
  async def review_blog(text_input, url_input):
82
+ # Initialize output variables
83
  button_text = "Processing..."
84
+ report = ""
85
+ download_path = None
86
 
87
+ # Determine input type
88
  if text_input and not url_input:
89
  input_type = "Text"
90
  input_text = text_input
 
99
  return "Review Blog", "Error: No input provided.", gr.update(visible=False)
100
 
101
  try:
102
+ # Wrap the entire process in a timeout
103
  async def process_with_timeout():
104
+ nonlocal button_text, report, download_path
105
+
106
  # Handle URL input
107
  if input_type == "URL":
108
  button_text = "Fetching content..."
109
+ content = await fetch_url_content(input_text)
110
+ if content.startswith("Error"):
111
+ return "Review Blog", content, gr.update(visible=False)
112
+ input_text_content = content
113
+ else:
114
+ input_text_content = input_text
115
 
116
  # Tokenize input for analysis
117
+ sentences = sent_tokenize(input_text_content)
118
  analysis_text = "\n".join(sentences)
119
 
120
  # Update button for API call
 
122
  try:
123
  response = await asyncio.to_thread(model.generate_content, PROMPT + "\n\nText to analyze:\n" + analysis_text)
124
  report = response.text.strip()
125
+ report = re.sub(r'^```markdown\n|```$', '', report, flags=re.MULTILINE)
 
126
  except Exception as e:
127
  report = f"Error analyzing content with Gemini: {str(e)}. Please check your API key, network connection, or model availability."
 
128
  print("Available models:")
129
  for m in genai.list_models():
130
  print(m.name)
 
134
  try:
135
  with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as temp_file:
136
  temp_file.write(report)
137
+ download_path = temp_file.name
 
138
  report = f"**Report generated, please scroll down to view.**\n\n{report}"
139
+ return "Review Blog", report, gr.update(visible=True, value=download_path)
140
  except Exception as e:
141
  return "Review Blog", f"Error creating temporary file: {str(e)}", gr.update(visible=False)
142
 
143
+ # Execute with timeout
144
  return await asyncio.wait_for(process_with_timeout(), timeout=30)
145
 
146
  except asyncio.TimeoutError:
147
+ return "Review Blog", "Error: Process timed out after 30 seconds.", gr.update(visible=False)
148
+ except Exception as e:
149
+ return "Review Blog", f"Unexpected error: {str(e)}", gr.update(visible=False)
150
 
151
  # Custom CSS for hover effect, loading state, and Inter font
152
  custom_css = """
 
221
  outputs=[status_button, report_output, download_btn]
222
  )
223
 
224
+ demo.launch()