nexusbert commited on
Commit
604609d
·
1 Parent(s): 63e21da

push final

Browse files
Files changed (4) hide show
  1. .dockerignore +34 -0
  2. Dockerfile +49 -0
  3. app.py +488 -0
  4. requirements.txt +13 -0
.dockerignore ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ .Python
6
+ *.so
7
+ *.egg
8
+ *.egg-info
9
+ dist
10
+ build
11
+ .git
12
+ .gitignore
13
+ .vscode
14
+ .idea
15
+ *.swp
16
+ *.swo
17
+ *~
18
+ .DS_Store
19
+ .env
20
+ .venv
21
+ venv/
22
+ env/
23
+ *.log
24
+ .pytest_cache
25
+ .coverage
26
+ htmlcov/
27
+ *.md
28
+ !README.md
29
+ models/
30
+ *.pdf
31
+ *.docx
32
+ *.pptx
33
+ *.ppt
34
+
Dockerfile ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base Image
2
+ FROM python:3.10-slim
3
+
4
+ ENV DEBIAN_FRONTEND=noninteractive \
5
+ PYTHONUNBUFFERED=1 \
6
+ PYTHONDONTWRITEBYTECODE=1
7
+
8
+ WORKDIR /code
9
+
10
+ # System Dependencies
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ build-essential \
13
+ git \
14
+ curl \
15
+ libopenblas-dev \
16
+ libomp-dev \
17
+ ffmpeg \
18
+ poppler-utils \
19
+ tesseract-ocr \
20
+ tesseract-ocr-eng \
21
+ libgl1 \
22
+ libglib2.0-0 \
23
+ && rm -rf /var/lib/apt/lists/*
24
+
25
+ # Copy requirements and install Python dependencies
26
+ COPY requirements.txt .
27
+ RUN pip install --no-cache-dir -r requirements.txt
28
+
29
+ # Hugging Face + model tools
30
+ RUN pip install --no-cache-dir huggingface-hub sentencepiece accelerate
31
+
32
+ # Hugging Face cache environment
33
+ ENV HF_HOME=/models/huggingface \
34
+ TRANSFORMERS_CACHE=/models/huggingface \
35
+ HUGGINGFACE_HUB_CACHE=/models/huggingface \
36
+ HF_HUB_CACHE=/models/huggingface
37
+
38
+ # Create cache dir and set permissions
39
+ RUN mkdir -p /models/huggingface && chmod -R 777 /models/huggingface
40
+
41
+ # Models will be downloaded at runtime (Zephyr is public, no token needed)
42
+
43
+ # Copy project files
44
+ COPY . .
45
+
46
+ EXPOSE 7860
47
+
48
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
49
+
app.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import json
3
+ import os
4
+ import tempfile
5
+ import io
6
+ from pathlib import Path
7
+ from typing import Optional, Tuple
8
+ from fastapi import FastAPI, UploadFile, File, HTTPException
9
+ from fastapi.responses import JSONResponse
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from pdfminer.high_level import extract_text as extract_pdf_text
12
+ from docx import Document as DocxDocument
13
+ from pptx import Presentation
14
+ import logging
15
+ from PIL import Image
16
+ import pytesseract
17
+ from pdf2image import convert_from_path
18
+ import easyocr
19
+
20
+ logging.basicConfig(level=logging.INFO)
21
+ logger = logging.getLogger(__name__)
22
+
23
+ app = FastAPI(
24
+ title="Deckgpt",
25
+ description="Upload your startup pitch deck (PDF, PPT, DOCX) and get an investor-style review",
26
+ version="1.0.0"
27
+ )
28
+
29
+ MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
30
+ tokenizer = None
31
+ model = None
32
+ ocr_reader = None
33
+
34
+ @app.on_event("startup")
35
+ async def load_model():
36
+ """Load the model, tokenizer, and OCR reader on startup"""
37
+ global tokenizer, model, ocr_reader
38
+ try:
39
+ logger.info(f"Loading model: {MODEL_ID} ...")
40
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
41
+ model = AutoModelForCausalLM.from_pretrained(
42
+ MODEL_ID,
43
+ torch_dtype=torch.bfloat16,
44
+ device_map="auto"
45
+ )
46
+ logger.info("✅ Model loaded successfully!")
47
+
48
+ logger.info("Loading OCR reader...")
49
+ try:
50
+ ocr_reader = easyocr.Reader(['en'], gpu=torch.cuda.is_available())
51
+ logger.info("✅ OCR reader loaded successfully!")
52
+ except Exception as e:
53
+ logger.warning(f"⚠️ EasyOCR failed to load, will use pytesseract fallback: {e}")
54
+ ocr_reader = None
55
+ except Exception as e:
56
+ logger.error(f"❌ Failed to load model: {e}")
57
+ raise
58
+
59
+
60
+ def extract_text_with_ocr(image_path_or_image, use_easyocr: bool = True) -> str:
61
+ """Extract text from image using OCR"""
62
+ try:
63
+ if use_easyocr and ocr_reader is not None:
64
+ if isinstance(image_path_or_image, str):
65
+ result = ocr_reader.readtext(image_path_or_image)
66
+ else:
67
+ result = ocr_reader.readtext(image_path_or_image)
68
+ text_parts = [detection[1] for detection in result if detection[2] > 0.5]
69
+ return "\n".join(text_parts)
70
+ else:
71
+ if isinstance(image_path_or_image, str):
72
+ img = Image.open(image_path_or_image)
73
+ else:
74
+ img = image_path_or_image
75
+ text = pytesseract.image_to_string(img, lang='eng')
76
+ return text
77
+ except Exception as e:
78
+ logger.warning(f"OCR extraction failed: {e}")
79
+ return ""
80
+
81
+ def extract_text_from_pdf(file_path: str, use_ocr: bool = True) -> str:
82
+ """Extract text from PDF file with OCR fallback"""
83
+ text_parts = []
84
+
85
+ try:
86
+ text = extract_pdf_text(file_path)
87
+ if text and text.strip():
88
+ text_parts.append(text.strip())
89
+ except Exception as e:
90
+ logger.warning(f"PDF text extraction failed: {e}")
91
+
92
+ if use_ocr:
93
+ try:
94
+ images = convert_from_path(file_path, dpi=300, first_page=1, last_page=50)
95
+ logger.info(f"Processing {len(images)} pages with OCR...")
96
+
97
+ for i, img in enumerate(images):
98
+ ocr_text = extract_text_with_ocr(img, use_easyocr=True)
99
+ if ocr_text.strip():
100
+ text_parts.append(f"\n--- Page {i+1} (OCR) ---\n{ocr_text}")
101
+ except Exception as e:
102
+ logger.warning(f"OCR processing failed: {e}")
103
+
104
+ combined_text = "\n\n".join(text_parts)
105
+ if not combined_text or not combined_text.strip():
106
+ raise ValueError("No readable text found in PDF (tried both text extraction and OCR)")
107
+ return combined_text
108
+
109
+ def extract_text_from_docx(file_path: str) -> str:
110
+ """Extract text from DOCX file"""
111
+ try:
112
+ doc = DocxDocument(file_path)
113
+ text_parts = []
114
+ for paragraph in doc.paragraphs:
115
+ if paragraph.text.strip():
116
+ text_parts.append(paragraph.text.strip())
117
+
118
+ for table in doc.tables:
119
+ for row in table.rows:
120
+ for cell in row.cells:
121
+ if cell.text.strip():
122
+ text_parts.append(cell.text.strip())
123
+
124
+ text = "\n".join(text_parts)
125
+ if not text or not text.strip():
126
+ raise ValueError("No readable text found in DOCX")
127
+ return text
128
+ except Exception as e:
129
+ raise ValueError(f"Error extracting text from DOCX: {str(e)}")
130
+
131
+ def extract_text_from_ppt(file_path: str, use_ocr: bool = True) -> str:
132
+ """Extract text from PowerPoint file with OCR for images"""
133
+ text_parts = []
134
+
135
+ try:
136
+ prs = Presentation(file_path)
137
+
138
+ for slide_num, slide in enumerate(prs.slides, 1):
139
+ slide_text = []
140
+
141
+ for shape in slide.shapes:
142
+ if hasattr(shape, "text") and shape.text.strip():
143
+ slide_text.append(shape.text.strip())
144
+ elif hasattr(shape, "table"):
145
+ for row in shape.table.rows:
146
+ row_text = []
147
+ for cell in row.cells:
148
+ if cell.text.strip():
149
+ row_text.append(cell.text.strip())
150
+ if row_text:
151
+ slide_text.append(" | ".join(row_text))
152
+ elif use_ocr and hasattr(shape, "image"):
153
+ try:
154
+ image = shape.image
155
+ image_bytes = image.blob
156
+ img = Image.open(io.BytesIO(image_bytes))
157
+ ocr_text = extract_text_with_ocr(img, use_easyocr=True)
158
+ if ocr_text.strip():
159
+ slide_text.append(f"[Image OCR]: {ocr_text.strip()}")
160
+ except Exception as e:
161
+ logger.debug(f"OCR on slide {slide_num} image failed: {e}")
162
+
163
+ if slide_text:
164
+ text_parts.append(f"Slide {slide_num}:\n" + "\n".join(slide_text))
165
+
166
+ text = "\n\n".join(text_parts)
167
+ if not text or not text.strip():
168
+ raise ValueError("No readable text found in PPT")
169
+ return text
170
+ except Exception as e:
171
+ raise ValueError(f"Error extracting text from PPT: {str(e)}")
172
+
173
+ def extract_text_from_file(file_path: str, file_extension: str) -> str:
174
+ """
175
+ Main extraction function that routes to appropriate extractor based on file type
176
+ """
177
+ extension = file_extension.lower()
178
+
179
+ if extension == ".pdf":
180
+ return extract_text_from_pdf(file_path)
181
+ elif extension in [".docx", ".doc"]:
182
+ return extract_text_from_docx(file_path)
183
+ elif extension in [".pptx", ".ppt"]:
184
+ return extract_text_from_ppt(file_path)
185
+ else:
186
+ raise ValueError(f"Unsupported file type: {extension}. Supported: PDF, DOCX, PPT/PPTX")
187
+
188
+ def review_pitchdeck(text: str) -> dict:
189
+ """
190
+ Send text to Zephyr model for VC-level review and return structured JSON
191
+ """
192
+ if not text or not text.strip():
193
+ raise ValueError("No text content provided for review")
194
+
195
+ deck_text = text[:12000]
196
+
197
+ prompt = f"""You are a senior venture capitalist with 15+ years of experience evaluating thousands of pitch decks. You know the patterns that lead to funding vs. ghosting. Based on extensive research analyzing hundreds of decks, these are the critical failure points:
198
+
199
+ 1. Beautiful decks missing commercial backbone (GTM, financials, market sizing, clear ask)
200
+ 2. Giant market claims without credibility - claiming $50B TAM instead of sharp, addressable market
201
+ 3. Mission over mechanics - purpose without profitable model
202
+ 4. No Go-To-Market strategy - "we'll figure it out" isn't a plan
203
+ 5. Traction theatre - vanity metrics instead of real growth (show % growth WOW, paid users, conversion rates)
204
+ 6. Team slide buried or weak - investors back founders at pre-seed, put team early
205
+ 7. Missing moat - can't explain defensibility in one clear line
206
+ 8. Unclear ask - vague "seeking partners" instead of specific: "Raising £400k to reach 10k users, £350k ARR"
207
+ 9. Overstuffed or underexplained - should be 12-14 slides, 1 key message per slide
208
+ 10. No financial logic - even pre-seed needs 3-year revenue/burn/milestone map
209
+
210
+ THE 5 CRITICAL QUESTIONS every deck must answer clearly:
211
+ 1. What problem are you solving?
212
+ 2. Who's paying?
213
+ 3. How do you reach them?
214
+ 4. Why you?
215
+ 5. What do you need?
216
+
217
+ Deck Content:
218
+ {deck_text}
219
+
220
+ TASK:
221
+ Evaluate this deck against these real-world failure patterns. Check specifically for: commercial backbone, credible market sizing, GTM clarity, real traction metrics, team positioning, moat definition, specific ask, slide count/clarity, and financial logic.
222
+
223
+ Produce ONLY valid JSON with these exact fields:
224
+
225
+ {{
226
+ "verdict": "Invest" | "Follow-up" | "Pass",
227
+ "score": 0-100,
228
+ "grade": "A+" | "A" | "A-" | "B+" | "B" | "B-" | "C+" | "C" | "C-" | "D" | "F",
229
+ "top_line": "1-2 sentence executive summary from VC perspective",
230
+ "investment_readiness": "Ready" | "Near-ready" | "Needs-work" | "Not-ready",
231
+ "critical_questions_check": {{
232
+ "what_problem": "clear" | "unclear" | "missing",
233
+ "who_paying": "clear" | "unclear" | "missing",
234
+ "how_reach_them": "clear" | "unclear" | "missing",
235
+ "why_you": "clear" | "unclear" | "missing",
236
+ "what_need": "clear" | "unclear" | "missing"
237
+ }},
238
+ "common_failures": [
239
+ "failure pattern 1 (from top 10 list)",
240
+ "failure pattern 2"
241
+ ],
242
+ "deal_breakers": ["critical issue 1", "critical issue 2", ...],
243
+ "high_potential_signals": ["positive signal 1", "positive signal 2", ...],
244
+ "priority_questions": ["question 1", "question 2", "question 3"],
245
+ "scores": {{
246
+ "storyline_clarity": 0-100,
247
+ "problem_solution": 0-100,
248
+ "market_opportunity": 0-100,
249
+ "market_credibility": 0-100,
250
+ "go_to_market": 0-100,
251
+ "traction_quality": 0-100,
252
+ "business_model": 0-100,
253
+ "team": 0-100,
254
+ "moat_defensibility": 0-100,
255
+ "financials_ask": 0-100,
256
+ "ask_specificity": 0-100,
257
+ "design_communication": 0-100
258
+ }},
259
+ "slide_reviews": [
260
+ {{
261
+ "slide_no": 1,
262
+ "title": "slide title",
263
+ "investor_comment": "VC-style critique",
264
+ "severity": "critical" | "major" | "minor" | "good",
265
+ "rewrite_suggestion": "specific improvement recommendation"
266
+ }}
267
+ ],
268
+ "vc_insights": {{
269
+ "commercial_backbone": "assessment of GTM, financials, ask clarity",
270
+ "market_credibility": "assessment of market sizing realism",
271
+ "gtm_clarity": "assessment of distribution strategy",
272
+ "traction_reality": "assessment of metrics authenticity vs. vanity",
273
+ "investment_thesis": "why invest or pass"
274
+ }},
275
+ "slide_count": number,
276
+ "slide_count_assessment": "optimal (12-14)" | "too_many" | "too_few"
277
+ }}
278
+
279
+ Be brutally honest. Commercial clarity keeps doors open - GTM and financials get you funded. Emotion opens the door, but logic closes the deal.
280
+ """
281
+
282
+ try:
283
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=8192).to(model.device)
284
+ outputs = model.generate(
285
+ **inputs,
286
+ max_new_tokens=2000,
287
+ temperature=0.3,
288
+ do_sample=True,
289
+ top_p=0.9,
290
+ pad_token_id=tokenizer.eos_token_id
291
+ )
292
+ raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
293
+
294
+ start = raw_output.find('{')
295
+ end = raw_output.rfind('}') + 1
296
+
297
+ if start == -1 or end == 0:
298
+ raise ValueError("No JSON object found in model output")
299
+
300
+ parsed_json = json.loads(raw_output[start:end])
301
+ return parsed_json
302
+
303
+ except json.JSONDecodeError as e:
304
+ logger.error(f"JSON parsing error: {e}")
305
+ raise ValueError(f"Failed to parse JSON from model output: {str(e)}")
306
+ except Exception as e:
307
+ logger.error(f"Model generation error: {e}")
308
+ raise ValueError(f"Error during model inference: {str(e)}")
309
+
310
+ def generate_improvement_pointers(review: dict) -> dict:
311
+ """Generate specific improvement pointers for decks below 80% or lacking clarity"""
312
+ score = review.get("score", 0)
313
+ storyline_clarity = review.get("scores", {}).get("storyline_clarity", 0)
314
+
315
+ needs_improvement = score < 80 or storyline_clarity < 70
316
+
317
+ if not needs_improvement:
318
+ return {
319
+ "needs_improvement": False,
320
+ "improvement_pointers": []
321
+ }
322
+
323
+ improvement_prompt = f"""You are a pitch deck consultant with expertise from reviewing hundreds of founder decks. Based on this VC review, provide actionable, specific improvement pointers grounded in real-world failure patterns.
324
+
325
+ VC Review:
326
+ {json.dumps(review, indent=2)}
327
+
328
+ Focus on fixing the TOP 10 COMMON FAILURES:
329
+ 1. Add commercial backbone: GTM plan, financials, market sizing, clear ask
330
+ 2. Fix market credibility: replace giant TAM claims with sharp, addressable market
331
+ 3. Add commercial mechanics: show how purpose becomes profit
332
+ 4. Create GTM strategy: Channels → Cost → Conversion → Timeline (one slide is enough)
333
+ 5. Replace traction theatre: show real metrics (% growth WOW, paid users, conversion rates, pilot outcomes)
334
+ 6. Reposition team: move team slide early (after problem/product), anchor with "lived the problem"
335
+ 7. Define moat: one clear line explaining defensibility
336
+ 8. Make ask specific: "Raising £X to achieve Y milestone, Z revenue" (not vague "seeking partners")
337
+ 9. Optimize slide count: 12-14 slides, 1 key message per slide
338
+ 10. Add financial logic: 3-year revenue/burn/milestone outline
339
+
340
+ Generate 5-10 prioritized improvement pointers addressing the specific failures identified. Focus on:
341
+ - Highest impact changes that will move the needle on score and commercial clarity
342
+ - Specific, actionable recommendations (not vague advice)
343
+ - What to fix first, second, third
344
+ - Slide-by-slide improvements where critical issues were identified
345
+ - How to address deal breakers and common failure patterns
346
+ - Quick wins vs. strategic changes
347
+
348
+ Return ONLY valid JSON:
349
+ {{
350
+ "improvement_pointers": [
351
+ {{
352
+ "priority": 1,
353
+ "category": "category name (e.g., GTM, Market Credibility, Traction, etc.)",
354
+ "failure_pattern": "which of the top 10 failures this addresses",
355
+ "issue": "specific problem from deck",
356
+ "recommendation": "actionable fix with example",
357
+ "expected_impact": "how this moves the needle"
358
+ }}
359
+ ],
360
+ "quick_wins": ["quick fix 1", "quick fix 2"],
361
+ "strategic_changes": ["strategic change 1", "strategic change 2"],
362
+ "critical_fixes": ["must-fix issue 1", "must-fix issue 2"]
363
+ }}
364
+ """
365
+
366
+ try:
367
+ inputs = tokenizer(improvement_prompt, return_tensors="pt", truncation=True, max_length=8192).to(model.device)
368
+ outputs = model.generate(
369
+ **inputs,
370
+ max_new_tokens=1500,
371
+ temperature=0.4,
372
+ do_sample=True,
373
+ pad_token_id=tokenizer.eos_token_id
374
+ )
375
+ raw_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
376
+
377
+ start = raw_output.find('{')
378
+ end = raw_output.rfind('}') + 1
379
+
380
+ if start == -1 or end == 0:
381
+ return {
382
+ "needs_improvement": True,
383
+ "improvement_pointers": [{"priority": 1, "category": "General", "recommendation": "Focus on improving storyline clarity and addressing identified deal breakers"}]
384
+ }
385
+
386
+ improvement_json = json.loads(raw_output[start:end])
387
+ improvement_json["needs_improvement"] = True
388
+ return improvement_json
389
+
390
+ except Exception as e:
391
+ logger.warning(f"Improvement pointers generation failed: {e}")
392
+ return {
393
+ "needs_improvement": True,
394
+ "improvement_pointers": [{"priority": 1, "category": "General", "recommendation": "Review and address all deal breakers and low-scoring areas identified in the review"}]
395
+ }
396
+
397
+ @app.get("/")
398
+ async def root():
399
+ """Health check endpoint"""
400
+ return {
401
+ "status": "healthy",
402
+ "message": "Deckgpt API",
403
+ "model": MODEL_ID,
404
+ "supported_formats": ["PDF", "DOCX", "PPT", "PPTX"]
405
+ }
406
+
407
+ @app.get("/health")
408
+ async def health():
409
+ """Health check endpoint"""
410
+ return {
411
+ "status": "healthy",
412
+ "model_loaded": model is not None and tokenizer is not None
413
+ }
414
+
415
+ @app.post("/review")
416
+ async def review_deck(file: UploadFile = File(...)):
417
+ """
418
+ Upload a pitch deck file and get an investor-style review.
419
+
420
+ Supported formats: PDF, DOCX, PPT, PPTX
421
+ """
422
+ if model is None or tokenizer is None:
423
+ raise HTTPException(status_code=503, detail="Model not loaded yet. Please wait for startup to complete.")
424
+
425
+ file_extension = Path(file.filename).suffix.lower()
426
+ supported_extensions = [".pdf", ".docx", ".doc", ".ppt", ".pptx"]
427
+
428
+ if file_extension not in supported_extensions:
429
+ raise HTTPException(
430
+ status_code=400,
431
+ detail=f"Unsupported file type: {file_extension}. Supported: {', '.join(supported_extensions)}"
432
+ )
433
+
434
+ temp_file = None
435
+ try:
436
+ suffix = file_extension
437
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
438
+ temp_path = temp_file.name
439
+
440
+ content = await file.read()
441
+ if not content:
442
+ raise HTTPException(status_code=400, detail="Uploaded file is empty")
443
+
444
+ temp_file.write(content)
445
+ temp_file.flush()
446
+
447
+ try:
448
+ logger.info(f"Extracting text from {file.filename} ({file_extension})")
449
+ deck_text = extract_text_from_file(temp_path, file_extension)
450
+ logger.info(f"Extracted {len(deck_text)} characters from file")
451
+ except ValueError as e:
452
+ raise HTTPException(status_code=400, detail=str(e))
453
+ except Exception as e:
454
+ logger.error(f"File extraction error: {e}")
455
+ raise HTTPException(status_code=500, detail=f"Error processing file: {str(e)}")
456
+
457
+ try:
458
+ logger.info("Generating VC-level review...")
459
+ review_result = review_pitchdeck(deck_text)
460
+ logger.info("Review generated successfully")
461
+
462
+ logger.info("Checking if improvement pointers are needed...")
463
+ improvement_pointers = generate_improvement_pointers(review_result)
464
+ review_result["improvement_analysis"] = improvement_pointers
465
+
466
+ return JSONResponse(content=review_result)
467
+ except ValueError as e:
468
+ raise HTTPException(status_code=500, detail=str(e))
469
+ except Exception as e:
470
+ logger.error(f"Review generation error: {e}")
471
+ raise HTTPException(status_code=500, detail=f"Error generating review: {str(e)}")
472
+
473
+ except HTTPException:
474
+ raise
475
+ except Exception as e:
476
+ logger.error(f"Unexpected error: {e}")
477
+ raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
478
+
479
+ finally:
480
+ if temp_file and os.path.exists(temp_path):
481
+ try:
482
+ os.unlink(temp_path)
483
+ except Exception as e:
484
+ logger.warning(f"Failed to delete temp file {temp_path}: {e}")
485
+
486
+ if __name__ == "__main__":
487
+ import uvicorn
488
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ fastapi
4
+ uvicorn[standard]
5
+ python-multipart
6
+ pdfminer.six
7
+ python-docx
8
+ python-pptx
9
+ pillow
10
+ pytesseract
11
+ pdf2image
12
+ easyocr
13
+