ATS-27 commited on
Commit
964c3cd
·
1 Parent(s): adad1d3

Fix syntax error by removing git merge markers from ethical assessment module

Browse files
Files changed (1) hide show
  1. integration_assets/ethical_assessment.py +360 -360
integration_assets/ethical_assessment.py CHANGED
@@ -1,4 +1,4 @@
1
- <<<<<<< HEAD
2
  """
3
  Ethical Assessment Module for AI-Generated Images
4
  Comprehensive evaluation of ethical concerns including:
@@ -1741,363 +1741,363 @@ def get_simple_status(assessment):
1741
  else:
1742
  return f"UNETHICAL (Risk: {risk:.1%}){flag_str}"
1743
  =======
1744
- """
1745
- Ethical Assessment Module for AI-Generated Images
1746
- Evaluates whether an AI-generated image's synthetic nature is detectable (ethical)
1747
- or if it presents high misuse risk (unethical)
1748
-
1749
- CRITICAL UPDATE: AI-generated images containing human faces are ALWAYS classified
1750
- as UNETHICAL due to privacy, consent, and deepfake concerns.
1751
- """
1752
-
1753
- import numpy as np
1754
- from scipy.ndimage import gaussian_filter
1755
- import numpy.fft as fft
1756
- from skimage.feature import local_binary_pattern
1757
- import cv2
1758
-
1759
- from detector import rgb_to_gray, extract_residual, fft_stats, lbp_entropy
1760
-
1761
-
1762
- class EthicalAssessment:
1763
- """Assesses ethical status of AI-generated images"""
1764
-
1765
- # Ethical classification thresholds
1766
- ETHICAL_THRESHOLD = 0.5 # Below = Ethical, Above = Unethical
1767
-
1768
- # Face detector (initialized once)
1769
- _face_cascade = None
1770
-
1771
- ETHICAL_CRITERIA = {
1772
- "high_quality_artifacts": {
1773
- "weight": 0.25,
1774
- "description": "Quality of generation (higher = more convincing/risky)"
1775
- },
1776
- "low_quality_artifacts": {
1777
- "weight": 0.20,
1778
- "description": "Detectable inconsistencies (higher = more obvious fake)"
1779
- },
1780
- "facial_consistency": {
1781
- "weight": 0.20,
1782
- "description": "Consistent facial features (higher = more natural)"
1783
- },
1784
- "lighting_anomalies": {
1785
- "weight": 0.15,
1786
- "description": "Lighting consistency (higher = more obvious artifacts)"
1787
- },
1788
- "frequency_analysis": {
1789
- "weight": 0.20,
1790
- "description": "GAN fingerprints (higher = more obvious synthetic patterns)"
1791
- }
1792
- }
1793
-
1794
- @classmethod
1795
- def _get_face_detector(cls):
1796
- """Get or initialize OpenCV face detector"""
1797
- if cls._face_cascade is None:
1798
- try:
1799
- # Try to load Haar Cascade face detector
1800
- cls._face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
1801
- except Exception as e:
1802
- print(f"Warning: Could not load face detector: {e}")
1803
- cls._face_cascade = None
1804
- return cls._face_cascade
1805
-
1806
- @classmethod
1807
- def detect_faces(cls, img_arr):
1808
- """Detect faces in image using OpenCV
1809
-
1810
- Returns:
1811
- tuple: (num_faces, face_bboxes)
1812
- """
1813
- try:
1814
- face_cascade = cls._get_face_detector()
1815
- if face_cascade is None:
1816
- return 0, []
1817
-
1818
- # Convert to grayscale for detection
1819
- if len(img_arr.shape) == 3:
1820
- gray = cv2.cvtColor((img_arr * 255).astype(np.uint8), cv2.COLOR_RGB2GRAY)
1821
- else:
1822
- gray = (img_arr * 255).astype(np.uint8)
1823
-
1824
- # Detect faces with tuned parameters for better detection
1825
- # Parameters tuned for AI-generated face detection (80% detection rate)
1826
- faces = face_cascade.detectMultiScale(
1827
- gray,
1828
- scaleFactor=1.05, # More sensitive to different face sizes
1829
- minNeighbors=3, # Lower threshold for face confirmation
1830
- minSize=(20, 20) # Detect smaller faces
1831
- )
1832
-
1833
- return len(faces), faces
1834
- except Exception as e:
1835
- print(f"Face detection error: {e}")
1836
- return 0, []
1837
-
1838
- @staticmethod
1839
- def extract_features(img_arr):
1840
- """Extract features for ethical assessment"""
1841
- try:
1842
- H, W, C = img_arr.shape
1843
- gray = rgb_to_gray(img_arr)
1844
-
1845
- # 1. Artifact Quality
1846
- residual = extract_residual(gray, sigma=1.5)
1847
- artifact_std = float(np.std(residual))
1848
- high_quality_artifacts = min(1.0, artifact_std * 2.0)
1849
-
1850
- # 2. Low-quality indicator
1851
- low_quality_score = min(1.0, artifact_std / 0.15)
1852
-
1853
- # 3. Facial consistency
1854
- _, hf_ratio = fft_stats(gray)
1855
- facial_consistency = 1.0 - min(1.0, hf_ratio)
1856
-
1857
- # 4. Lighting anomalies
1858
- try:
1859
- lbp = local_binary_pattern((gray * 255).astype(np.uint8), 8, 1, method='uniform')
1860
- lbp_variance = float(np.var(lbp))
1861
- lighting_anomaly = min(1.0, lbp_variance / 50.0)
1862
- except:
1863
- lighting_anomaly = 0.5
1864
- lbp_variance = 0.0
1865
-
1866
- # 5. Frequency domain analysis
1867
- F = fft.fft2(gray)
1868
- Fshift = fft.fftshift(F)
1869
- Fmag = np.abs(Fshift)
1870
-
1871
- h, w = gray.shape
1872
- center_h, center_w = h // 2, w // 2
1873
-
1874
- ring_pattern = 0.0
1875
- for r in [10, 20, 30]:
1876
- y, x = np.ogrid[-center_h:h-center_h, -center_w:w-center_w]
1877
- mask = (x**2 + y**2 >= (r-2)**2) & (x**2 + y**2 <= (r+2)**2)
1878
- ring_energy = np.mean(Fmag[mask]) if np.any(mask) else 0
1879
- ring_pattern = max(ring_pattern, ring_energy)
1880
-
1881
- frequency_risk = min(1.0, ring_pattern / (np.max(Fmag) + 1e-6) * 5)
1882
-
1883
- return {
1884
- "high_quality_artifacts": high_quality_artifacts,
1885
- "low_quality_artifacts": low_quality_score,
1886
- "facial_consistency": facial_consistency,
1887
- "lighting_anomalies": lighting_anomaly,
1888
- "frequency_analysis": frequency_risk,
1889
- "artifact_std": artifact_std,
1890
- "lbp_variance": lbp_variance
1891
- }
1892
- except Exception as e:
1893
- print(f"Feature extraction error: {e}")
1894
- return None
1895
-
1896
- @classmethod
1897
- def assess(cls, img_arr, threshold=None):
1898
- """
1899
- Assess ethical status of AI-generated image
1900
-
1901
- CRITICAL: Images with detected faces are ALWAYS classified as UNETHICAL
1902
-
1903
- Returns:
1904
- dict with ethical assessment details
1905
- """
1906
- # First, detect faces - AI-generated faces are ethically problematic
1907
- num_faces, face_bboxes = cls.detect_faces(img_arr)
1908
-
1909
- features = cls.extract_features(img_arr)
1910
-
1911
- if features is None:
1912
- return {
1913
- "is_ethical": True,
1914
- "status": "ASSESSMENT_FAILED",
1915
- "risk_score": 0.5,
1916
- "confidence": 0.0,
1917
- "details": "Could not assess image",
1918
- "faces_detected": num_faces
1919
- }
1920
-
1921
- # Calculate weighted risk score
1922
- risk_score = (
1923
- cls.ETHICAL_CRITERIA["high_quality_artifacts"]["weight"] *
1924
- features["high_quality_artifacts"] +
1925
-
1926
- cls.ETHICAL_CRITERIA["low_quality_artifacts"]["weight"] *
1927
- (1.0 - features["low_quality_artifacts"]) +
1928
-
1929
- cls.ETHICAL_CRITERIA["facial_consistency"]["weight"] *
1930
- (1.0 - features["facial_consistency"]) +
1931
-
1932
- cls.ETHICAL_CRITERIA["lighting_anomalies"]["weight"] *
1933
- features["lighting_anomalies"] +
1934
-
1935
- cls.ETHICAL_CRITERIA["frequency_analysis"]["weight"] *
1936
- features["frequency_analysis"]
1937
- )
1938
-
1939
- # Determine threshold to use (allow override)
1940
- use_threshold = cls.ETHICAL_THRESHOLD if threshold is None else float(threshold)
1941
-
1942
- # CRITICAL RULE: AI-generated images with faces are ALWAYS unethical
1943
- # due to privacy, consent, and deepfake misuse concerns
1944
- if num_faces > 0:
1945
- # Override classification for face detection
1946
- is_ethical = False
1947
- status = "UNETHICAL - FACES DETECTED"
1948
- # Boost risk score to reflect face presence
1949
- risk_score = max(risk_score, 0.85) # Ensure high risk
1950
- else:
1951
- # Classify based on artifact features only if no faces
1952
- is_ethical = risk_score <= use_threshold
1953
- status = "ETHICAL" if is_ethical else "UNETHICAL"
1954
-
1955
- # Calculate confidence (based on distance from used threshold)
1956
- distance_from_threshold = abs(risk_score - use_threshold)
1957
- confidence = max(0.0, min(1.0, 1.0 - (distance_from_threshold * 2.0)))
1958
-
1959
- return {
1960
- "is_ethical": is_ethical,
1961
- "status": status,
1962
- "risk_score": float(risk_score),
1963
- "confidence": float(confidence),
1964
- "threshold": float(use_threshold),
1965
- "faces_detected": num_faces,
1966
- "details": cls._get_status_details(is_ethical, risk_score, num_faces),
1967
- "explanation": cls._get_explanation(is_ethical, features, num_faces),
1968
- "recommendations": cls._get_recommendations(is_ethical, num_faces),
1969
- "features": features
1970
- }
1971
-
1972
- @staticmethod
1973
- def _get_status_details(is_ethical, risk_score, num_faces=0):
1974
- """Get detailed status message"""
1975
- if num_faces > 0:
1976
- return "UNETHICAL - Human faces detected in AI-generated image. High privacy/consent risk."
1977
-
1978
- if is_ethical:
1979
- if risk_score < 0.3:
1980
- return "SAFE - Image has clear detectable artifacts making it obviously synthetic"
1981
- else:
1982
- return "ETHICAL - Image is detectable as AI-generated with visible artifacts"
1983
- else:
1984
- if risk_score > 0.7:
1985
- return "HIGH RISK - Image is highly convincing with minimal detectable artifacts"
1986
- else:
1987
- return "RISKY - Image has subtle artifacts, higher misuse potential"
1988
-
1989
- @staticmethod
1990
- def _get_explanation(is_ethical, features, num_faces=0):
1991
- """Generate explanation for classification"""
1992
- explanations = []
1993
-
1994
- # Face detection takes priority in explanation
1995
- if num_faces > 0:
1996
- explanations.append("CRITICAL: Human faces detected in AI-generated content")
1997
- explanations.append("- AI-generated faces violate privacy and consent principles")
1998
- explanations.append("- High potential for deepfake misuse and impersonation")
1999
- explanations.append("- Cannot verify consent from depicted individual(s)")
2000
- return "\n".join(explanations)
2001
-
2002
- if is_ethical:
2003
- if features["artifact_std"] > 0.5:
2004
- explanations.append("- Strong residual artifacts detected")
2005
- if features["facial_consistency"] < 0.55:
2006
- explanations.append("- Inconsistent or uncanny facial features")
2007
- if features["frequency_analysis"] > 0.03:
2008
- explanations.append("- Visible frequency domain patterns typical of synthetic generation")
2009
-
2010
- if not explanations:
2011
- explanations.append("- Detectable synthetic characteristics present")
2012
- else:
2013
- if features["artifact_std"] <= 0.5:
2014
- explanations.append("- Smooth artifacts indicate high-quality generation")
2015
- if features["facial_consistency"] >= 0.55:
2016
- explanations.append("- Natural-looking facial features")
2017
- if features["lighting_anomalies"] <= 0.1:
2018
- explanations.append("- Consistent lighting throughout image")
2019
- if features["frequency_analysis"] <= 0.03:
2020
- explanations.append("- Minimal visible GAN fingerprints")
2021
-
2022
- return "\n".join(explanations) if explanations else "Limited feature information available"
2023
-
2024
- @staticmethod
2025
- def _get_recommendations(is_ethical, num_faces=0):
2026
- """Get recommendations based on ethical status"""
2027
- if num_faces > 0:
2028
- # Specific recommendations for face-containing AI images
2029
- return [
2030
- "DO NOT SHARE - High risk of privacy violation",
2031
- "REQUIRES EXPLICIT CONSENT from person(s) depicted",
2032
- "VERIFY compliance with deepfake and privacy laws",
2033
- "Could be illegal in many jurisdictions without consent",
2034
- "If consent obtained: Add prominent 'AI-GENERATED' watermark",
2035
- "Document consent and generation method for legal protection",
2036
- "Consider digital signatures to prevent misuse",
2037
- "Consult legal counsel before any distribution"
2038
- ]
2039
-
2040
- if is_ethical:
2041
- return [
2042
- "May be used for educational or artistic purposes",
2043
- "No exceptional privacy/consent concerns",
2044
- "Share with clear 'AI-generated' disclosure",
2045
- "Include metadata about generation method"
2046
- ]
2047
- else:
2048
- return [
2049
- "HIGH CAUTION: Requires explicit consent from person depicted",
2050
- "Must clearly disclose AI-generation before sharing",
2051
- "Do NOT use for deception or impersonation",
2052
- "Verify compliance with local deepfake laws",
2053
- "Consider adding watermarks or digital signatures",
2054
- "Document consent and creation details for legal protection"
2055
- ]
2056
-
2057
-
2058
- def format_ethical_report(assessment):
2059
- """Format ethical assessment for display"""
2060
- report = f"\n{'='*70}\n"
2061
- report += f"ETHICAL ASSESSMENT REPORT\n"
2062
- report += f"{'='*70}\n\n"
2063
-
2064
- # Status
2065
- report += f"STATUS: {assessment['status']}\n"
2066
- report += f"Risk Score: {assessment['risk_score']:.4f} (Threshold: {assessment.get('threshold', 0.5):.3f})\n"
2067
- report += f"Confidence: {assessment['confidence']*100:.1f}%\n\n"
2068
-
2069
- # Details
2070
- report += f"CLASSIFICATION DETAILS:\n"
2071
- report += f"{'-'*70}\n"
2072
- report += f"{assessment['details']}\n\n"
2073
-
2074
- # Explanation
2075
- report += f"TECHNICAL ANALYSIS:\n"
2076
- report += f"{'-'*70}\n"
2077
- report += f"{assessment['explanation']}\n\n"
2078
-
2079
- # Recommendations
2080
- report += f"RECOMMENDATIONS:\n"
2081
- report += f"{'-'*70}\n"
2082
- for rec in assessment['recommendations']:
2083
- report += f"{rec}\n"
2084
-
2085
- # Raw feature values (for debugging / tuning)
2086
- if 'features' in assessment and assessment['features'] is not None:
2087
- report += f"\nRAW FEATURES:\n"
2088
- report += f"{'-'*70}\n"
2089
- for k, v in assessment['features'].items():
2090
- report += f"{k}: {v}\n"
2091
-
2092
- report += f"\n{'='*70}\n"
2093
-
2094
- return report
2095
-
2096
-
2097
- def get_simple_status(assessment):
2098
- """Get simple one-line status"""
2099
- if assessment['is_ethical']:
2100
- return f"ETHICAL (Risk Score: {assessment['risk_score']:.3f})"
2101
- else:
2102
- return f"UNETHICAL (Risk Score: {assessment['risk_score']:.3f})"
2103
  >>>>>>> 65ab9814191b6bb448da441c53a768594e7d1d59
 
1
+ HEAD
2
  """
3
  Ethical Assessment Module for AI-Generated Images
4
  Comprehensive evaluation of ethical concerns including:
 
1741
  else:
1742
  return f"UNETHICAL (Risk: {risk:.1%}){flag_str}"
1743
  =======
1744
+ """
1745
+ Ethical Assessment Module for AI-Generated Images
1746
+ Evaluates whether an AI-generated image's synthetic nature is detectable (ethical)
1747
+ or if it presents high misuse risk (unethical)
1748
+
1749
+ CRITICAL UPDATE: AI-generated images containing human faces are ALWAYS classified
1750
+ as UNETHICAL due to privacy, consent, and deepfake concerns.
1751
+ """
1752
+
1753
+ import numpy as np
1754
+ from scipy.ndimage import gaussian_filter
1755
+ import numpy.fft as fft
1756
+ from skimage.feature import local_binary_pattern
1757
+ import cv2
1758
+
1759
+ from detector import rgb_to_gray, extract_residual, fft_stats, lbp_entropy
1760
+
1761
+
1762
+ class EthicalAssessment:
1763
+ """Assesses ethical status of AI-generated images"""
1764
+
1765
+ # Ethical classification thresholds
1766
+ ETHICAL_THRESHOLD = 0.5 # Below = Ethical, Above = Unethical
1767
+
1768
+ # Face detector (initialized once)
1769
+ _face_cascade = None
1770
+
1771
+ ETHICAL_CRITERIA = {
1772
+ "high_quality_artifacts": {
1773
+ "weight": 0.25,
1774
+ "description": "Quality of generation (higher = more convincing/risky)"
1775
+ },
1776
+ "low_quality_artifacts": {
1777
+ "weight": 0.20,
1778
+ "description": "Detectable inconsistencies (higher = more obvious fake)"
1779
+ },
1780
+ "facial_consistency": {
1781
+ "weight": 0.20,
1782
+ "description": "Consistent facial features (higher = more natural)"
1783
+ },
1784
+ "lighting_anomalies": {
1785
+ "weight": 0.15,
1786
+ "description": "Lighting consistency (higher = more obvious artifacts)"
1787
+ },
1788
+ "frequency_analysis": {
1789
+ "weight": 0.20,
1790
+ "description": "GAN fingerprints (higher = more obvious synthetic patterns)"
1791
+ }
1792
+ }
1793
+
1794
+ @classmethod
1795
+ def _get_face_detector(cls):
1796
+ """Get or initialize OpenCV face detector"""
1797
+ if cls._face_cascade is None:
1798
+ try:
1799
+ # Try to load Haar Cascade face detector
1800
+ cls._face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
1801
+ except Exception as e:
1802
+ print(f"Warning: Could not load face detector: {e}")
1803
+ cls._face_cascade = None
1804
+ return cls._face_cascade
1805
+
1806
+ @classmethod
1807
+ def detect_faces(cls, img_arr):
1808
+ """Detect faces in image using OpenCV
1809
+
1810
+ Returns:
1811
+ tuple: (num_faces, face_bboxes)
1812
+ """
1813
+ try:
1814
+ face_cascade = cls._get_face_detector()
1815
+ if face_cascade is None:
1816
+ return 0, []
1817
+
1818
+ # Convert to grayscale for detection
1819
+ if len(img_arr.shape) == 3:
1820
+ gray = cv2.cvtColor((img_arr * 255).astype(np.uint8), cv2.COLOR_RGB2GRAY)
1821
+ else:
1822
+ gray = (img_arr * 255).astype(np.uint8)
1823
+
1824
+ # Detect faces with tuned parameters for better detection
1825
+ # Parameters tuned for AI-generated face detection (80% detection rate)
1826
+ faces = face_cascade.detectMultiScale(
1827
+ gray,
1828
+ scaleFactor=1.05, # More sensitive to different face sizes
1829
+ minNeighbors=3, # Lower threshold for face confirmation
1830
+ minSize=(20, 20) # Detect smaller faces
1831
+ )
1832
+
1833
+ return len(faces), faces
1834
+ except Exception as e:
1835
+ print(f"Face detection error: {e}")
1836
+ return 0, []
1837
+
1838
+ @staticmethod
1839
+ def extract_features(img_arr):
1840
+ """Extract features for ethical assessment"""
1841
+ try:
1842
+ H, W, C = img_arr.shape
1843
+ gray = rgb_to_gray(img_arr)
1844
+
1845
+ # 1. Artifact Quality
1846
+ residual = extract_residual(gray, sigma=1.5)
1847
+ artifact_std = float(np.std(residual))
1848
+ high_quality_artifacts = min(1.0, artifact_std * 2.0)
1849
+
1850
+ # 2. Low-quality indicator
1851
+ low_quality_score = min(1.0, artifact_std / 0.15)
1852
+
1853
+ # 3. Facial consistency
1854
+ _, hf_ratio = fft_stats(gray)
1855
+ facial_consistency = 1.0 - min(1.0, hf_ratio)
1856
+
1857
+ # 4. Lighting anomalies
1858
+ try:
1859
+ lbp = local_binary_pattern((gray * 255).astype(np.uint8), 8, 1, method='uniform')
1860
+ lbp_variance = float(np.var(lbp))
1861
+ lighting_anomaly = min(1.0, lbp_variance / 50.0)
1862
+ except:
1863
+ lighting_anomaly = 0.5
1864
+ lbp_variance = 0.0
1865
+
1866
+ # 5. Frequency domain analysis
1867
+ F = fft.fft2(gray)
1868
+ Fshift = fft.fftshift(F)
1869
+ Fmag = np.abs(Fshift)
1870
+
1871
+ h, w = gray.shape
1872
+ center_h, center_w = h // 2, w // 2
1873
+
1874
+ ring_pattern = 0.0
1875
+ for r in [10, 20, 30]:
1876
+ y, x = np.ogrid[-center_h:h-center_h, -center_w:w-center_w]
1877
+ mask = (x**2 + y**2 >= (r-2)**2) & (x**2 + y**2 <= (r+2)**2)
1878
+ ring_energy = np.mean(Fmag[mask]) if np.any(mask) else 0
1879
+ ring_pattern = max(ring_pattern, ring_energy)
1880
+
1881
+ frequency_risk = min(1.0, ring_pattern / (np.max(Fmag) + 1e-6) * 5)
1882
+
1883
+ return {
1884
+ "high_quality_artifacts": high_quality_artifacts,
1885
+ "low_quality_artifacts": low_quality_score,
1886
+ "facial_consistency": facial_consistency,
1887
+ "lighting_anomalies": lighting_anomaly,
1888
+ "frequency_analysis": frequency_risk,
1889
+ "artifact_std": artifact_std,
1890
+ "lbp_variance": lbp_variance
1891
+ }
1892
+ except Exception as e:
1893
+ print(f"Feature extraction error: {e}")
1894
+ return None
1895
+
1896
+ @classmethod
1897
+ def assess(cls, img_arr, threshold=None):
1898
+ """
1899
+ Assess ethical status of AI-generated image
1900
+
1901
+ CRITICAL: Images with detected faces are ALWAYS classified as UNETHICAL
1902
+
1903
+ Returns:
1904
+ dict with ethical assessment details
1905
+ """
1906
+ # First, detect faces - AI-generated faces are ethically problematic
1907
+ num_faces, face_bboxes = cls.detect_faces(img_arr)
1908
+
1909
+ features = cls.extract_features(img_arr)
1910
+
1911
+ if features is None:
1912
+ return {
1913
+ "is_ethical": True,
1914
+ "status": "ASSESSMENT_FAILED",
1915
+ "risk_score": 0.5,
1916
+ "confidence": 0.0,
1917
+ "details": "Could not assess image",
1918
+ "faces_detected": num_faces
1919
+ }
1920
+
1921
+ # Calculate weighted risk score
1922
+ risk_score = (
1923
+ cls.ETHICAL_CRITERIA["high_quality_artifacts"]["weight"] *
1924
+ features["high_quality_artifacts"] +
1925
+
1926
+ cls.ETHICAL_CRITERIA["low_quality_artifacts"]["weight"] *
1927
+ (1.0 - features["low_quality_artifacts"]) +
1928
+
1929
+ cls.ETHICAL_CRITERIA["facial_consistency"]["weight"] *
1930
+ (1.0 - features["facial_consistency"]) +
1931
+
1932
+ cls.ETHICAL_CRITERIA["lighting_anomalies"]["weight"] *
1933
+ features["lighting_anomalies"] +
1934
+
1935
+ cls.ETHICAL_CRITERIA["frequency_analysis"]["weight"] *
1936
+ features["frequency_analysis"]
1937
+ )
1938
+
1939
+ # Determine threshold to use (allow override)
1940
+ use_threshold = cls.ETHICAL_THRESHOLD if threshold is None else float(threshold)
1941
+
1942
+ # CRITICAL RULE: AI-generated images with faces are ALWAYS unethical
1943
+ # due to privacy, consent, and deepfake misuse concerns
1944
+ if num_faces > 0:
1945
+ # Override classification for face detection
1946
+ is_ethical = False
1947
+ status = "UNETHICAL - FACES DETECTED"
1948
+ # Boost risk score to reflect face presence
1949
+ risk_score = max(risk_score, 0.85) # Ensure high risk
1950
+ else:
1951
+ # Classify based on artifact features only if no faces
1952
+ is_ethical = risk_score <= use_threshold
1953
+ status = "ETHICAL" if is_ethical else "UNETHICAL"
1954
+
1955
+ # Calculate confidence (based on distance from used threshold)
1956
+ distance_from_threshold = abs(risk_score - use_threshold)
1957
+ confidence = max(0.0, min(1.0, 1.0 - (distance_from_threshold * 2.0)))
1958
+
1959
+ return {
1960
+ "is_ethical": is_ethical,
1961
+ "status": status,
1962
+ "risk_score": float(risk_score),
1963
+ "confidence": float(confidence),
1964
+ "threshold": float(use_threshold),
1965
+ "faces_detected": num_faces,
1966
+ "details": cls._get_status_details(is_ethical, risk_score, num_faces),
1967
+ "explanation": cls._get_explanation(is_ethical, features, num_faces),
1968
+ "recommendations": cls._get_recommendations(is_ethical, num_faces),
1969
+ "features": features
1970
+ }
1971
+
1972
+ @staticmethod
1973
+ def _get_status_details(is_ethical, risk_score, num_faces=0):
1974
+ """Get detailed status message"""
1975
+ if num_faces > 0:
1976
+ return "UNETHICAL - Human faces detected in AI-generated image. High privacy/consent risk."
1977
+
1978
+ if is_ethical:
1979
+ if risk_score < 0.3:
1980
+ return "SAFE - Image has clear detectable artifacts making it obviously synthetic"
1981
+ else:
1982
+ return "ETHICAL - Image is detectable as AI-generated with visible artifacts"
1983
+ else:
1984
+ if risk_score > 0.7:
1985
+ return "HIGH RISK - Image is highly convincing with minimal detectable artifacts"
1986
+ else:
1987
+ return "RISKY - Image has subtle artifacts, higher misuse potential"
1988
+
1989
+ @staticmethod
1990
+ def _get_explanation(is_ethical, features, num_faces=0):
1991
+ """Generate explanation for classification"""
1992
+ explanations = []
1993
+
1994
+ # Face detection takes priority in explanation
1995
+ if num_faces > 0:
1996
+ explanations.append("CRITICAL: Human faces detected in AI-generated content")
1997
+ explanations.append("- AI-generated faces violate privacy and consent principles")
1998
+ explanations.append("- High potential for deepfake misuse and impersonation")
1999
+ explanations.append("- Cannot verify consent from depicted individual(s)")
2000
+ return "\n".join(explanations)
2001
+
2002
+ if is_ethical:
2003
+ if features["artifact_std"] > 0.5:
2004
+ explanations.append("- Strong residual artifacts detected")
2005
+ if features["facial_consistency"] < 0.55:
2006
+ explanations.append("- Inconsistent or uncanny facial features")
2007
+ if features["frequency_analysis"] > 0.03:
2008
+ explanations.append("- Visible frequency domain patterns typical of synthetic generation")
2009
+
2010
+ if not explanations:
2011
+ explanations.append("- Detectable synthetic characteristics present")
2012
+ else:
2013
+ if features["artifact_std"] <= 0.5:
2014
+ explanations.append("- Smooth artifacts indicate high-quality generation")
2015
+ if features["facial_consistency"] >= 0.55:
2016
+ explanations.append("- Natural-looking facial features")
2017
+ if features["lighting_anomalies"] <= 0.1:
2018
+ explanations.append("- Consistent lighting throughout image")
2019
+ if features["frequency_analysis"] <= 0.03:
2020
+ explanations.append("- Minimal visible GAN fingerprints")
2021
+
2022
+ return "\n".join(explanations) if explanations else "Limited feature information available"
2023
+
2024
+ @staticmethod
2025
+ def _get_recommendations(is_ethical, num_faces=0):
2026
+ """Get recommendations based on ethical status"""
2027
+ if num_faces > 0:
2028
+ # Specific recommendations for face-containing AI images
2029
+ return [
2030
+ "DO NOT SHARE - High risk of privacy violation",
2031
+ "REQUIRES EXPLICIT CONSENT from person(s) depicted",
2032
+ "VERIFY compliance with deepfake and privacy laws",
2033
+ "Could be illegal in many jurisdictions without consent",
2034
+ "If consent obtained: Add prominent 'AI-GENERATED' watermark",
2035
+ "Document consent and generation method for legal protection",
2036
+ "Consider digital signatures to prevent misuse",
2037
+ "Consult legal counsel before any distribution"
2038
+ ]
2039
+
2040
+ if is_ethical:
2041
+ return [
2042
+ "May be used for educational or artistic purposes",
2043
+ "No exceptional privacy/consent concerns",
2044
+ "Share with clear 'AI-generated' disclosure",
2045
+ "Include metadata about generation method"
2046
+ ]
2047
+ else:
2048
+ return [
2049
+ "HIGH CAUTION: Requires explicit consent from person depicted",
2050
+ "Must clearly disclose AI-generation before sharing",
2051
+ "Do NOT use for deception or impersonation",
2052
+ "Verify compliance with local deepfake laws",
2053
+ "Consider adding watermarks or digital signatures",
2054
+ "Document consent and creation details for legal protection"
2055
+ ]
2056
+
2057
+
2058
+ def format_ethical_report(assessment):
2059
+ """Format ethical assessment for display"""
2060
+ report = f"\n{'='*70}\n"
2061
+ report += f"ETHICAL ASSESSMENT REPORT\n"
2062
+ report += f"{'='*70}\n\n"
2063
+
2064
+ # Status
2065
+ report += f"STATUS: {assessment['status']}\n"
2066
+ report += f"Risk Score: {assessment['risk_score']:.4f} (Threshold: {assessment.get('threshold', 0.5):.3f})\n"
2067
+ report += f"Confidence: {assessment['confidence']*100:.1f}%\n\n"
2068
+
2069
+ # Details
2070
+ report += f"CLASSIFICATION DETAILS:\n"
2071
+ report += f"{'-'*70}\n"
2072
+ report += f"{assessment['details']}\n\n"
2073
+
2074
+ # Explanation
2075
+ report += f"TECHNICAL ANALYSIS:\n"
2076
+ report += f"{'-'*70}\n"
2077
+ report += f"{assessment['explanation']}\n\n"
2078
+
2079
+ # Recommendations
2080
+ report += f"RECOMMENDATIONS:\n"
2081
+ report += f"{'-'*70}\n"
2082
+ for rec in assessment['recommendations']:
2083
+ report += f"{rec}\n"
2084
+
2085
+ # Raw feature values (for debugging / tuning)
2086
+ if 'features' in assessment and assessment['features'] is not None:
2087
+ report += f"\nRAW FEATURES:\n"
2088
+ report += f"{'-'*70}\n"
2089
+ for k, v in assessment['features'].items():
2090
+ report += f"{k}: {v}\n"
2091
+
2092
+ report += f"\n{'='*70}\n"
2093
+
2094
+ return report
2095
+
2096
+
2097
+ def get_simple_status(assessment):
2098
+ """Get simple one-line status"""
2099
+ if assessment['is_ethical']:
2100
+ return f"ETHICAL (Risk Score: {assessment['risk_score']:.3f})"
2101
+ else:
2102
+ return f"UNETHICAL (Risk Score: {assessment['risk_score']:.3f})"
2103
  >>>>>>> 65ab9814191b6bb448da441c53a768594e7d1d59