mgbam commited on
Commit
66dc777
·
verified ·
1 Parent(s): bbd7a55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -87
app.py CHANGED
@@ -1,97 +1,186 @@
1
  # app.py
2
  import sys
3
  import os
 
 
4
 
5
- print("--- DEBUG INFO ---")
6
- print("Current Working Directory:", os.getcwd())
 
7
  print("sys.path:")
8
  for p in sys.path:
9
  print(f" - {p}")
10
- print("Root Directory Contents:", os.listdir('.'))
11
- if os.path.exists('src'):
12
- print("src Directory Contents:", os.listdir('src'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  else:
14
- print("'src' directory NOT FOUND at root.")
15
- print("--- END DEBUG INFO ---")
16
-
17
- # Original imports (keep the failing one to see the error after the debug info)
18
- from src.chimera.core.orchestrator import run_analysis
19
- from src.chimera.utils.logging_config import setup_logging, logger
20
- from src.chimera.config import GEMINI_API_KEY
21
- import gradio as gr
22
- import asyncio
23
-
24
- # Setup logging as soon as the app starts
25
- setup_logging()
26
-
27
- # Check essential configurations on startup
28
- if not GEMINI_API_KEY:
29
- logger.error("CRITICAL: GEMINI_API_KEY is not set. The application might not function correctly.")
30
- # Optionally, raise an exception or display a persistent error in the UI
31
-
32
- async def chimera_interface(query: str):
33
- """
34
- Wrapper function for Gradio to call the async orchestrator.
35
- """
36
- if not query:
37
- return "Please enter a query."
38
- if not GEMINI_API_KEY:
39
- return "Error: Application is not configured correctly (Missing API Key)."
40
-
41
- logger.info(f"Gradio interface received query: {query}")
 
 
42
  try:
43
- # Use asyncio.create_task if Gradio runs its own event loop correctly,
44
- # otherwise run it directly if Gradio handles the async function call.
45
- # Gradio generally handles async functions well.
46
- result = await run_analysis(query)
47
- logger.info("Gradio interface processing complete.")
48
- return result
 
49
  except Exception as e:
50
- logger.exception("Error in Gradio interface call to run_analysis.")
51
- return f"An unexpected error occurred in the backend: {e}"
52
-
53
- # --- Gradio UI Definition ---
54
- with gr.Blocks(theme=gr.themes.Soft(), title="Project Chimera") as demo:
55
- gr.Markdown(
56
- """
57
- # Project Chimera : Real-Time Global Analysis Engine
58
- Enter your query to analyze real-time data from SERP and other sources using Gemini.
59
- (Example: "Analyze recent news about renewable energy investments in the US")
60
- """
61
- )
62
- with gr.Row():
63
- query_input = gr.Textbox(
64
- label="Your Query:",
65
- placeholder="Type your complex question or analysis request here...",
66
- lines=3
67
- )
68
- submit_button = gr.Button("Analyze", variant="primary")
69
- with gr.Row():
70
- output_display = gr.Markdown(label="Chimera Analysis:") # Use Markdown for better formatting
71
-
72
- # Link the button click to the interface function
73
- submit_button.click(
74
- fn=chimera_interface,
75
- inputs=[query_input],
76
- outputs=[output_display]
77
- )
78
-
79
- # Example usage display
80
- gr.Examples(
81
- examples=[
82
- "Search recent news about AI impact on healthcare.",
83
- "What are the latest developments in fusion energy according to recent searches?",
84
- # Add more examples relevant to the APIs you integrate
85
- ],
86
- inputs=[query_input],
87
- outputs=[output_display],
88
- fn=chimera_interface, # Make examples clickable
89
- cache_examples=False # Depends if you want to cache example runs
90
- )
91
-
92
- # --- Launching the App ---
93
- if __name__ == "__main__":
94
- logger.info("Starting Gradio application...")
95
- # Ensure loop is running if needed (Gradio might handle this)
96
- # asyncio.run(demo.launch()) # If running locally and need explicit loop start
97
- demo.launch() # Standard launch for Hugging Face Spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
  import sys
3
  import os
4
+ import importlib.util # Import the utility
5
+ import traceback # Import traceback for detailed error printing
6
 
7
+ print("--- DETAILED DEBUG INFO ---")
8
+ print(f"Python Version: {sys.version}")
9
+ print(f"Current Working Directory: {os.getcwd()}")
10
  print("sys.path:")
11
  for p in sys.path:
12
  print(f" - {p}")
13
+
14
+ print("\n--- Checking Directory Structure ---")
15
+ root_contents = []
16
+ try:
17
+ root_contents = os.listdir('.')
18
+ except Exception as e:
19
+ print(f"[ERROR] Could not list root directory contents: {e}")
20
+ print(f"Root Directory Contents: {root_contents}")
21
+
22
+ src_path = os.path.join(os.getcwd(), 'src')
23
+ if os.path.exists(src_path) and os.path.isdir(src_path):
24
+ print(f"\n[OK] src Directory ('{src_path}') Exists.")
25
+ try:
26
+ src_contents = os.listdir(src_path)
27
+ print(f" src Contents: {src_contents}")
28
+
29
+ chimera_path = os.path.join(src_path, 'chimera')
30
+ if os.path.exists(chimera_path) and os.path.isdir(chimera_path):
31
+ print(f" [OK] chimera Directory ('{chimera_path}') Exists.")
32
+ try:
33
+ chimera_contents = os.listdir(chimera_path)
34
+ print(f" chimera Contents: {chimera_contents}")
35
+
36
+ # Explicitly check for __init__.py in chimera
37
+ chimera_init_path = os.path.join(chimera_path, '__init__.py')
38
+ if os.path.exists(chimera_init_path):
39
+ print(" [OK] src/chimera/__init__.py Exists.")
40
+ else:
41
+ print(" [ERROR] src/chimera/__init__.py MISSING!")
42
+
43
+ core_path = os.path.join(chimera_path, 'core')
44
+ if os.path.exists(core_path) and os.path.isdir(core_path):
45
+ print(f" [OK] core Directory ('{core_path}') Exists.")
46
+ try:
47
+ core_contents = os.listdir(core_path)
48
+ print(f" core Contents: {core_contents}")
49
+
50
+ # Explicitly check for __init__.py in core
51
+ core_init_path = os.path.join(core_path, '__init__.py')
52
+ if os.path.exists(core_init_path):
53
+ print(" [OK] src/chimera/core/__init__.py Exists.")
54
+ else:
55
+ print(" [ERROR] src/chimera/core/__init__.py MISSING!")
56
+
57
+ orchestrator_path = os.path.join(core_path, 'orchestrator.py')
58
+ if os.path.exists(orchestrator_path):
59
+ print(f" [OK] orchestrator.py ('{orchestrator_path}') Exists.")
60
+ else:
61
+ print(f" [ERROR] orchestrator.py ('{orchestrator_path}') MISSING!")
62
+ except Exception as e:
63
+ print(f" [ERROR] Could not list core directory contents: {e}")
64
+ else:
65
+ print(f" [ERROR] core Directory ('{core_path}') MISSING or is not a directory.")
66
+ except Exception as e:
67
+ print(f" [ERROR] Could not list chimera directory contents: {e}")
68
+ else:
69
+ print(f" [ERROR] chimera Directory ('{chimera_path}') MISSING or is not a directory.")
70
+ except Exception as e:
71
+ print(f"\n[ERROR] Could not list src directory contents: {e}")
72
  else:
73
+ print(f"\n[ERROR] src Directory ('{src_path}') MISSING or is not a directory.")
74
+
75
+
76
+ # --- Test importability using importlib ---
77
+ module_name_to_test = "src.chimera.core.orchestrator"
78
+ print(f"\n--- Testing importability of '{module_name_to_test}' using importlib ---")
79
+ spec = None
80
+ try:
81
+ # Clear any previous import attempts from sys.modules that might interfere
82
+ if module_name_to_test in sys.modules:
83
+ del sys.modules[module_name_to_test]
84
+ # Also potentially clear parent modules if issues persist
85
+ # if "src.chimera.core" in sys.modules: del sys.modules["src.chimera.core"]
86
+ # if "src.chimera" in sys.modules: del sys.modules["src.chimera"]
87
+ # if "src" in sys.modules: del sys.modules["src"]
88
+
89
+ spec = importlib.util.find_spec(module_name_to_test)
90
+ except Exception as e:
91
+ print(f"[ERROR] Exception during importlib.util.find_spec: {type(e).__name__}: {e}")
92
+ traceback.print_exc()
93
+
94
+ if spec is None:
95
+ print(f"[FAIL] importlib.util.find_spec could NOT find module '{module_name_to_test}'.")
96
+ print(" This means Python's import machinery cannot locate this module.")
97
+ print(" Double-check directory names, __init__.py files, and potential typos.")
98
+ else:
99
+ print(f"[OK] importlib.util.find_spec found module '{module_name_to_test}'.")
100
+ print(f" Module Location Hint: {spec.origin}")
101
+ # If found, try to actually import it to see if loading fails
102
+ print(f"\n--- Attempting direct import of '{module_name_to_test}' using importlib.import_module ---")
103
  try:
104
+ imported_module = importlib.import_module(module_name_to_test)
105
+ print(f"[OK] Successfully imported '{module_name_to_test}'. Module type: {type(imported_module)}")
106
+ # Try accessing the function
107
+ if hasattr(imported_module, 'run_analysis'):
108
+ print("[OK] Function 'run_analysis' found in the imported module.")
109
+ else:
110
+ print("[ERROR] Function 'run_analysis' NOT FOUND in the imported module!")
111
  except Exception as e:
112
+ print(f"[FAIL] Error occurred DURING import of '{module_name_to_test}':")
113
+ traceback.print_exc() # Print the full traceback for the import error
114
+
115
+ print("\n--- Attempting original failing import ---")
116
+ try:
117
+ # Ensure sys.modules cache is clean before this attempt too
118
+ if module_name_to_test in sys.modules: del sys.modules[module_name_to_test]
119
+
120
+ from src.chimera.core.orchestrator import run_analysis
121
+ print("[OK] Original 'from ... import ...' statement SUCCEEDED.")
122
+ # If this succeeds now, the issue might have been temporary or fixed by restart
123
+ except ModuleNotFoundError:
124
+ print("[FAIL] Original 'from ... import ...' statement FAILED with ModuleNotFoundError.")
125
+ print(" Refer to the importlib test above for clues.")
126
+ traceback.print_exc() # Also print traceback for ModuleNotFoundError
127
+ except Exception as e:
128
+ print(f"[FAIL] Original 'from ... import ...' statement FAILED with a different error:")
129
+ traceback.print_exc()
130
+
131
+ print("\n--- End of Debug Script ---")
132
+
133
+ # Prevent Gradio from starting since imports might have failed
134
+ # ===============================================================
135
+ # == COMMENT OUT OR REMOVE GRADIO CODE BELOW FOR THIS TEST RUN ==
136
+ # ===============================================================
137
+ # import gradio as gr
138
+ # from src.chimera.utils.logging_config import setup_logging, logger # This import would also fail if orchestrator fails
139
+ # from src.chimera.config import GEMINI_API_KEY
140
+
141
+ # # Setup logging as soon as the app starts
142
+ # # setup_logging() # Comment out if logging_config import fails
143
+
144
+ # # Check essential configurations on startup
145
+ # # if not GEMINI_API_KEY:
146
+ # # # logger.error("CRITICAL: GEMINI_API_KEY is not set. The application might not function correctly.")
147
+ # # print("CRITICAL: GEMINI_API_KEY is not set.") # Use print during early debug
148
+
149
+ # async def chimera_interface(query: str):
150
+ # # Placeholder implementation for debugging
151
+ # print(f"Gradio interface received query (debug): {query}")
152
+ # if not query:
153
+ # return "Please enter a query."
154
+ # # logger.info(f"Gradio interface received query: {query}")
155
+ # try:
156
+ # # Need to import run_analysis successfully first
157
+ # from src.chimera.core.orchestrator import run_analysis
158
+ # result = await run_analysis(query)
159
+ # # logger.info("Gradio interface processing complete.")
160
+ # print("Gradio interface processing complete (debug).")
161
+ # return result
162
+ # except NameError:
163
+ # print("Error: run_analysis could not be imported for Gradio.")
164
+ # return "Error: Backend function 'run_analysis' is not available due to import issues."
165
+ # except Exception as e:
166
+ # # logger.exception("Error in Gradio interface call to run_analysis.")
167
+ # print(f"Error in Gradio interface call (debug): {e}")
168
+ # traceback.print_exc()
169
+ # return f"An unexpected error occurred in the backend: {e}"
170
+
171
+ # # --- Gradio UI Definition ---
172
+ # with gr.Blocks(theme=gr.themes.Soft(), title="Project Chimera (Debug Mode)") as demo:
173
+ # gr.Markdown(
174
+ # """
175
+ # # Project Chimera : Real-Time Global Analysis Engine (DEBUG MODE)
176
+ # Enter your query to analyze real-time data from SERP and other sources using Gemini.
177
+ # (Example: "Analyze recent news about renewable energy investments in the US")
178
+ # """
179
+ # )
180
+ # # ... rest of your Gradio UI definition ...
181
+
182
+ # # --- Launching the App ---
183
+ # if __name__ == "__main__":
184
+ # # logger.info("Starting Gradio application...")
185
+ # print("Starting Gradio application (debug)...")
186
+ # # demo.launch() # Don't launch Gradio if imports fail