Hadiil commited on
Commit
74e2209
·
verified ·
1 Parent(s): 13cb912

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -30
app.py CHANGED
@@ -23,6 +23,7 @@ app = FastAPI(
23
  )
24
 
25
  # Mount static files
 
26
  app.mount("/static", StaticFiles(directory="static"), name="static")
27
 
28
  # Load AI models
@@ -31,7 +32,8 @@ try:
31
  image_pipeline = pipeline(
32
  "image-to-text",
33
  model="Salesforce/blip-image-captioning-base",
34
- device="cpu"
 
35
  )
36
  text_pipeline = pipeline(
37
  "text2text-generation",
@@ -68,6 +70,8 @@ async def home():
68
  try:
69
  with open("static/index.html") as f:
70
  return f.read()
 
 
71
  except Exception as e:
72
  logger.error(f"Failed to load frontend: {e}")
73
  raise HTTPException(500, "Frontend loading failed")
@@ -77,11 +81,7 @@ async def summarize(
77
  file: Optional[UploadFile] = File(None),
78
  text: Optional[str] = Form(None)
79
  ):
80
- """
81
- Summarize text or document
82
- Accepts: PDF, DOCX or raw text
83
- Returns: {'summary': str}
84
- """
85
  try:
86
  if file:
87
  text = await extract_text(file)
@@ -89,7 +89,7 @@ async def summarize(
89
  raise HTTPException(400, "No text provided")
90
 
91
  result = text_pipeline(f"summarize: {text}", max_length=150)
92
- return JSONResponse({"summary": result[0]['generated_text']})
93
  except HTTPException:
94
  raise
95
  except Exception as e:
@@ -98,15 +98,11 @@ async def summarize(
98
 
99
  @app.post("/api/caption")
100
  async def caption_image(file: UploadFile = File(...)):
101
- """
102
- Generate caption for image
103
- Accepts: JPEG, PNG
104
- Returns: {'caption': str}
105
- """
106
  try:
107
  image = Image.open(io.BytesIO(await file.read()))
108
  result = image_pipeline(image)
109
- return JSONResponse({"caption": result[0]['generated_text']})
110
  except Exception as e:
111
  logger.error(f"Captioning error: {e}")
112
  raise HTTPException(500, "Image captioning failed")
@@ -117,11 +113,7 @@ async def answer_question(
117
  text: Optional[str] = Form(None),
118
  question: str = Form(...)
119
  ):
120
- """
121
- Answer questions about text/document
122
- Accepts: PDF, DOCX or raw text + question
123
- Returns: {'answer': str}
124
- """
125
  try:
126
  if file:
127
  text = await extract_text(file)
@@ -129,7 +121,7 @@ async def answer_question(
129
  raise HTTPException(400, "No text provided")
130
 
131
  result = text_pipeline(f"question: {question} context: {text}")
132
- return JSONResponse({"answer": result[0]['generated_text']})
133
  except HTTPException:
134
  raise
135
  except Exception as e:
@@ -141,11 +133,7 @@ async def generate_visualization(
141
  file: UploadFile = File(...),
142
  chart_type: str = Form("bar")
143
  ):
144
- """
145
- Generate visualization code for Excel data
146
- Accepts: XLSX, CSV
147
- Returns: {'code': str, 'columns': list}
148
- """
149
  try:
150
  df = pd.read_excel(io.BytesIO(await file.read()))
151
 
@@ -160,10 +148,10 @@ sns.pairplot(df)
160
  plt.title('Data Distribution')
161
  plt.show()"""
162
 
163
- return JSONResponse({
164
  "code": code,
165
  "columns": list(df.columns)
166
- })
167
  except Exception as e:
168
  logger.error(f"Visualization error: {e}")
169
  raise HTTPException(500, "Visualization code generation failed")
@@ -171,21 +159,21 @@ plt.show()"""
171
  @app.get("/health")
172
  async def health_check():
173
  """Health check endpoint"""
174
- return JSONResponse({
175
  "status": "healthy",
176
  "models": {
177
  "image_captioning": "loaded",
178
  "text_generation": "loaded"
179
  }
180
- })
181
 
182
  # Server initialization
183
  if __name__ == "__main__":
184
  import uvicorn
185
  uvicorn.run(
186
- app,
187
  host="0.0.0.0",
188
  port=8000,
189
  log_level="info",
190
- reload=True
191
  )
 
23
  )
24
 
25
  # Mount static files
26
+ os.makedirs("static", exist_ok=True)
27
  app.mount("/static", StaticFiles(directory="static"), name="static")
28
 
29
  # Load AI models
 
32
  image_pipeline = pipeline(
33
  "image-to-text",
34
  model="Salesforce/blip-image-captioning-base",
35
+ device="cpu",
36
+ use_fast=False # Explicitly set to avoid warning
37
  )
38
  text_pipeline = pipeline(
39
  "text2text-generation",
 
70
  try:
71
  with open("static/index.html") as f:
72
  return f.read()
73
+ except FileNotFoundError:
74
+ return "<h1>Welcome to AI Web Services</h1><p>Frontend not found</p>"
75
  except Exception as e:
76
  logger.error(f"Failed to load frontend: {e}")
77
  raise HTTPException(500, "Frontend loading failed")
 
81
  file: Optional[UploadFile] = File(None),
82
  text: Optional[str] = Form(None)
83
  ):
84
+ """Summarize text or document"""
 
 
 
 
85
  try:
86
  if file:
87
  text = await extract_text(file)
 
89
  raise HTTPException(400, "No text provided")
90
 
91
  result = text_pipeline(f"summarize: {text}", max_length=150)
92
+ return {"summary": result[0]['generated_text']}
93
  except HTTPException:
94
  raise
95
  except Exception as e:
 
98
 
99
  @app.post("/api/caption")
100
  async def caption_image(file: UploadFile = File(...)):
101
+ """Generate caption for image"""
 
 
 
 
102
  try:
103
  image = Image.open(io.BytesIO(await file.read()))
104
  result = image_pipeline(image)
105
+ return {"caption": result[0]['generated_text']}
106
  except Exception as e:
107
  logger.error(f"Captioning error: {e}")
108
  raise HTTPException(500, "Image captioning failed")
 
113
  text: Optional[str] = Form(None),
114
  question: str = Form(...)
115
  ):
116
+ """Answer questions about text/document"""
 
 
 
 
117
  try:
118
  if file:
119
  text = await extract_text(file)
 
121
  raise HTTPException(400, "No text provided")
122
 
123
  result = text_pipeline(f"question: {question} context: {text}")
124
+ return {"answer": result[0]['generated_text']}
125
  except HTTPException:
126
  raise
127
  except Exception as e:
 
133
  file: UploadFile = File(...),
134
  chart_type: str = Form("bar")
135
  ):
136
+ """Generate visualization code for Excel data"""
 
 
 
 
137
  try:
138
  df = pd.read_excel(io.BytesIO(await file.read()))
139
 
 
148
  plt.title('Data Distribution')
149
  plt.show()"""
150
 
151
+ return {
152
  "code": code,
153
  "columns": list(df.columns)
154
+ }
155
  except Exception as e:
156
  logger.error(f"Visualization error: {e}")
157
  raise HTTPException(500, "Visualization code generation failed")
 
159
  @app.get("/health")
160
  async def health_check():
161
  """Health check endpoint"""
162
+ return {
163
  "status": "healthy",
164
  "models": {
165
  "image_captioning": "loaded",
166
  "text_generation": "loaded"
167
  }
168
+ }
169
 
170
  # Server initialization
171
  if __name__ == "__main__":
172
  import uvicorn
173
  uvicorn.run(
174
+ "app:app", # Changed to string format for proper reload
175
  host="0.0.0.0",
176
  port=8000,
177
  log_level="info",
178
+ reload=False # Disabled reload for direct execution
179
  )