mlbench123 commited on
Commit
c055343
ยท
verified ยท
1 Parent(s): ec473d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -109
app.py CHANGED
@@ -1987,125 +1987,159 @@ async def analyze_only(files: List[UploadFile] = File(...)):
1987
  raise HTTPException(status_code=500, detail=str(e))
1988
 
1989
 
1990
- if __name__ == "__main__":
1991
-
1992
- # Hardcoded API Key
1993
- GEMINI_API_KEY = "AIzaSyCy6GoBR724Hj9VyuW3hKM4N0P6liBOlDo"
1994
 
1995
- def process_pdfs(pdf_files):
1996
- """Process uploaded PDFs and return Excel file"""
1997
- if not pdf_files:
1998
- return None, "Please upload at least one PDF file"
1999
 
2000
- try:
2001
- # Create temporary directory for PDFs
2002
- temp_dir = tempfile.mkdtemp()
2003
-
2004
- # Save uploaded PDFs to temp directory
2005
- for pdf_file in pdf_files:
2006
- shutil.copy(pdf_file.name, temp_dir)
2007
-
2008
- # Initialize pipeline with hardcoded API key
2009
- pipeline = RealEstateModelPipeline(GEMINI_API_KEY)
2010
-
2011
- # Create output file in temp directory
2012
- output_file = Path(temp_dir) / "Real_Estate_Financial_Model.xlsx"
2013
-
2014
- # Run pipeline
2015
- result = pipeline.run_full_pipeline(temp_dir, str(output_file))
2016
-
2017
- # Generate summary text
2018
- summary = f"""
2019
- โœ… Processing Complete!
2020
-
2021
- Key Metrics:
2022
- โ€ข Total Project Cost: ${pipeline.formula_results.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0):,.0f}
2023
- โ€ข Total Debt: ${pipeline.formula_results.get('TOTAL_DEBT', 0):,.0f}
2024
- โ€ข Total Equity: ${pipeline.formula_results.get('TOTAL_EQUITY', 0):,.0f}
2025
- โ€ข NOI: ${pipeline.formula_results.get('NET_OPERATING_INCOME', 0):,.0f}
2026
- โ€ข Yield on Cost: {pipeline.formula_results.get('YIELD_ON_COST_PERCENTAGE', 0):.2%}
2027
- โ€ข LP IRR: {float(pipeline.formula_results.get('IRR_TO_LP', 0).real if isinstance(pipeline.formula_results.get('IRR_TO_LP', 0), complex) else pipeline.formula_results.get('IRR_TO_LP', 0)):.2f}%
2028
-
2029
- Download your Excel file below โฌ‡๏ธ
2030
- """
2031
-
2032
- return str(output_file), summary
2033
-
2034
- except Exception as e:
2035
- return None, f"โŒ Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2036
 
2037
- # Create Gradio interface
2038
- with gr.Blocks(title="Real Estate Financial Model Generator", theme=gr.themes.Soft()) as demo:
2039
-
2040
- gr.Markdown("""
2041
- # Real Estate Financial Model Generator
2042
- Upload your PDF documents and generate a comprehensive financial model in Excel format.
2043
- """)
2044
-
2045
- with gr.Row():
2046
- with gr.Column(scale=2):
2047
- pdf_input = gr.File(
2048
- label="Upload PDF/XLSX Files",
2049
- file_count="multiple",
2050
- file_types=[".pdf", ".xlsx", ".xls"], # Added .xlsx and .xls
2051
- type="filepath"
2052
- )
2053
-
2054
- process_btn = gr.Button("Generate Financial Model", variant="primary", size="lg")
2055
-
2056
- with gr.Column(scale=1):
2057
- gr.Markdown("""
2058
- ### ๐Ÿ“‹ Supported Formats
2059
- - **PDF**: Offering Memorandum, Reports
2060
- - **XLSX/XLS**: Financial statements, data tables
2061
-
2062
- ### ๐Ÿ“‹ Required Documents
2063
- - Offering Memorandum (PDF/XLSX)
2064
- - Operating Expenses Summary (PDF/XLSX)
2065
- - Sales Comps (PDF/XLSX)
2066
- - Rent Comps (PDF/XLSX)
2067
- - Market Report (PDF/XLSX)
2068
- - Demographics Overview (PDF/XLSX)
2069
-
2070
- ### โšก Features
2071
- - Automated data extraction
2072
- - Formula calculations
2073
- - Professional Excel output
2074
- - Multiple analysis sheets
2075
- """)
2076
-
2077
- with gr.Row():
2078
- output_text = gr.Textbox(
2079
- label="Processing Results",
2080
- lines=12,
2081
- interactive=False
2082
  )
2083
-
2084
- with gr.Row():
2085
- excel_output = gr.File(
2086
- label="๐Ÿ“Š Download Excel File"
 
2087
  )
2088
 
2089
- process_btn.click(
2090
- fn=process_pdfs,
2091
- inputs=[pdf_input],
2092
- outputs=[excel_output, output_text]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2093
  )
2094
-
2095
- gr.Markdown("""
2096
- ---
2097
- ### ๐Ÿ’ก Tips
2098
- - Ensure PDF files are readable and not scanned images
2099
- - Use descriptive filenames (e.g., "Offering_Memorandum.pdf")
2100
- - Processing may take 30-60 seconds depending on file sizes
2101
- """)
2102
 
2103
- # Launch the app
2104
- # demo.launch(share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2105
  app = gr.mount_gradio_app(app, demo, path="/")
 
 
2106
  uvicorn.run(
2107
- app,
2108
- host="0.0.0.0",
2109
  port=7860,
2110
  log_level="info"
2111
  )
 
1987
  raise HTTPException(status_code=500, detail=str(e))
1988
 
1989
 
1990
+ def process_pdfs(pdf_files):
1991
+ """Process uploaded PDFs and return Excel file"""
1992
+ if not pdf_files:
1993
+ return None, "โš ๏ธ Please upload at least one PDF/XLSX file"
1994
 
1995
+ try:
1996
+ # Create temporary directory for PDFs
1997
+ temp_dir = tempfile.mkdtemp()
 
1998
 
1999
+ # Save uploaded PDFs to temp directory
2000
+ for pdf_file in pdf_files:
2001
+ if pdf_file is None:
2002
+ continue
2003
+ dest_path = Path(temp_dir) / Path(pdf_file.name).name
2004
+ shutil.copy(pdf_file.name, dest_path)
2005
+
2006
+ # Initialize pipeline with hardcoded API key
2007
+ pipeline = RealEstateModelPipeline(GEMINI_API_KEY)
2008
+
2009
+ # Create output file in temp directory
2010
+ output_file = Path(temp_dir) / "Real_Estate_Financial_Model.xlsx"
2011
+
2012
+ # Run pipeline
2013
+ result = pipeline.run_full_pipeline(temp_dir, str(output_file))
2014
+
2015
+ # Generate summary text
2016
+ r = pipeline.formula_results
2017
+ irr_val = r.get('IRR_TO_LP', 0)
2018
+ if isinstance(irr_val, complex):
2019
+ irr_val = irr_val.real
2020
+
2021
+ summary = f"""โœ… **Processing Complete!**
2022
+
2023
+ ๐Ÿ“Š **Key Metrics:**
2024
+ โ€ข Total Project Cost: ${r.get('TOTAL_FINANCING_CONTINGENCY_AND_RESERVES', 0):,.0f}
2025
+ โ€ข Total Debt: ${r.get('TOTAL_DEBT', 0):,.0f}
2026
+ โ€ข Total Equity: ${r.get('TOTAL_EQUITY', 0):,.0f}
2027
+ โ€ข NOI: ${r.get('NET_OPERATING_INCOME', 0):,.0f}
2028
+ โ€ข Yield on Cost: {r.get('YIELD_ON_COST_PERCENTAGE', 0):.2%}
2029
+ โ€ข LP IRR: {float(irr_val):.2f}%
2030
+
2031
+ โœจ Download your Excel file below โฌ‡๏ธ
2032
+ """
2033
+
2034
+ return str(output_file), summary
2035
+
2036
+ except Exception as e:
2037
+ import traceback
2038
+ error_msg = f"โŒ **Error occurred:**\n\n{str(e)}\n\n**Details:**\n{traceback.format_exc()}"
2039
+ return None, error_msg
2040
+
2041
+ # Create Gradio interface with better styling
2042
+ with gr.Blocks(
2043
+ title="Real Estate Financial Model Generator",
2044
+ theme=gr.themes.Soft(),
2045
+ css="""
2046
+ .gradio-container {
2047
+ max-width: 1200px !important;
2048
+ }
2049
+ .output-text {
2050
+ font-family: monospace;
2051
+ }
2052
+ """
2053
+ ) as demo:
2054
 
2055
+ gr.Markdown("""
2056
+ # ๐Ÿข Real Estate Financial Model Generator
2057
+
2058
+ Upload your PDF/XLSX documents and generate a comprehensive financial model in Excel format.
2059
+ """)
2060
+
2061
+ with gr.Row():
2062
+ with gr.Column(scale=2):
2063
+ pdf_input = gr.File(
2064
+ label="๐Ÿ“ Upload PDF/XLSX Files",
2065
+ file_count="multiple",
2066
+ file_types=[".pdf", ".xlsx", ".xls"],
2067
+ type="filepath"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2068
  )
2069
+
2070
+ process_btn = gr.Button(
2071
+ "๐Ÿš€ Generate Financial Model",
2072
+ variant="primary",
2073
+ size="lg"
2074
  )
2075
 
2076
+ with gr.Column(scale=1):
2077
+ gr.Markdown("""
2078
+ ### ๐Ÿ“‹ Supported Formats
2079
+ - **PDF**: Offering Memorandum, Reports
2080
+ - **XLSX/XLS**: Financial statements, data tables
2081
+
2082
+ ### ๐Ÿ“‹ Required Documents
2083
+ - Offering Memorandum
2084
+ - Operating Expenses Summary
2085
+ - Sales Comps
2086
+ - Rent Comps
2087
+ - Market Report
2088
+ - Demographics Overview
2089
+
2090
+ ### โšก Features
2091
+ - โœจ Automated data extraction
2092
+ - ๐Ÿงฎ Formula calculations
2093
+ - ๐Ÿ“Š Professional Excel output
2094
+ - ๐Ÿ“ˆ Multiple analysis sheets
2095
+ """)
2096
+
2097
+ with gr.Row():
2098
+ output_text = gr.Textbox(
2099
+ label="๐Ÿ“‹ Processing Results",
2100
+ lines=15,
2101
+ interactive=False,
2102
+ elem_classes=["output-text"]
2103
  )
 
 
 
 
 
 
 
 
2104
 
2105
+ with gr.Row():
2106
+ excel_output = gr.File(
2107
+ label="๐Ÿ“Š Download Excel File",
2108
+ interactive=False
2109
+ )
2110
+
2111
+ # Connect the button
2112
+ process_btn.click(
2113
+ fn=process_pdfs,
2114
+ inputs=[pdf_input],
2115
+ outputs=[excel_output, output_text],
2116
+ api_name="process"
2117
+ )
2118
+
2119
+ gr.Markdown("""
2120
+ ---
2121
+ ### ๐Ÿ’ก Tips
2122
+ - Ensure PDF files are readable and not scanned images
2123
+ - Use descriptive filenames (e.g., "Offering_Memorandum.pdf")
2124
+ - Processing may take 30-60 seconds depending on file sizes
2125
+ - Check the **Processing Results** section for detailed feedback
2126
+
2127
+ ### ๐Ÿ”ง API Endpoints
2128
+ - `POST /api/generate-model` - Generate Excel only
2129
+ - `POST /api/generate-model-with-summary` - Generate Excel + JSON summary
2130
+ - `POST /api/analyze-only` - Generate JSON summary only
2131
+ - `GET /api/health` - Health check
2132
+ """)
2133
+
2134
+ # ============= Mount and Launch =============
2135
+ if __name__ == "__main__":
2136
+ # Mount Gradio to FastAPI
2137
  app = gr.mount_gradio_app(app, demo, path="/")
2138
+
2139
+ # Launch with proper configuration
2140
  uvicorn.run(
2141
+ app,
2142
+ host="0.0.0.0",
2143
  port=7860,
2144
  log_level="info"
2145
  )