Update flask_server.py

This commit is contained in:
MacRimi
2025-10-07 18:15:33 +02:00
parent 9187bf0b83
commit 3c85797cc9

View File

@@ -1607,128 +1607,118 @@ def get_detailed_gpu_info(gpu):
return detailed_info return detailed_info
data_retrieved = False data_retrieved = False
process = None
try: try:
result = subprocess.run( # Start intel_gpu_top process
process = subprocess.Popen(
['intel_gpu_top', '-J', '-s', '500', '-o', '-'], ['intel_gpu_top', '-J', '-s', '500', '-o', '-'],
capture_output=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True, text=True,
timeout=1.5 bufsize=1 # Line buffered
) )
output = result.stdout.strip() print(f"[v0] intel_gpu_top process started, reading output...")
if output and result.returncode == 0: # Read output with timeout
print(f"[v0] intel_gpu_top output received ({len(output)} chars)") output_lines = []
start_time = time.time()
timeout_seconds = 3.0
while time.time() - start_time < timeout_seconds:
# Check if process has output ready
if process.poll() is not None:
# Process ended
break
# Try to parse as JSON
try: try:
# Find first complete JSON object # Read one line with short timeout
brace_count = 0 line = process.stdout.readline()
json_end = -1 if line:
for i, char in enumerate(output): output_lines.append(line)
if char == '{':
brace_count += 1
elif char == '}':
brace_count -= 1
if brace_count == 0:
json_end = i + 1
break
if json_end > 0: # Try to parse accumulated output as JSON
json_str = output[:json_end] output = ''.join(output_lines)
json_data = json.loads(json_str)
# Parse frequency data # Check if we have a complete JSON object
if 'frequency' in json_data: brace_count = 0
freq = json_data['frequency'] json_end = -1
if 'actual' in freq: for i, char in enumerate(output):
detailed_info['clock_graphics'] = f"{freq['actual']:.0f} MHz" if char == '{':
data_retrieved = True brace_count += 1
if 'requested' in freq: elif char == '}':
detailed_info['clock_max'] = f"{freq['requested']:.0f} MHz" brace_count -= 1
data_retrieved = True if brace_count == 0:
json_end = i + 1
break
# Parse power data if json_end > 0:
if 'power' in json_data: # We have a complete JSON object
power = json_data['power'] json_str = output[:json_end]
if 'GPU' in power: try:
detailed_info['power_draw'] = f"{power['GPU']:.2f} W" json_data = json.loads(json_str)
data_retrieved = True print(f"[v0] Successfully parsed JSON from intel_gpu_top")
if 'Package' in power:
detailed_info['power_limit'] = f"{power['Package']:.2f} W"
data_retrieved = True
# Parse RC6 state # Parse frequency data
if 'rc6' in json_data: if 'frequency' in json_data:
rc6_value = json_data['rc6'].get('value', 0) freq = json_data['frequency']
detailed_info['power_state'] = f"RC6: {rc6_value:.1f}%" if 'actual' in freq:
data_retrieved = True detailed_info['clock_graphics'] = f"{freq['actual']:.0f} MHz"
data_retrieved = True
if 'requested' in freq:
detailed_info['clock_max'] = f"{freq['requested']:.0f} MHz"
data_retrieved = True
# Parse interrupts # Parse power data
if 'interrupts' in json_data: if 'power' in json_data:
irq_count = json_data['interrupts'].get('count', 0) power = json_data['power']
detailed_info['irq_rate'] = int(irq_count) if 'GPU' in power:
data_retrieved = True detailed_info['power_draw'] = f"{power['GPU']:.2f} W"
data_retrieved = True
if 'Package' in power:
detailed_info['power_limit'] = f"{power['Package']:.2f} W"
data_retrieved = True
# Parse engine utilization # Parse RC6 state
if 'engines' in json_data: if 'rc6' in json_data:
engines_data = json_data['engines'] rc6_value = json_data['rc6'].get('value', 0)
engine_map = { detailed_info['power_state'] = f"RC6: {rc6_value:.1f}%"
'Render/3D': 'engine_render',
'Blitter': 'engine_blitter',
'Video': 'engine_video',
'VideoEnhance': 'engine_video_enhance'
}
for engine_name, key in engine_map.items():
if engine_name in engines_data:
busy_value = engines_data[engine_name].get('busy', 0)
detailed_info[key] = float(busy_value)
data_retrieved = True data_retrieved = True
print(f"[v0] Intel GPU data retrieved successfully via JSON") # Parse interrupts
if 'interrupts' in json_data:
irq_count = json_data['interrupts'].get('count', 0)
detailed_info['irq_rate'] = int(irq_count)
data_retrieved = True
except (json.JSONDecodeError, ValueError) as e: # Parse engine utilization
print(f"[v0] JSON parsing failed, trying text parsing: {e}") if 'engines' in json_data:
# Fallback to text parsing engines_data = json_data['engines']
freq_match = re.search(r'(\d+)/\s*(\d+)\s*MHz', output) engine_map = {
if freq_match: 'Render/3D': 'engine_render',
detailed_info['clock_graphics'] = f"{freq_match.group(1)} MHz" 'Blitter': 'engine_blitter',
detailed_info['clock_max'] = f"{freq_match.group(2)} MHz" 'Video': 'engine_video',
data_retrieved = True 'VideoEnhance': 'engine_video_enhance'
}
for engine_name, key in engine_map.items():
if engine_name in engines_data:
busy_value = engines_data[engine_name].get('busy', 0)
detailed_info[key] = float(busy_value)
data_retrieved = True
power_match = re.search(r'([\d.]+)/\s*([\d.]+)\s*W', output) print(f"[v0] Intel GPU data retrieved successfully")
if power_match: break # Exit loop, we got the data
detailed_info['power_draw'] = f"{power_match.group(1)} W"
detailed_info['power_limit'] = f"{power_match.group(2)} W"
data_retrieved = True
rc6_match = re.search(r'(\d+)%\s*RC6', output) except json.JSONDecodeError:
if rc6_match: # Not a complete JSON yet, continue reading
detailed_info['power_state'] = f"RC6: {rc6_match.group(1)}%" pass
data_retrieved = True else:
# No more output, wait a bit
time.sleep(0.1)
engines = { except Exception as e:
'Render/3D': 'engine_render', print(f"[v0] Error reading intel_gpu_top output: {e}")
'Blitter': 'engine_blitter', break
'Video': 'engine_video',
'VideoEnhance': 'engine_video_enhance'
}
for engine_name, key in engines.items():
pattern = rf'{engine_name}\s+([\d.]+)%'
match = re.search(pattern, output)
if match:
detailed_info[key] = float(match.group(1))
data_retrieved = True
irq_match = re.search(r'(\d+)\s*irqs/s', output)
if irq_match:
detailed_info['irq_rate'] = int(irq_match.group(1))
data_retrieved = True
if data_retrieved:
print(f"[v0] Intel GPU data retrieved successfully via text parsing")
else:
print(f"[v0] No output from intel_gpu_top (return code: {result.returncode})")
if data_retrieved: if data_retrieved:
detailed_info['has_monitoring_tool'] = True detailed_info['has_monitoring_tool'] = True
@@ -1737,12 +1727,18 @@ def get_detailed_gpu_info(gpu):
detailed_info['has_monitoring_tool'] = False detailed_info['has_monitoring_tool'] = False
print(f"[v0] Intel GPU monitoring failed - no data retrieved") print(f"[v0] Intel GPU monitoring failed - no data retrieved")
except subprocess.TimeoutExpired:
print(f"[v0] intel_gpu_top timed out after 1.5 seconds - marking tool as unavailable")
detailed_info['has_monitoring_tool'] = False
except Exception as e: except Exception as e:
print(f"[v0] Error getting Intel GPU details: {e}") print(f"[v0] Error getting Intel GPU details: {e}")
detailed_info['has_monitoring_tool'] = False detailed_info['has_monitoring_tool'] = False
finally:
# Always terminate the process
if process and process.poll() is None:
process.terminate()
try:
process.wait(timeout=1)
except subprocess.TimeoutExpired:
process.kill()
print(f"[v0] intel_gpu_top process terminated")
elif vendor == 'NVIDIA': elif vendor == 'NVIDIA':
try: try:
@@ -2700,7 +2696,7 @@ def api_hardware():
'cpu': hardware_info.get('cpu', {}), 'cpu': hardware_info.get('cpu', {}),
'motherboard': hardware_info.get('motherboard', {}), 'motherboard': hardware_info.get('motherboard', {}),
'memory_modules': hardware_info.get('memory_modules', []), 'memory_modules': hardware_info.get('memory_modules', []),
'storage_devices': hardware_info.get('storage_devices', []), 'storage_devices': hardware_data.get('storage_devices', []),
'pci_devices': hardware_info.get('pci_devices', []), 'pci_devices': hardware_info.get('pci_devices', []),
'temperatures': hardware_info.get('sensors', {}).get('temperatures', []), 'temperatures': hardware_info.get('sensors', {}).get('temperatures', []),
'fans': all_fans, # Return combined fans (sensors + IPMI) 'fans': all_fans, # Return combined fans (sensors + IPMI)