SPB Git

Repository Public

main.py 14.6 KB 330 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : KA Apify Actors9# File             : ka-instagram/src/main.py10# Module           : ka-instagram11# Repository       : https://git.spboucher.ai/ka-apify-actors12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# ==============================================================================88# Author: Simon-Pierre Boucher <contact@spboucher.ai>89# File:   src/main.py (ka-instagram)90# Desc:   Profils Instagram publics ULTRA DÉTAILLÉS via l'endpoint web officiel91#         web_profile_info (JSON du web public) : identité complète, compteurs,92#         12 derniers posts (likes/commentaires/vues/légende/musique/lieu/93#         co-auteurs/épinglés), agrégats d'engagement et de cadence, profils94#         reliés — + recherche d'utilisateurs (topsearch) en découverte.95# ==============================================================================96from __future__ import annotations9798import asyncio99import json100import urllib.parse101from datetime import datetime, timezone102103from apify import Actor104105from .net import Fetcher106107PROFILE_API = ("https://i.instagram.com/api/v1/users/web_profile_info/"108               "?username={u}")109SEARCH_API = ("https://www.instagram.com/web/search/topsearch/"110              "?context=blended&query={q}&count=30")111SEARCH_API_ALT = ("https://i.instagram.com/api/v1/web/search/topsearch/"112                  "?context=blended&query={q}&count=30")113HDRS = {"x-ig-app-id": "936619743392459", "Accept": "application/json"}114115116def _iso(ts) -> str | None:117    try:118        return datetime.fromtimestamp(int(ts), tz=timezone.utc) \119            .strftime("%Y-%m-%dT%H:%M:%SZ")120    except (TypeError, ValueError, OSError):121        return None122123124def _avg(vals: list) -> int | None:125    vals = [v for v in vals if isinstance(v, (int, float))]126    return round(sum(vals) / len(vals)) if vals else None127128129def parse_post(node: dict) -> dict:130    """Nœud média du fil → post détaillé (métriques, musique, lieu, épinglé)."""131    cap = (node.get("edge_media_to_caption") or {}).get("edges") or []132    music = node.get("clips_music_attribution_info") or {}133    dims = node.get("dimensions") or {}134    return {135        "id": node.get("id"),136        "shortcode": node.get("shortcode"),137        "url": f"https://www.instagram.com/p/{node.get('shortcode')}/",138        "type": ("reel" if node.get("product_type") == "clips"139                 else "video" if node.get("is_video") else140                 "carousel" if node.get("edge_sidecar_to_children")141                 else "image"),142        "caption": ((cap[0].get("node") or {}).get("text", "")143                    if cap else "")[:500],144        "likes": (node.get("edge_liked_by") or {}).get("count"),145        "comments": (node.get("edge_media_to_comment") or {}).get("count"),146        "video_views": node.get("video_view_count"),147        "video_duration_s": node.get("video_duration"),148        "timestamp": node.get("taken_at_timestamp"),149        "posted_at": _iso(node.get("taken_at_timestamp")),150        "display_url": node.get("display_url"),151        "thumbnail_url": node.get("thumbnail_src"),152        "width": dims.get("width"),153        "height": dims.get("height"),154        "is_pinned": bool(node.get("pinned_for_users")),155        "comments_disabled": node.get("comments_disabled"),156        "location": (node.get("location") or {}).get("name"),157        "coauthors": [c.get("username")158                      for c in (node.get("coauthor_producers") or [])159                      if c.get("username")],160        "music": ({"artist": music.get("artist_name"),161                   "song": music.get("song_name"),162                   "uses_original_audio": music.get("uses_original_audio")}163                  if music.get("song_name") or music.get("artist_name")164                  else None),165        "accessibility_caption": (node.get("accessibility_caption")166                                  or "")[:200] or None,167        "tagged_users": [((t.get("node") or {}).get("user") or {})168                         .get("username")169                         for t in ((node.get("edge_media_to_tagged_user")170                                    or {}).get("edges") or [])][:10],171    }172173174def parse_user(user: dict) -> dict:175    """Objet user web_profile_info → enregistrement riche standardisé."""176    posts = [parse_post((e.get("node") or {}))177             for e in ((user.get("edge_owner_to_timeline_media") or {})178                       .get("edges") or [])]179    followers = (user.get("edge_followed_by") or {}).get("count")180    avg_likes = _avg([p["likes"] for p in posts])181    avg_comments = _avg([p["comments"] for p in posts])182    videos = [p for p in posts if p["type"] in ("video", "reel")]183    avg_video_views = _avg([p["video_views"] for p in videos])184    engagement = None185    if followers and avg_likes is not None:186        engagement = round(187            (avg_likes + (avg_comments or 0)) / followers * 100, 3)188    timestamps = sorted(p["timestamp"] for p in posts189                        if isinstance(p["timestamp"], int))190    posts_per_week = None191    if len(timestamps) >= 3 and timestamps[-1] > timestamps[0]:192        span_weeks = (timestamps[-1] - timestamps[0]) / 604_800193        posts_per_week = round((len(timestamps) - 1) / span_weeks, 2)194    top_post = max((p for p in posts if isinstance(p["likes"], int)),195                   key=lambda p: p["likes"], default=None)196    related = []197    for edge in ((user.get("edge_related_profiles") or {}).get("edges") or []):198        n = edge.get("node") or {}199        if n.get("username"):200            related.append({"username": n["username"],201                            "full_name": n.get("full_name"),202                            "is_verified": n.get("is_verified"),203                            "is_private": n.get("is_private")})204    return {205        "kind": "profile",206        "platform": "instagram",207        "found": True,208        "id": user.get("id"),209        "username": user.get("username"),210        "full_name": user.get("full_name"),211        "biography": user.get("biography"),212        "pronouns": user.get("pronouns") or None,213        "external_url": user.get("external_url"),214        "bio_links": [b.get("url") for b in (user.get("bio_links") or [])215                      if b.get("url")],216        "followers": followers,217        "following": (user.get("edge_follow") or {}).get("count"),218        "posts_count": (user.get("edge_owner_to_timeline_media")219                        or {}).get("count"),220        "highlight_reels": user.get("highlight_reel_count"),221        "is_verified": user.get("is_verified"),222        "is_private": user.get("is_private"),223        "is_business": user.get("is_business_account"),224        "is_professional": user.get("is_professional_account"),225        "category": user.get("category_name"),226        "business_category": user.get("business_category_name"),227        "business_address": user.get("business_address_json"),228        "has_clips": user.get("has_clips"),229        "has_channel": user.get("has_channel"),230        "has_ar_effects": user.get("has_ar_effects"),231        "recently_joined": user.get("is_joined_recently"),232        "avatar": user.get("profile_pic_url_hd")233                  or user.get("profile_pic_url"),234        # agrégats calculés sur les 12 derniers posts235        "avg_likes": avg_likes,236        "avg_comments": avg_comments,237        "avg_video_views": avg_video_views,238        "engagement_rate_pct": engagement,239        "posts_per_week": posts_per_week,240        "last_post_at": _iso(timestamps[-1]) if timestamps else None,241        "video_share_pct": (round(len(videos) / len(posts) * 100)242                            if posts else None),243        "top_post": ({"url": top_post["url"], "likes": top_post["likes"],244                      "comments": top_post["comments"],245                      "type": top_post["type"]} if top_post else None),246        "recent_posts": posts,247        "related_profiles": related,248    }249250251async def main() -> None:252    async with Actor:253        inp = await Actor.get_input() or {}254        usernames = [u.strip().lstrip("@").lower()255                     for u in (inp.get("usernames") or []) if u and u.strip()]256        queries = [q.strip() for q in (inp.get("queries") or [])257                   if q and q.strip()]258        proxy = await Actor.create_proxy_configuration(259            actor_proxy_input=inp.get("proxyConfiguration"))260        fetcher = Fetcher(proxy, delay=float(inp.get("requestDelay") or 1))261        sem = asyncio.Semaphore(int(inp.get("concurrency") or 3))262263        async def one_profile(u: str) -> None:264            async with sem:265                miss = {"kind": "profile", "platform": "instagram",266                        "username": u, "found": False}267                try:268                    resp = await fetcher.get(PROFILE_API.format(u=u),269                                             headers=HDRS, session_id=u)270                except Exception as exc:271                    await Actor.push_data({**miss, "error": str(exc)[:200]})272                    return273                if resp.status_code == 404:274                    await Actor.push_data({**miss, "error": "http_404"})275                    return276                user = None277                if resp.status_code == 200:278                    try:279                        user = ((json.loads(resp.text).get("data") or {})280                                .get("user"))281                    except Exception:282                        user = None283                if not user:284                    await Actor.push_data(285                        {**miss, "error": f"http_{resp.status_code}"})286                    return287                await Actor.push_data(parse_user(user))288289        async def one_search(q: str) -> None:290            async with sem:291                data = {}292                for endpoint in (SEARCH_API, SEARCH_API_ALT):293                    u2 = endpoint.format(q=urllib.parse.quote(q))294                    try:295                        resp = await fetcher.get(u2, headers=HDRS,296                                                 session_id=f"srch{q[:4]}")297                    except Exception as exc:298                        Actor.log.warning(f"recherche '{q}' : {exc}")299                        continue300                    if resp.status_code == 200:301                        try:302                            data = json.loads(resp.text)303                        except Exception:304                            data = {}305                    if data.get("users"):306                        break307                if not data.get("users"):308                    Actor.log.warning(309                        f"recherche '{q}' : 0 user "310                        f"(http {resp.status_code}) {resp.text[:200]!r}")311                for item in data.get("users") or []:312                    u = item.get("user") or {}313                    if not u.get("username") or u.get("is_private"):314                        continue315                    await Actor.push_data({316                        "kind": "search_user",317                        "platform": "instagram",318                        "query": q,319                        "username": u.get("username"),320                        "full_name": u.get("full_name"),321                        "is_verified": u.get("is_verified"),322                        "followers": u.get("follower_count"),323                        "avatar": u.get("profile_pic_url"),324                    })325326        await asyncio.gather(*[one_profile(u) for u in usernames],327                             *[one_search(q) for q in queries])328        Actor.log.info(f"terminé : {len(usernames)} profils, "329                       f"{len(queries)} recherches")330
Files main
Menu

Theme