← back to dan10002ht__pipe-counter

Function bodies 24 total

All specs Real LLM only Function bodies
GeneratedPluginRegistrant class · java · L15-L44 (30 LOC)
flutter_app/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
public final class GeneratedPluginRegistrant {
  private static final String TAG = "GeneratedPluginRegistrant";
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.camerax.CameraAndroidCameraxPlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin camera_android_camerax, io.flutter.plugins.camerax.CameraAndroidCameraxPlugin", e);
    }
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin flutter_plugin_android_lifecycle, io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin", e);
    }
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.imagepicker.ImagePickerPlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin image_picker_android, io.flutter.
registerWith method · java · L17-L43 (27 LOC)
flutter_app/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.camerax.CameraAndroidCameraxPlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin camera_android_camerax, io.flutter.plugins.camerax.CameraAndroidCameraxPlugin", e);
    }
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin flutter_plugin_android_lifecycle, io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecyclePlugin", e);
    }
    try {
      flutterEngine.getPlugins().add(new io.flutter.plugins.imagepicker.ImagePickerPlugin());
    } catch (Exception e) {
      Log.e(TAG, "Error registering plugin image_picker_android, io.flutter.plugins.imagepicker.ImagePickerPlugin", e);
    }
    try {
      flutterEngine.getPlugins().add(new io.flutter.
PipeCounterApp class · dart · L16-L46 (31 LOC)
flutter_app/lib/main.dart
class PipeCounterApp extends StatelessWidget {
  const PipeCounterApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pipe Counter',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorSchemeSeed: const Color(0xFF1565C0),
        useMaterial3: true,
        brightness: Brightness.light,
        fontFamily: 'SF Pro Display',
        appBarTheme: const AppBarTheme(
          centerTitle: true,
          elevation: 0,
          scrolledUnderElevation: 2,
        ),
        filledButtonTheme: FilledButtonThemeData(
          style: FilledButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 16),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
          ),
        ),
      ),
      home: const HomeScreen(),
    );
  }
}
HistoryEntry class · dart · L6-L16 (11 LOC)
flutter_app/lib/screens/history_screen.dart
class HistoryEntry {
  final Uint8List imageBytes;
  final DetectionResult result;
  final DateTime timestamp;

  HistoryEntry({
    required this.imageBytes,
    required this.result,
    required this.timestamp,
  });
}
HistoryScreen class · dart · L18-L66 (49 LOC)
flutter_app/lib/screens/history_screen.dart
class HistoryScreen extends StatelessWidget {
  final List<HistoryEntry> history;

  const HistoryScreen({super.key, required this.history});

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'History',
          style: TextStyle(fontWeight: FontWeight.w700),
        ),
      ),
      body: history.isEmpty
          ? Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.history, size: 56, color: colorScheme.outline),
                  const SizedBox(height: 12),
                  Text(
                    'No detections yet',
                    style: TextStyle(color: colorScheme.onSurfaceVariant),
                  ),
                ],
              ),
            )
          : ListView.builder(
              padding: const EdgeInsets.all(16),
              it
_HistoryCard class · dart · L68-L138 (71 LOC)
flutter_app/lib/screens/history_screen.dart
class _HistoryCard extends StatelessWidget {
  final HistoryEntry entry;
  final VoidCallback onTap;

  const _HistoryCard({required this.entry, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final time = entry.timestamp;
    final timeStr =
        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    final dateStr =
        '${time.day}/${time.month}/${time.year}';

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      clipBehavior: Clip.antiAlias,
      elevation: 0,
      color: colorScheme.surfaceContainerLow,
      child: InkWell(
        onTap: onTap,
        child: Row(
          children: [
            // Thumbnail
            SizedBox(
              width: 90,
              height: 90,
              child: Image.memory(entry.imageBytes, fit: BoxFit.cover),
     
_HistoryDetailScreen class · dart · L140-L229 (90 LOC)
flutter_app/lib/screens/history_screen.dart
class _HistoryDetailScreen extends StatelessWidget {
  final HistoryEntry entry;

  const _HistoryDetailScreen({required this.entry});

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      appBar: AppBar(
        title: Text(
          '${entry.result.count} Pipes',
          style: const TextStyle(fontWeight: FontWeight.w700),
        ),
      ),
      body: Column(
        children: [
          // Image with overlay
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20),
                child: InteractiveViewer(
                  minScale: 0.5,
                  maxScale: 5.0,
                  child: DetectionOverlay(
                    imageBytes: entry.imageBytes,
                    detections: entry.result.detections,
                  ),
                ),
             
Repobility (the analyzer behind this table) · https://repobility.com
_StatItem class · dart · L231-L270 (40 LOC)
flutter_app/lib/screens/history_screen.dart
class _StatItem extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  final Color color;

  const _StatItem({
    required this.label,
    required this.value,
    required this.icon,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, color: color, size: 22),
        const SizedBox(height: 6),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w700,
            color: color,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Theme.of(context).colorScheme.onSurfaceVariant,
          ),
        ),
      ],
    );
  }
}
HomeScreen class · dart · L9-L14 (6 LOC)
flutter_app/lib/screens/home_screen.dart
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}
_HomeScreenState class · dart · L16-L346 (331 LOC)
flutter_app/lib/screens/home_screen.dart
class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  final DetectorService _detector = DetectorService();
  final ImagePicker _picker = ImagePicker();

  Uint8List? _imageBytes;
  DetectionResult? _result;
  bool _isLoading = false;
  bool _modelLoaded = false;
  String _statusMessage = 'Loading model...';

  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;

  // History of results
  final List<HistoryEntry> _history = [];

  @override
  void initState() {
    super.initState();
    _fadeController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    _fadeAnimation = CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeOut,
    );
    _loadModel();
  }

  Future<void> _loadModel() async {
    try {
      await _detector.loadModel();
      setState(() {
        _modelLoaded = true;
        _statusMessage = '';
      });
    } catch (e) {
      setState(()
_DetectionDetailsSheet class · dart · L349-L484 (136 LOC)
flutter_app/lib/screens/home_screen.dart
class _DetectionDetailsSheet extends StatelessWidget {
  final DetectionResult result;

  const _DetectionDetailsSheet({required this.result});

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return DraggableScrollableSheet(
      initialChildSize: 0.45,
      minChildSize: 0.3,
      maxChildSize: 0.8,
      builder: (context, scrollController) {
        return Container(
          decoration: BoxDecoration(
            color: colorScheme.surface,
            borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
          ),
          child: Column(
            children: [
              const SizedBox(height: 12),
              Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: colorScheme.outlineVariant,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              Padding(
      
_ConfidenceBadge class · dart · L486-L523 (38 LOC)
flutter_app/lib/screens/home_screen.dart
class _ConfidenceBadge extends StatelessWidget {
  final double confidence;
  final String label;

  const _ConfidenceBadge({required this.confidence, required this.label});

  @override
  Widget build(BuildContext context) {
    final Color color;
    final Color textColor;
    if (confidence > 0.8) {
      color = Colors.green;
      textColor = Colors.green.shade700;
    } else if (confidence > 0.6) {
      color = Colors.orange;
      textColor = Colors.orange.shade700;
    } else {
      color = Colors.red;
      textColor = Colors.red.shade700;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: color.withOpacity(0.12),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        label,
        style: TextStyle(
          color: textColor,
          fontWeight: FontWeight.w700,
          fontSize: 13,
        ),
      ),
    );
  }
}
Detection class · dart · L10-L24 (15 LOC)
flutter_app/lib/services/detector_service.dart
class Detection {
  final double x;
  final double y;
  final double width;
  final double height;
  final double confidence;

  Detection({
    required this.x,
    required this.y,
    required this.width,
    required this.height,
    required this.confidence,
  });
}
DetectionResult class · dart · L26-L32 (7 LOC)
flutter_app/lib/services/detector_service.dart
class DetectionResult {
  final List<Detection> detections;

  DetectionResult({required this.detections});

  int get count => detections.length;
}
DetectorService class · dart · L34-L161 (128 LOC)
flutter_app/lib/services/detector_service.dart
class DetectorService {
  static const String _modelAsset = 'assets/models/best.onnx';
  static const int _inputSize = 640;
  static const double _confThreshold = 0.5;
  static const double _iouThreshold = 0.45;

  OrtSession? _session;

  Future<void> loadModel() async {
    OrtEnv.instance.init();

    // Copy asset to temp file (ONNX Runtime needs a file path)
    final byteData = await rootBundle.load(_modelAsset);
    final tempDir = await getTemporaryDirectory();
    final modelFile = File(p.join(tempDir.path, 'best.onnx'));
    await modelFile.writeAsBytes(byteData.buffer.asUint8List());

    final sessionOptions = OrtSessionOptions();
    _session = OrtSession.fromFile(modelFile, sessionOptions);
  }

  void dispose() {
    _session?.release();
    OrtEnv.instance.release();
  }

  /// Detect pipes from image bytes
  Future<DetectionResult> detectFromBytes(Uint8List imageBytes) async {
    if (_session == null) {
      throw Exception('Model not loaded. Call loadModel() first.'
Powered by Repobility — scan your code at https://repobility.com
DetectionOverlay class · dart · L5-L31 (27 LOC)
flutter_app/lib/widgets/detection_overlay.dart
class DetectionOverlay extends StatelessWidget {
  final Uint8List imageBytes;
  final List<Detection> detections;

  const DetectionOverlay({
    super.key,
    required this.imageBytes,
    required this.detections,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Stack(
          fit: StackFit.expand,
          children: [
            Image.memory(imageBytes, fit: BoxFit.contain),
            CustomPaint(
              painter: _DetectionPainter(detections: detections),
            ),
          ],
        );
      },
    );
  }
}
_DetectionPainter class · dart · L33-L128 (96 LOC)
flutter_app/lib/widgets/detection_overlay.dart
class _DetectionPainter extends CustomPainter {
  final List<Detection> detections;

  _DetectionPainter({required this.detections});

  @override
  void paint(Canvas canvas, Size size) {
    for (int i = 0; i < detections.length; i++) {
      final det = detections[i];
      final conf = det.confidence;

      // Color based on confidence
      final color = conf > 0.8
          ? const Color(0xFF4CAF50)
          : conf > 0.6
              ? const Color(0xFFFF9800)
              : const Color(0xFFF44336);

      final boxPaint = Paint()
        ..color = color
        ..style = PaintingStyle.stroke
        ..strokeWidth = 2.5;

      final rect = Rect.fromLTWH(det.x, det.y, det.width, det.height);

      // Draw rounded rect
      final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(4));
      canvas.drawRRect(rrect, boxPaint);

      // Draw corner accents
      _drawCornerAccents(canvas, rect, color);

      // Draw label background
      final label = '#${i + 1}';
   
ResultCard class · dart · L4-L102 (99 LOC)
flutter_app/lib/widgets/result_card.dart
class ResultCard extends StatelessWidget {
  final DetectionResult result;
  final VoidCallback? onTapDetails;

  const ResultCard({
    super.key,
    required this.result,
    this.onTapDetails,
  });

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final avgConf = result.detections.isEmpty
        ? 0.0
        : result.detections.map((d) => d.confidence).reduce((a, b) => a + b) /
            result.detections.length;

    return GestureDetector(
      onTap: onTapDetails,
      child: Container(
        margin: const EdgeInsets.fromLTRB(16, 4, 16, 4),
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              colorScheme.primary,
              colorScheme.primary.withOpacity(0.85),
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          bord
AppDelegate class · swift · L5-L13 (9 LOC)
flutter_app/macos/Runner/AppDelegate.swift
class AppDelegate: FlutterAppDelegate {
  override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    return true
  }

  override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
    return true
  }
}
MainFlutterWindow class · swift · L4-L15 (12 LOC)
flutter_app/macos/Runner/MainFlutterWindow.swift
class MainFlutterWindow: NSWindow {
  override func awakeFromNib() {
    let flutterViewController = FlutterViewController()
    let windowFrame = self.frame
    self.contentViewController = flutterViewController
    self.setFrame(windowFrame, display: true)

    RegisterGeneratedPlugins(registry: flutterViewController)

    super.awakeFromNib()
  }
}
RunnerTests class · swift · L5-L12 (8 LOC)
flutter_app/macos/RunnerTests/RunnerTests.swift
class RunnerTests: XCTestCase {

  func testExample() {
    // If you add code to the Runner application, consider adding tests here.
    // See https://developer.apple.com/documentation/xctest for more information about using XCTest.
  }

}
export function · python · L13-L28 (16 LOC)
training/scripts/export_tflite.py
def export():
    if not Path(MODEL_PATH).exists():
        print(f"Model not found at {MODEL_PATH}")
        print("Please train the model first: python scripts/train.py")
        return

    model = YOLO(MODEL_PATH)

    model.export(
        format="onnx",
        imgsz=640,
        simplify=True,
    )

    print("Export complete!")
    print("Copy the .onnx file to: flutter_app/assets/models/best.onnx")
split_dataset function · python · L12-L46 (35 LOC)
training/scripts/prepare_data.py
def split_dataset(data_dir: str = "data", val_ratio: float = 0.2):
    images_dir = Path(data_dir) / "images"
    labels_dir = Path(data_dir) / "labels"

    train_img = Path(data_dir) / "train" / "images"
    train_lbl = Path(data_dir) / "train" / "labels"
    val_img = Path(data_dir) / "val" / "images"
    val_lbl = Path(data_dir) / "val" / "labels"

    for d in [train_img, train_lbl, val_img, val_lbl]:
        d.mkdir(parents=True, exist_ok=True)

    # Get all image files
    extensions = {".jpg", ".jpeg", ".png", ".bmp"}
    images = [f for f in images_dir.iterdir() if f.suffix.lower() in extensions]
    random.shuffle(images)

    val_count = int(len(images) * val_ratio)
    val_images = images[:val_count]
    train_images = images[val_count:]

    def copy_pair(img_path: Path, dst_img: Path, dst_lbl: Path):
        shutil.copy2(img_path, dst_img / img_path.name)
        label_file = labels_dir / f"{img_path.stem}.txt"
        if label_file.exists():
            shutil.copy2(lab
Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
train function · python · L21-L48 (28 LOC)
training/scripts/train.py
def train(model_size: str = "n", resume: bool = False):
    if resume:
        model = YOLO("runs/detect/pipe_detector/weights/last.pt")
    else:
        model = YOLO(MODEL_SIZES[model_size])

    model.train(
        data="data/dataset.yaml",
        epochs=150,
        imgsz=640,
        batch=16,
        name="pipe_detector",
        exist_ok=True,     # overwrite previous run
        patience=30,       # early stopping
        save=True,
        device="mps",      # Apple Silicon GPU; change to "0" for NVIDIA, "cpu" for CPU
        # Data augmentation for better generalization
        augment=True,
        hsv_h=0.015,       # hue shift
        hsv_s=0.7,         # saturation shift
        hsv_v=0.4,         # brightness shift
        flipud=0.5,        # vertical flip
        fliplr=0.5,        # horizontal flip
        mosaic=1.0,        # mosaic augmentation
        scale=0.5,         # scale augmentation
    )

    print("Training complete! Best model saved at: runs/detect/pip