Hadiil commited on
Commit
3e341ae
·
verified ·
1 Parent(s): a2febbf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -14
app.py CHANGED
@@ -1,13 +1,12 @@
1
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
2
  from fastapi.staticfiles import StaticFiles
3
- from fastapi.responses import RedirectResponse, JSONResponse, HTMLResponse
4
  from transformers import pipeline, ViltProcessor, ViltForQuestionAnswering, M2M100ForConditionalGeneration, M2M100Tokenizer
5
- from typing import Optional, Dict, Any, List
6
  import logging
7
  import time
8
  import os
9
  import io
10
- import json
11
  import re
12
  from PIL import Image
13
  from docx import Document
@@ -149,7 +148,10 @@ def load_model(task: str, model_name: str = None):
149
  )
150
 
151
  except Exception as e:
152
- logger.error(f"Model load failed: {str(e)}")
 
 
 
153
  raise HTTPException(status_code=500, detail=f"Model loading failed: {task} - {str(e)}")
154
 
155
  def get_gemini_response(user_input: str, is_generation: bool = False):
@@ -216,7 +218,7 @@ def translate_text(text: str, target_language: str):
216
  return translated_text
217
 
218
  except Exception as e:
219
- logger.error(f"Translation error: {str(e)}", exc_info=True)
220
  return f"Translation error: {str(e)}"
221
 
222
  def detect_intent(text: str = None, file: UploadFile = None) -> tuple[str, str]:
@@ -585,10 +587,9 @@ async def process_input(
585
  if not content.strip():
586
  raise HTTPException(status_code=400, detail="No text could be extracted from the file")
587
 
588
- try:
589
- qa_pipeline = load_model("file-qa")
590
- except Exception as e:
591
- logger.warning(f"File-QA model failed: {str(e)}. Falling back to Gemini.")
592
  question = text.strip()
593
  if not question.endswith('?'):
594
  question += '?'
@@ -648,7 +649,7 @@ async def process_input(
648
  return {"response": response, "type": "chat"}
649
 
650
  except Exception as e:
651
- logger.error(f"Processing error: {str(e)}", exc_info=True)
652
  raise HTTPException(status_code=500, detail=str(e))
653
  finally:
654
  process_time = time.time() - start_time
@@ -695,7 +696,7 @@ async def extract_text_from_file(file: UploadFile) -> str:
695
  raise HTTPException(status_code=400, detail=f"Unsupported file format: {filename}")
696
 
697
  except Exception as e:
698
- logger.error(f"File extraction error: {str(e)}", exc_info=True)
699
  raise HTTPException(
700
  status_code=500,
701
  detail=f"Error extracting text: {str(e)}. Supported formats: PDF, DOCX, TXT, RTF"
@@ -807,17 +808,17 @@ plt.tight_layout()
807
  plt.savefig('dashboard.png')
808
  plt.show()"""
809
 
810
- @app.get("/", include_in_schema=False)
811
  async def home():
812
  """Redirect to the static index.html file"""
813
  return RedirectResponse(url="/static/index.html")
814
 
815
- @app.get("/health", include_in_schema=True)
816
  async def health_check():
817
  """Health check endpoint"""
818
  return {"status": "healthy", "version": "2.0.0"}
819
 
820
- @app.get("/models", include_in_schema=True)
821
  async def list_models():
822
  """List available models"""
823
  return {"models": MODELS}
 
1
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
2
  from fastapi.staticfiles import StaticFiles
3
+ from fastapi.responses import RedirectResponse, JSONResponse
4
  from transformers import pipeline, ViltProcessor, ViltForQuestionAnswering, M2M100ForConditionalGeneration, M2M100Tokenizer
5
+ from typing import Optional, Dict, Any
6
  import logging
7
  import time
8
  import os
9
  import io
 
10
  import re
11
  from PIL import Image
12
  from docx import Document
 
148
  )
149
 
150
  except Exception as e:
151
+ logger.error(f"Model load failed: {task} - {str(e)}")
152
+ if task == "file-qa":
153
+ logger.warning("Falling back to Gemini for file-qa due to model load failure")
154
+ return None
155
  raise HTTPException(status_code=500, detail=f"Model loading failed: {task} - {str(e)}")
156
 
157
  def get_gemini_response(user_input: str, is_generation: bool = False):
 
218
  return translated_text
219
 
220
  except Exception as e:
221
+ logger.error(f"Translation error: {str(e)}")
222
  return f"Translation error: {str(e)}"
223
 
224
  def detect_intent(text: str = None, file: UploadFile = None) -> tuple[str, str]:
 
587
  if not content.strip():
588
  raise HTTPException(status_code=400, detail="No text could be extracted from the file")
589
 
590
+ qa_pipeline = load_model("file-qa")
591
+ if qa_pipeline is None:
592
+ logger.info("Using Gemini fallback for file-qa")
 
593
  question = text.strip()
594
  if not question.endswith('?'):
595
  question += '?'
 
649
  return {"response": response, "type": "chat"}
650
 
651
  except Exception as e:
652
+ logger.error(f"Processing error: {str(e)}")
653
  raise HTTPException(status_code=500, detail=str(e))
654
  finally:
655
  process_time = time.time() - start_time
 
696
  raise HTTPException(status_code=400, detail=f"Unsupported file format: {filename}")
697
 
698
  except Exception as e:
699
+ logger.error(f"File extraction error: {str(e)}")
700
  raise HTTPException(
701
  status_code=500,
702
  detail=f"Error extracting text: {str(e)}. Supported formats: PDF, DOCX, TXT, RTF"
 
808
  plt.savefig('dashboard.png')
809
  plt.show()"""
810
 
811
+ @app.get("/")
812
  async def home():
813
  """Redirect to the static index.html file"""
814
  return RedirectResponse(url="/static/index.html")
815
 
816
+ @app.get("/health")
817
  async def health_check():
818
  """Health check endpoint"""
819
  return {"status": "healthy", "version": "2.0.0"}
820
 
821
+ @app.get("/models")
822
  async def list_models():
823
  """List available models"""
824
  return {"models": MODELS}