Spaces:
Sleeping
Sleeping
Download app.py from CarsoN24IA/FTTHP9: direct link, hf CLI and curl.
- Browser
- Download file 6.83 kB
-
https://huggingface.co/spaces/CarsoN24IA/FTTHP9/resolve/main/app.py
- Command line
-
hf download hf://spaces/CarsoN24IA/FTTHP9/app.py
-
curl -L -o app.py https://huggingface.co/spaces/CarsoN24IA/FTTHP9/resolve/main/app.py
6.83 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| import re | |
| from pathlib import Path | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer | |
| from reportlab.lib.styles import getSampleStyleSheet | |
| # ========================================================= | |
| # 1. PARSER | |
| # ========================================================= | |
| class IndustrialSORParser: | |
| def __init__(self, path): | |
| self.data = Path(path).read_bytes() | |
| def parse_header(self): | |
| try: | |
| txt = self.data.decode("latin1", errors="ignore") | |
| patterns = { | |
| "lambda": r"Wave\s*length\s*[:=]\s*(\d+)", | |
| "length": r"Total\s*length\s*[:=]\s*([\d\.]+)", | |
| "loss": r"Total\s*loss\s*[:=]\s*([\d\.]+)", | |
| "coef": r"Loss/km\s*[:=]\s*([\d\.]+)", | |
| } | |
| result = {} | |
| for k, p in patterns.items(): | |
| m = re.search(p, txt, re.IGNORECASE) | |
| if m: | |
| result[k] = float(m.group(1)) | |
| return result | |
| except Exception as e: | |
| print("HEADER ERROR:", e) | |
| return {} | |
| def parse_events(self): | |
| events = [] | |
| try: | |
| pattern = re.compile(rb"(\d+\.\d+)\s*(km|m)?\s+(-?\d+\.\d+)") | |
| pos = self.data.find(b"KeyEvents") | |
| if pos == -1: | |
| pos = self.data.find(b"Events") | |
| if pos == -1: | |
| return events | |
| chunk = self.data[pos:pos + 10000] | |
| for m in pattern.finditer(chunk): | |
| try: | |
| d = float(m.group(1)) | |
| if m.group(2) == b"m": | |
| d /= 1000 | |
| loss = abs(float(m.group(3))) | |
| events.append({ | |
| "dist": d, | |
| "loss": loss | |
| }) | |
| except Exception: | |
| continue | |
| return events | |
| except Exception as e: | |
| print("EVENT PARSE ERROR:", e) | |
| return [] | |
| def classify(self, events): | |
| for e in events: | |
| if e["loss"] < 0.1: | |
| e["type"] = "Empalme" | |
| elif e["loss"] < 0.5: | |
| e["type"] = "Conector" | |
| else: | |
| e["type"] = "Evento fuerte" | |
| return events | |
| def extract(self): | |
| events = self.parse_events() | |
| events = self.classify(events) | |
| return { | |
| "header": self.parse_header(), | |
| "events": events | |
| } | |
| # ========================================================= | |
| # 2. ANALISIS | |
| # ========================================================= | |
| COEF = { | |
| 1310: 0.35, | |
| 1550: 0.22 | |
| } | |
| def analyze(data): | |
| try: | |
| events = data.get("events", []) | |
| header = data.get("header", {}) | |
| if not events: | |
| return None | |
| total_events = sum(e.get("loss", 0) for e in events) | |
| length = header.get("length", events[-1].get("dist", 0)) | |
| lam = int(header.get("lambda", 1550)) | |
| coef = COEF.get(lam, 0.22) | |
| fiber_loss = length * coef | |
| total = fiber_loss + total_events | |
| return { | |
| "length": length, | |
| "lambda": lam, | |
| "coef": coef, | |
| "events_loss": total_events, | |
| "fiber_loss": fiber_loss, | |
| "total_loss": total, | |
| "events": events | |
| } | |
| except Exception as e: | |
| print("ANALYZE ERROR:", e) | |
| return None | |
| # ========================================================= | |
| # 3. GRAFICO | |
| # ========================================================= | |
| def plot_otdr(events): | |
| try: | |
| if not events: | |
| return None | |
| dist = [0] | |
| loss = [0] | |
| acc = 0 | |
| for e in events: | |
| acc += e.get("loss", 0) | |
| dist.append(e.get("dist", 0)) | |
| loss.append(acc) | |
| plt.figure() | |
| plt.plot(dist, loss, marker="o") | |
| plt.gca().invert_yaxis() | |
| plt.grid() | |
| path = "/tmp/otdr.png" | |
| plt.savefig(path) | |
| plt.close() | |
| return path | |
| except Exception as e: | |
| print("PLOT ERROR:", e) | |
| return None | |
| # ========================================================= | |
| # 4. PDF | |
| # ========================================================= | |
| def generate_pdf(result): | |
| try: | |
| path = "/tmp/report.pdf" | |
| doc = SimpleDocTemplate(path) | |
| styles = getSampleStyleSheet() | |
| content = [] | |
| content.append( | |
| Paragraph("REPORTE OTDR", styles["Title"]) | |
| ) | |
| content.append(Spacer(1, 10)) | |
| content.append( | |
| Paragraph( | |
| f"Longitud: {result.get('length', 0)} km", | |
| styles["Normal"] | |
| ) | |
| ) | |
| content.append( | |
| Paragraph( | |
| f"Lambda: {result.get('lambda', 0)} nm", | |
| styles["Normal"] | |
| ) | |
| ) | |
| content.append( | |
| Paragraph( | |
| f"Perdida: {result.get('total_loss', 0):.2f} dB", | |
| styles["Normal"] | |
| ) | |
| ) | |
| doc.build(content) | |
| return path | |
| except Exception as e: | |
| print("PDF ERROR:", e) | |
| return None | |
| # ========================================================= | |
| # 5. MAIN | |
| # ========================================================= | |
| def process(file): | |
| try: | |
| if file is None: | |
| return "❌ Sin archivo", None, None | |
| parser = IndustrialSORParser(file.name) | |
| data = parser.extract() | |
| print("DEBUG DATA:", data) | |
| result = analyze(data) | |
| if result is None: | |
| return "❌ No se pudo analizar el archivo", None, None | |
| text = ( | |
| f"✔ Longitud: {result.get('length', 0)} km\n" | |
| f"✔ λ: {result.get('lambda', 0)} nm\n" | |
| f"✔ Pérdida total: {result.get('total_loss', 0):.3f} dB\n" | |
| f"✔ Eventos: {len(result.get('events', []))}\n" | |
| ) | |
| img = plot_otdr(result.get("events", [])) | |
| pdf = generate_pdf(result) | |
| return text, img, pdf | |
| except Exception as e: | |
| print("PROCESS ERROR:", e) | |
| return f"❌ Error crítico: {str(e)}", None, None | |
| # ========================================================= | |
| # 6. UI | |
| # ========================================================= | |
| with gr.Blocks() as app: | |
| gr.Markdown("# 📡 OTDR Analyzer (HF Ready)") | |
| file = gr.File(file_types=[".sor"]) | |
| btn = gr.Button("Analizar") | |
| out_text = gr.Textbox() | |
| out_img = gr.Image() | |
| out_pdf = gr.File() | |
| btn.click( | |
| process, | |
| inputs=file, | |
| outputs=[out_text, out_img, out_pdf] | |
| ) | |
| app.launch( | |
| server_name="0.0.0.0", | |
| server_port=7860 | |
| ) |