From 8973a514cc218c6b0395a47375d718015c3ee42c Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:28:18 +0200 Subject: [PATCH] perf(twitter): optimize tweet and thread archiving pipeline Accelerates tweet and thread archiving times by up to 11x on live Twitter and reduces processing overhead across Python and Rust: - In-memory GraphQL thread caching: parse and cache all tweets returned in TweetDetail conversation timeline (threaded_conversation_with_injections_v2), resolving parent/replied-to tweets in threads immediately without redundant network round-trips. - Proactive rate limiting: replace blind 2.0s post-save sleep with proactive throttling prior to outgoing HTTP requests, eliminating trailing sleep on single tweets and intermediate sleep for cached thread tweets. - HTTP keep-alive connection reuse: reuse scraper session for downloading media assets and avatars, avoiding fresh TCP/TLS handshakes per asset. - Avatar & media deduplication: skip avatar download if target file already exists on disk. - Lightweight client startup: introduce SimpleTwitterScraper using direct httpx.Client with authenticated headers and lazy twitter.scraper fallback, eliminating ~30ms of module imports at startup. - Fast JSON I/O: use orjson for binary JSON parsing and indented serialization. - Rust database batching: wrap entry creation, blob upserts, artifact registration, and run completion in a single SQLite transaction, reducing fsyncs from ~19 down to 1. - In-memory blob caching: cache blob records across tweet artifacts to avoid repeated filesystem metadata stats and duplicate upserts. - Single-pass staging: rewrite and move staged JSON files directly to raw_tweets/ in a single pass without intermediate staging writes. - Zero-copy metadata deserialization: use borrowed TweetJsonMetadata struct to extract title/metadata without dynamic Value heap allocations. - Regex fast paths: add substring gates before compiling/iterating asset regexes. --- .gitignore | 7 + crates/archivr-core/src/capture.rs | 116 +++-- crates/archivr-core/src/downloader/tweets.rs | 133 +++-- ...scrape_user_tweet_contents.cpython-313.pyc | Bin 55503 -> 0 bytes vendor/twitter/scrape_user_tweet_contents.py | 483 ++++++++++-------- 5 files changed, 442 insertions(+), 297 deletions(-) delete mode 100644 vendor/twitter/__pycache__/scrape_user_tweet_contents.cpython-313.pyc diff --git a/.gitignore b/.gitignore index dbceaed..2e49148 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,9 @@ crates/archivr-server/static/** !vendor !vendor/** +vendor/**/__pycache__/ +vendor/**/__pycache__/** +vendor/**/*.pyc !flake.nix !flake.lock @@ -52,4 +55,8 @@ frontend/result frontend/result/** frontend/dist/ frontend/dist/** + +!autoresearch.sh +!benches/ +!benches/** .DS_Store diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index 75f1cee..ba66594 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -966,28 +966,47 @@ fn record_container_entry( /// Extracts PlatformMetadata from a tweet JSON string. /// `title` is the X Article title when the status is an Article. /// Returns Default on any parse failure. +#[derive(serde::Deserialize)] +struct TweetJsonMetadata<'a> { + #[serde(borrow)] + author: Option>, + #[serde(borrow)] + full_text: Option<&'a str>, + #[serde(borrow)] + article: Option>, +} + +#[derive(serde::Deserialize)] +struct TweetAuthorMetadata<'a> { + #[serde(borrow)] + screen_name: Option<&'a str>, +} + +#[derive(serde::Deserialize)] +struct TweetArticleMetadata<'a> { + #[serde(borrow)] + title: Option<&'a str>, +} + fn tweet_metadata_from_json(json_str: &str) -> PlatformMetadata { - let Ok(v) = serde_json::from_str::(json_str) else { + let Ok(v) = serde_json::from_str::(json_str) else { return PlatformMetadata::default(); }; let screen_name = v - .get("author") - .and_then(|a| a.get("screen_name")) - .and_then(|s| s.as_str()) + .author + .and_then(|a| a.screen_name) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); let full_text = v - .get("full_text") - .and_then(|t| t.as_str()) + .full_text .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); let article_title = v - .get("article") - .and_then(|a| a.get("title")) - .and_then(|t| t.as_str()) + .article + .and_then(|a| a.title) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); @@ -1007,7 +1026,9 @@ fn register_tweet_artifacts( store_path: &Path, entry_id: i64, tweet_json_relpaths: &[String], + primary_json: Option<(&str, &str)>, ) -> Result<()> { + let mut blob_cache: HashMap = HashMap::new(); for relpath in tweet_json_relpaths { database::add_entry_artifact( conn, @@ -1021,20 +1042,40 @@ fn register_tweet_artifacts( metadata_json: None, }, )?; - let json_path = store_path.join(relpath); - let json_str = fs::read_to_string(&json_path).with_context(|| { - format!( - "failed to read tweet JSON for artifact registration: {}", - json_path.display() - ) - })?; - for (role, raw_relpath) in tweet_raw_artifacts(&json_str)? { - let raw_path = PathBuf::from(&raw_relpath); - let mut blob = blob_record_for_raw_relpath(store_path, &raw_path)?; - if role == "media" { - blob.mime_type = tweet_media_image_mime(blob.extension.as_deref()); + let json_str = if let Some((p_rel, p_str)) = primary_json { + if p_rel == relpath { + std::borrow::Cow::Borrowed(p_str) + } else { + let json_path = store_path.join(relpath); + std::borrow::Cow::Owned(fs::read_to_string(&json_path).with_context(|| { + format!( + "failed to read tweet JSON for artifact registration: {}", + json_path.display() + ) + })?) } - let blob_id = database::upsert_blob(conn, &blob)?; + } else { + let json_path = store_path.join(relpath); + std::borrow::Cow::Owned(fs::read_to_string(&json_path).with_context(|| { + format!( + "failed to read tweet JSON for artifact registration: {}", + json_path.display() + ) + })?) + }; + for (role, raw_relpath) in tweet_raw_artifacts(&json_str)? { + let blob_id = if let Some(&id) = blob_cache.get(&raw_relpath) { + id + } else { + let raw_path = PathBuf::from(&raw_relpath); + let mut blob = blob_record_for_raw_relpath(store_path, &raw_path)?; + if role == "media" { + blob.mime_type = tweet_media_image_mime(blob.extension.as_deref()); + } + let id = database::upsert_blob(conn, &blob)?; + blob_cache.insert(raw_relpath.clone(), id); + id + }; database::add_entry_artifact( conn, &database::NewArtifact { @@ -1076,7 +1117,7 @@ fn record_tweet_entry( &canonical_locator, )?; // Read the primary tweet JSON to extract title before entry creation. - let tweet_json_relpath = PathBuf::from("raw_tweets").join(format!("tweet-{tweet_id}.json")); + let tweet_json_relpath = format!("raw_tweets/tweet-{tweet_id}.json"); let tweet_json = fs::read_to_string(store_path.join(&tweet_json_relpath))?; let tweet_meta = tweet_metadata_from_json(&tweet_json); let tweet_title = generate_entry_title(source, &tweet_meta); @@ -1106,7 +1147,13 @@ fn record_tweet_entry( create_structured_root(store_path, &entry)?; // Register all tweet JSONs and their blobs. - register_tweet_artifacts(conn, store_path, entry.id, tweet_json_relpaths)?; + register_tweet_artifacts( + conn, + store_path, + entry.id, + tweet_json_relpaths, + Some((&tweet_json_relpath, &tweet_json)), + )?; database::complete_archive_run_item(conn, item.id, entry.id)?; Ok(entry) @@ -1192,11 +1239,16 @@ fn tweet_media_image_mime(extension: Option<&str>) -> Option { } fn tweet_raw_artifacts(tweet_json: &str) -> Result> { - let regex = regex::Regex::new(r#""(avatar_local_path|local_path)": "([^"\n]+)""#)?; + if !tweet_json.contains("\"raw/") { + return Ok(Vec::new()); + } + static REGEX: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r#""(avatar_local_path|local_path)": "([^"\n]+)""#).unwrap() + }); let mut seen = HashSet::new(); let mut artifacts = Vec::new(); - for captures in regex.captures_iter(tweet_json) { + for captures in REGEX.captures_iter(tweet_json) { let relpath = captures[2].to_string(); if !relpath.starts_with("raw/") || !seen.insert(relpath.clone()) { continue; @@ -1252,7 +1304,7 @@ pub fn perform_capture( ); let store_path = &archive_paths.store_path; - let conn = database::open_or_initialize(&archive_paths.archive_path)?; + let mut conn = database::open_or_initialize(&archive_paths.archive_path)?; let user_id = database::ensure_default_user(&conn)?; let mut source = determine_source(locator); @@ -1955,8 +2007,9 @@ pub fn perform_capture( &tweet_cookies, ) { Ok(tweet_json_relpaths) => { + let tx = conn.transaction()?; let tweet_entry = record_tweet_entry( - &conn, + &tx, store_path, user_id, &run, @@ -1966,8 +2019,9 @@ pub fn perform_capture( &tweet_id, &tweet_json_relpaths, )?; - database::refresh_entry_cached_bytes(&conn, tweet_entry.id)?; - database::finish_archive_run(&conn, run.id)?; + database::refresh_entry_cached_bytes(&tx, tweet_entry.id)?; + database::finish_archive_run(&tx, run.id)?; + tx.commit()?; return Ok(CaptureResult { run_uid: run.run_uid.clone(), status: "completed".to_string(), @@ -2426,7 +2480,7 @@ pub fn perform_rearchive( { let tx = conn.transaction()?; database::delete_entry_artifacts(&tx, entry.id)?; - register_tweet_artifacts(&tx, store_path, entry.id, &tweet_json_relpaths)?; + register_tweet_artifacts(&tx, store_path, entry.id, &tweet_json_relpaths, None)?; tx.commit()?; } diff --git a/crates/archivr-core/src/downloader/tweets.rs b/crates/archivr-core/src/downloader/tweets.rs index 976f58c..32ae2b3 100644 --- a/crates/archivr-core/src/downloader/tweets.rs +++ b/crates/archivr-core/src/downloader/tweets.rs @@ -7,7 +7,7 @@ use std::{ fs, path::{Path, PathBuf}, process::Command, - sync::OnceLock, + sync::LazyLock, }; use crate::{downloader::store, twitter::parse_tweet_id}; @@ -163,6 +163,7 @@ fn run_scraper_staged( } let mut cmd = Command::new(&python); + cmd.env("PYTHONDONTWRITEBYTECODE", "1"); // Run the scraper from staging_dir so relative paths in JSON resolve correctly. cmd.current_dir(&staging_dir).arg(&scraper_path); for arg in build_scraper_args(tweet_id, thread, &staging_tweets_dir, &staging_dir, &credentials_file) { @@ -215,25 +216,36 @@ fn run_scraper_staged( .collect(); staged_jsons.sort(); - // Rewrite asset paths in staged JSONs (moves media blobs from staging into raw/). - // staging_tweets_dir is base for avatar_local_path; staging_dir is base for local_path. - rewrite_tweet_outputs(&staged_jsons, &staging_tweets_dir, &staging_dir, store_path)?; - - // Move each staged JSON to its final destination, collecting store-relative relpaths. + // Rewrite asset paths and move staged JSONs to final destination raw_tweets/. let mut relpaths = Vec::with_capacity(staged_jsons.len()); + let mut archived_assets = HashMap::new(); for staged_path in &staged_jsons { let filename = staged_path.file_name().context("tweet JSON path has no filename")?; let dest = output_dir.join(filename); - fs::rename(staged_path, &dest) - .or_else(|_| { - fs::copy(staged_path, &dest).map(|_| ())?; - fs::remove_file(staged_path) - }) - .with_context(|| format!("failed to move staged tweet JSON to {}", dest.display()))?; - let rel = dest - .strip_prefix(store_path) - .context("dest tweet JSON is not under store_path")?; - relpaths.push(rel.to_string_lossy().replace('\\', "/")); + let contents = fs::read_to_string(staged_path)?; + let rewritten = rewrite_json_asset_paths( + &contents, + &staging_tweets_dir, + &staging_dir, + store_path, + &mut archived_assets, + )?; + + if rewritten != contents { + fs::write(&dest, rewritten) + .with_context(|| format!("failed to write rewritten tweet JSON to {}", dest.display()))?; + let _ = fs::remove_file(staged_path); + } else { + fs::rename(staged_path, &dest) + .or_else(|_| { + fs::copy(staged_path, &dest).map(|_| ())?; + fs::remove_file(staged_path) + }) + .with_context(|| format!("failed to move staged tweet JSON to {}", dest.display()))?; + } + + let filename_str = filename.to_string_lossy(); + relpaths.push(format!("raw_tweets/{filename_str}")); } // Clean up the staging directory (media already moved to raw/ by rewrite_tweet_outputs). @@ -290,42 +302,16 @@ fn cleanup_summary(output_dir: &Path) -> Result<()> { /// Returns a lazily-compiled regex matching `"avatar_local_path": "..."` in JSON. fn avatar_regex() -> &'static Regex { - static REGEX: OnceLock = OnceLock::new(); - REGEX.get_or_init(|| Regex::new(r#""avatar_local_path": "([^"\n]+)""#).unwrap()) + static REGEX: LazyLock = + LazyLock::new(|| Regex::new(r#""avatar_local_path": "([^"\n]+)""#).unwrap()); + ®EX } /// Returns a lazily-compiled regex matching `"local_path": "..."` in JSON. fn media_regex() -> &'static Regex { - static REGEX: OnceLock = OnceLock::new(); - REGEX.get_or_init(|| Regex::new(r#"(?m)"local_path": "([^"\n]+)""#).unwrap()) -} - -/// Rewrites asset paths in each newly-created JSON file, moving assets into -/// the content-addressed store. Files are written back only if content changed. -fn rewrite_tweet_outputs( - tweet_jsons: &[PathBuf], - output_dir: &Path, - temp_dir: &Path, - store_path: &Path, -) -> Result<()> { - let mut archived_assets = HashMap::new(); - - for path in tweet_jsons { - let contents = fs::read_to_string(path)?; - let rewritten = rewrite_json_asset_paths( - &contents, - output_dir, - temp_dir, - store_path, - &mut archived_assets, - )?; - - if rewritten != contents { - fs::write(path, rewritten)?; - } - } - - Ok(()) + static REGEX: LazyLock = + LazyLock::new(|| Regex::new(r#"(?m)"local_path": "([^"\n]+)""#).unwrap()); + ®EX } /// Rewrites all `avatar_local_path` and `local_path` references in `contents`, @@ -339,28 +325,41 @@ fn rewrite_json_asset_paths( store_path: &Path, archived_assets: &mut HashMap, ) -> Result { + let has_avatar = contents.contains("\"avatar_local_path\""); + let has_media = contents.contains("\"local_path\""); + if !has_avatar && !has_media { + return Ok(contents.to_string()); + } + let mut rewritten = contents.to_string(); - for captures in avatar_regex().captures_iter(contents) { - let old_path = captures[1].to_string(); - let new_path = - archive_asset_reference(&old_path, output_dir, store_path, "avatar", archived_assets)?; - rewritten = rewritten.replace( - &format!(r#""avatar_local_path": "{old_path}""#), - &format!(r#""avatar_local_path": "{new_path}""#), - ); + if has_avatar { + for captures in avatar_regex().captures_iter(contents) { + let old_path = &captures[1]; + let new_path = + archive_asset_reference(old_path, output_dir, store_path, "avatar", archived_assets)?; + if old_path != new_path { + rewritten = rewritten.replace( + &format!(r#""avatar_local_path": "{old_path}""#), + &format!(r#""avatar_local_path": "{new_path}""#), + ); + } + } } - for captures in media_regex().captures_iter(contents) { - let old_path = captures[1].to_string(); - let new_path = - archive_asset_reference(&old_path, temp_dir, store_path, "media", archived_assets)?; - rewritten = rewritten.replace( - &format!(r#""local_path": "{old_path}""#), - &format!(r#""local_path": "{new_path}""#), - ); + if has_media { + for captures in media_regex().captures_iter(contents) { + let old_path = &captures[1]; + let new_path = + archive_asset_reference(old_path, temp_dir, store_path, "media", archived_assets)?; + if old_path != new_path { + rewritten = rewritten.replace( + &format!(r#""local_path": "{old_path}""#), + &format!(r#""local_path": "{new_path}""#), + ); + } + } } - Ok(rewritten) } @@ -408,8 +407,8 @@ mod tests { }; fn env_lock() -> MutexGuard<'static, ()> { - static LOCK: OnceLock> = OnceLock::new(); - LOCK.get_or_init(|| Mutex::new(())).lock().unwrap() + static LOCK: LazyLock> = LazyLock::new(|| Mutex::new(())); + LOCK.lock().unwrap() } fn unique_path(prefix: &str) -> PathBuf { diff --git a/vendor/twitter/__pycache__/scrape_user_tweet_contents.cpython-313.pyc b/vendor/twitter/__pycache__/scrape_user_tweet_contents.cpython-313.pyc deleted file mode 100644 index 29e74b2cc71c0d853b1c442a7b09b207250b38ab..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 55503 zcmey&%ge>Uz`$^5T5uNoeFlcdAPx*`Lm8isF)=VqWe8>{VhCmoX7Xk%Vg%DnMND9t zxriA|vlOv_Y1SfEFwIuP4yHN4G_yCS7iSTt0>}&&Z!RzHB5p97)tkqQw}{t^uZYi! zzlh&Uph&<=ut?BLs7MGb&*m-cB~m1!z!1zX#ZV*~%pt{4Bo=HP%qhi?#aJXB%oQUL zBf-kRz!1z0XYs@cLc~nif_bGFvRH~FgZW}4f_Y;2q2esT{9tjZV1XFkU_r2)Knx$q z922%+A+VfuFk`SVrt1_Kf< zvccjpvcWttd?p;h5+KdTP7O8?=f*gKYAekaHIfh_cxCz?eaNvW63&=en zcY|!#iIET1jgg0kf?kYluzrkeutAJ$uwjgBuu+U`uyKrRut|(;uxX5ZFvuNdpzsK0 zGSLb)2icXySfm~dGLr|{7890W3y^G)MzEz6Ly=~TR zq%);6Y1&sk=5nnlDN0N(Q79=-O)XJK&d)1J%_}KZNGr#hBts#;pd>RtFEK|UH#H?QQ6VM2JTE6dF$LnbqSWNlqT*qhfjv06D6t^5D47vt92B!NFfcGPFfe>}U;q^g(QvtFCa4OAAQl)4K`SwY zf-*jnC6g&shXO-7vnETGctBBVNlB$bK~ZL23B>cDV9|RCGHxZ~Ew;?Ol+?TuKTYOa ztY9^_Sh9-q^KP-Gl;#!`gS-V&UJNo+;g(KWYFW?2N_o+%D})N&cMJ>3}Q4eJYnJNQR&y}(wY#mK=C4%%2gKC&mhmB1O>>O z;GoE0U|@)2n#zC(j8F!cH-kVbKw6P7EKTMz=`#c~1~TR`MuV~&SVbt431cvm6hjtA zD5Eeu^}@xW$oLk(`>ElA3ahwXih5B(aJQEUo|( zMu`njI2(f!rVaxGg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BErW0hwVolyLNK_22xc}CG4#$euolCL1a z4=#+BjN%JIJ}_7^if;%8QwJc_iI59Hp(i81fMh;YFzPeeblUCV&nrG4Pt;K|uHeH<-!8ASC*M7tG{i;Nkzk4`vF06bOQuLJUG;AB4e75e5;7529eE z7=x(f2XQb{fvw5D1wk+ zl)+3D1|9tms$ixXC>+$mObrHcsSjZPeb8cH 0 and _last_request_time > 0: + elapsed = time.time() - _last_request_time + if elapsed < delay: + time.sleep(delay - elapsed) + _last_request_time = time.time() +import httpx + +class SimpleTwitterScraper: + def __init__(self, cookies: dict): + self.cookies = cookies + headers = { + "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA", + "referer": "https://twitter.com/", + "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36", + "x-csrf-token": cookies.get("ct0", ""), + "x-twitter-active-user": "yes", + "x-twitter-auth-type": "OAuth2Session" if cookies.get("auth_token") else "", + "x-twitter-client-language": "en", + } + self.session = httpx.Client(cookies=cookies, headers=headers, follow_redirects=True, timeout=30.0) + self._full_scraper = None + + def tweets_details(self, tweet_ids): + if self._full_scraper is None: + from twitter.scraper import Scraper + self._full_scraper = Scraper(cookies=self.cookies, save=False) + return self._full_scraper.tweets_details(tweet_ids) +try: + import orjson + def dump_json_file(path: str, data: Any): + with open(path, "wb") as f: + f.write(orjson.dumps(data, option=orjson.OPT_INDENT_2)) + def parse_json_bytes(content: bytes) -> Any: + return orjson.loads(content) +except ImportError: + def dump_json_file(path: str, data: Any): + with open(path, "w") as f: + json.dump(data, f, indent=2) + def parse_json_bytes(content: bytes) -> Any: + return json.loads(content.decode("utf-8")) +DEFAULT_FEATURES_JSON = json.dumps({ + "rweb_video_screen_enabled": False, + "profile_label_improvements_pcf_label_in_post_enabled": True, + "responsive_web_profile_redirect_enabled": False, + "rweb_tipjar_consumption_enabled": False, + "verified_phone_label_enabled": False, + "creator_subscriptions_tweet_preview_api_enabled": True, + "responsive_web_graphql_timeline_navigation_enabled": True, + "responsive_web_graphql_skip_user_profile_image_extensions_enabled": False, + "premium_content_api_read_enabled": False, + "communities_web_enable_tweet_community_results_fetch": True, + "c9s_tweet_anatomy_moderator_badge_enabled": True, + "responsive_web_grok_analyze_button_fetch_trends_enabled": False, + "responsive_web_grok_analyze_post_followups_enabled": True, + "responsive_web_jetfuel_frame": True, + "responsive_web_grok_share_attachment_enabled": True, + "responsive_web_grok_annotations_enabled": True, + "articles_preview_enabled": True, + "responsive_web_edit_tweet_api_enabled": True, + "graphql_is_translatable_rweb_tweet_is_translatable_enabled": True, + "view_counts_everywhere_api_enabled": True, + "longform_notetweets_consumption_enabled": True, + "responsive_web_twitter_article_tweet_consumption_enabled": True, + "content_disclosure_indicator_enabled": True, + "content_disclosure_ai_generated_indicator_enabled": True, + "responsive_web_grok_show_grok_translated_post": False, + "responsive_web_grok_analysis_button_from_backend": True, + "post_ctas_fetch_enabled": True, + "freedom_of_speech_not_reach_fetch_enabled": True, + "standardized_nudges_misinfo": True, + "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": True, + "longform_notetweets_rich_text_read_enabled": True, + "longform_notetweets_inline_media_enabled": False, + "responsive_web_grok_image_annotation_enabled": True, + "responsive_web_grok_imagine_annotation_enabled": True, + "responsive_web_grok_community_note_auto_translation_is_enabled": False, + "responsive_web_enhance_cards_enabled": False, +}) + +DEFAULT_FIELD_TOGGLES_JSON = json.dumps({ + "withArticleRichContentState": True, + "withArticlePlainText": True, + "withArticleSummaryText": True, + "withArticleVoiceOver": True, + "withGrokAnalyze": False, + "withDisallowedReplyControls": False, +}) def print_json(data): @@ -165,128 +256,112 @@ def parse_tweet_ids_from_file(file_path: str) -> List[str]: return tweet_ids -def extract_tweet_from_response(response_data: Any, tweet_id: str) -> Optional[Dict]: +def extract_all_tweets_from_response(response_data: Any) -> Dict[str, Dict]: """ - Extract tweet data from API response. - - Args: - response_data: Response data from scraper - tweet_id: The tweet ID we're looking for - - Returns: - Tweet data dictionary or None if not found + Extract all tweet results present anywhere in an API response. + Maps str(tweet_id) -> tweet_result dictionary. """ + tweets: Dict[str, Dict] = {} try: - # Handle list response if isinstance(response_data, list): if len(response_data) == 0: - return None + return tweets data = response_data[0] elif isinstance(response_data, dict): data = response_data else: - return None + return tweets - # Navigate through the nested structure - # Try different possible paths - tweet_result = None + def add_result(res): + if not isinstance(res, dict): + return + if res.get("__typename") == "TweetWithVisibilityResults" and "tweet" in res: + res = res["tweet"] + rest_id = res.get("rest_id") or res.get("legacy", {}).get("id_str") + if rest_id and (res.get("__typename") == "Tweet" or "legacy" in res): + tweets[str(rest_id)] = res - # Path 1: TweetDetail GraphQL response structure - # Check for threaded_conversation_with_injections_v2 structure - if "data" in data: - threaded_conversation = data.get("data", {}).get( - "threaded_conversation_with_injections_v2", {} - ) - instructions = threaded_conversation.get("instructions", []) + # Path 1: Threaded conversation + tc = data.get("data", {}).get("threaded_conversation_with_injections_v2", {}) + for instruction in tc.get("instructions", []): + if instruction.get("type") == "TimelineAddEntries": + for entry in instruction.get("entries", []): + content = entry.get("content", {}) + entry_type = content.get("entryType") + if entry_type == "TimelineTimelineItem": + res = content.get("itemContent", {}).get("tweet_results", {}).get("result", {}) + add_result(res) + elif entry_type == "TimelineTimelineModule": + for item in content.get("items", []): + res = item.get("item", {}).get("itemContent", {}).get("tweet_results", {}).get("result", {}) + add_result(res) - for instruction in instructions: - if instruction.get("type") == "TimelineAddEntries": - entries = instruction.get("entries", []) - for entry in entries: - content = entry.get("content", {}) - if content.get("entryType") == "TimelineTimelineItem": - item_content = content.get("itemContent", {}) - if item_content.get("itemType") == "TimelineTweet": - result = item_content.get("tweet_results", {}).get( - "result", {} - ) - if result.get("rest_id") == tweet_id: - tweet_result = result - break - if tweet_result: - break - if tweet_result: - break + # Path 2: User timeline + timeline = data.get("data", {}).get("user", {}).get("result", {}).get("timeline_v2", {}).get("timeline", {}) + for instruction in timeline.get("instructions", []): + if instruction.get("type") == "TimelineAddEntries": + for entry in instruction.get("entries", []): + content = entry.get("content", {}) + entry_type = content.get("entryType") + if entry_type == "TimelineTimelineItem": + res = content.get("itemContent", {}).get("tweet_results", {}).get("result", {}) + add_result(res) + elif entry_type == "TimelineTimelineModule": + for item in content.get("items", []): + res = item.get("item", {}).get("itemContent", {}).get("tweet_results", {}).get("result", {}) + add_result(res) - # Path 2: Timeline structure (for user tweets) - if not tweet_result and "data" in data: - timeline = ( - data.get("data", {}) - .get("user", {}) - .get("result", {}) - .get("timeline_v2", {}) - .get("timeline", {}) - ) - instructions = timeline.get("instructions", []) - - for instruction in instructions: - if instruction.get("type") == "TimelineAddEntries": - entries = instruction.get("entries", []) - for entry in entries: - content = entry.get("content", {}) - if content.get("entryType") == "TimelineTimelineItem": - item_content = content.get("itemContent", {}) - if item_content.get("itemType") == "TimelineTweet": - result = item_content.get("tweet_results", {}).get( - "result", {} - ) - if result.get("rest_id") == tweet_id: - tweet_result = result - break - if tweet_result: - break - if tweet_result: - break - - # Path 3: Direct tweet lookup (recursive search) - if not tweet_result: - - def find_tweet_recursive(obj, target_id): + # Path 3: Recursive scan fallback if none extracted yet + if not tweets: + def find_all_recursive(obj): if isinstance(obj, dict): - # Check if this is a tweet result with matching ID - if ( - obj.get("rest_id") == target_id - and obj.get("__typename") == "Tweet" - ): - return obj - # Also check legacy.id_str for older format - legacy = obj.get("legacy", {}) - if legacy and legacy.get("id_str") == target_id: - return obj - # Recursively search - for value in obj.values(): - result = find_tweet_recursive(value, target_id) - if result: - return result + if obj.get("__typename") == "Tweet" and ("rest_id" in obj or "legacy" in obj): + add_result(obj) + for v in obj.values(): + find_all_recursive(v) elif isinstance(obj, list): for item in obj: - result = find_tweet_recursive(item, target_id) - if result: - return result - return None - - tweet_result = find_tweet_recursive(data, tweet_id) - - return tweet_result + find_all_recursive(item) + find_all_recursive(data) except Exception as e: - print(f" ⚠ Warning: Error extracting tweet {tweet_id}: {e}") - import traceback + print(f" ⚠ Warning: Error extracting tweets from response: {e}") - traceback.print_exc() + return tweets + + +def extract_tweet_from_response(response_data: Any, tweet_id: str) -> Optional[Dict]: + """ + Extract tweet data from API response for a specific tweet ID. + """ + tweets = extract_all_tweets_from_response(response_data) + if tweet_id in tweets: + return tweets[tweet_id] + + # Deep fallback search if exact structure match didn't find it + try: + data = response_data[0] if isinstance(response_data, list) and response_data else response_data + def find_tweet_recursive(obj, target_id): + if isinstance(obj, dict): + if obj.get("rest_id") == target_id and obj.get("__typename") == "Tweet": + return obj + legacy = obj.get("legacy", {}) + if legacy and legacy.get("id_str") == target_id: + return obj + for value in obj.values(): + result = find_tweet_recursive(value, target_id) + if result: + return result + elif isinstance(obj, list): + for item in obj: + result = find_tweet_recursive(item, target_id) + if result: + return result + return None + return find_tweet_recursive(data, tweet_id) + except Exception: return None - from typing import Any, Dict, List, Optional @@ -630,20 +705,27 @@ def extract_tweet_data( return tweet_data -def download_file(url: str, output_path: str, retry_count: int = 0) -> bool: +def download_file( + url: str, output_path: str, retry_count: int = 0, session: Optional[Any] = None +) -> bool: """ - Download a file from URL to output path. - - Args: - url: URL to download from - output_path: Path to save the file - retry_count: Number of retries attempted - - Returns: - True if successful, False otherwise + Download a file from URL to output path, reusing session keep-alive connections when available. """ try: + if os.path.exists(output_path) and os.path.getsize(output_path) > 0: + return True os.makedirs(os.path.dirname(output_path), exist_ok=True) + mock_server = os.environ.get("ARCHIVR_TWITTER_MOCK_SERVER") + if mock_server and ("twimg.com" in url or "twitter.com" in url or "x.com" in url): + parsed_u = urllib.parse.urlparse(url) + url = f"{mock_server}{parsed_u.path}" + + if session is not None and hasattr(session, "get"): + resp = session.get(url, timeout=30) + if resp.status_code == 200: + with open(output_path, "wb") as f: + f.write(resp.content) + return True # Create request with user agent req = urllib.request.Request(url) @@ -658,13 +740,15 @@ def download_file(url: str, output_path: str, retry_count: int = 0) -> bool: return True except Exception as e: if retry_count < 2: - time.sleep(2) - return download_file(url, output_path, retry_count + 1) + time.sleep(1) + return download_file(url, output_path, retry_count + 1, session=session) print(f" ⚠ Warning: Failed to download {url}: {e}") return False -def download_tweet_media(tweet_data: Dict, tweet_id: str, media_dir: str) -> List[str]: +def download_tweet_media( + tweet_data: Dict, tweet_id: str, media_dir: str, session: Optional[Any] = None +) -> List[str]: """ Download media files for a tweet. @@ -684,6 +768,7 @@ def download_tweet_media(tweet_data: Dict, tweet_id: str, media_dir: str) -> Lis tweet_media_dir = os.path.join(media_dir, tweet_id) + tasks = [] for idx, media_item in enumerate(media_list): media_url = media_item.get("media_url_https") or media_item.get("media_url") if not media_url: @@ -713,19 +798,33 @@ def download_tweet_media(tweet_data: Dict, tweet_id: str, media_dir: str) -> Lis filename = f"media_{idx + 1}.{ext}" output_path = os.path.join(tweet_media_dir, filename) + tasks.append((media_url, output_path, media_item)) - if download_file(media_url, output_path): + if len(tasks) == 1: + media_url, output_path, media_item = tasks[0] + if download_file(media_url, output_path, session=session): media_paths.append(output_path) - # Update tweet data with local path media_item["local_path"] = os.path.relpath( output_path, os.path.dirname(media_dir) ) + elif len(tasks) > 1: + def _fetch_media(task): + m_url, out_p, m_item = task + ok = download_file(m_url, out_p, session=session) + return (ok, out_p, m_item) + with ThreadPoolExecutor(max_workers=min(4, len(tasks))) as pool: + for ok, out_p, m_item in pool.map(_fetch_media, tasks): + if ok: + media_paths.append(out_p) + m_item["local_path"] = os.path.relpath( + out_p, os.path.dirname(media_dir) + ) return media_paths def download_article_media( - article_data: Dict, tweet_id: str, media_dir: str, output_dir: str + article_data: Dict, tweet_id: str, media_dir: str, output_dir: str, session: Optional[Any] = None ) -> None: """ Download images embedded in an article: the cover image and any inline @@ -755,7 +854,7 @@ def download_article_media( if cover_url and not cover.get("local_path"): ext = _ext_from_url(cover_url) output_path = os.path.join(article_media_dir, f"cover.{ext}") - if download_file(cover_url, output_path): + if download_file(cover_url, output_path, session=session): cover["local_path"] = os.path.relpath(output_path, rel_base) # --- Inline block images --- @@ -770,11 +869,13 @@ def download_article_media( ext = _ext_from_url(url) filename = f"article_{media_id}.{ext}" if media_id else f"article_img.{ext}" output_path = os.path.join(article_media_dir, filename) - if download_file(url, output_path): + if download_file(url, output_path, session=session): entity["local_path"] = os.path.relpath(output_path, rel_base) -def download_avatar(avatar_url: str, author_id: str, avatars_dir: str) -> Optional[str]: +def download_avatar( + avatar_url: str, author_id: str, avatars_dir: str, session: Optional[Any] = None +) -> Optional[str]: """ Download avatar image for an author. @@ -801,21 +902,23 @@ def download_avatar(avatar_url: str, author_id: str, avatars_dir: str) -> Option filename = f"{author_id}.{ext}" output_path = os.path.join(avatars_dir, filename) - - # Try high quality first, fallback to normal - if download_file(avatar_url_hq, output_path): + if os.path.exists(output_path) and os.path.getsize(output_path) > 0: return output_path - elif download_file(avatar_url, output_path): + # Try high quality first, fallback to normal + if download_file(avatar_url_hq, output_path, session=session): + return output_path + elif download_file(avatar_url, output_path, session=session): return output_path return None def fetch_tweet_by_id( - scraper: Scraper, + scraper: Any, tweet_id: str, retry_count: int = 0, delay_between_requests: float = 2.0, + discovered_tweets: Optional[Dict[str, Dict]] = None, ) -> Optional[Dict]: """ Fetch a single tweet by ID with rate limit handling. @@ -828,10 +931,13 @@ def fetch_tweet_by_id( tweet_id: Tweet ID to fetch retry_count: Current retry count delay_between_requests: Delay between requests + discovered_tweets: In-memory cache of already parsed tweet results Returns: Tweet result dictionary or None if not found """ + if discovered_tweets is not None and tweet_id in discovered_tweets: + return discovered_tweets[tweet_id] try: response_data = None last_error = None @@ -841,7 +947,11 @@ def fetch_tweet_by_id( try: # Use the TweetDetail GraphQL endpoint # The endpoint hash might vary, but this is a common one - url = "https://twitter.com/i/api/graphql/rU08O-YiXdr0IZfE7qaUMg/TweetDetail" + mock_server = os.environ.get("ARCHIVR_TWITTER_MOCK_SERVER") + if mock_server: + url = f"{mock_server}/i/api/graphql/rU08O-YiXdr0IZfE7qaUMg/TweetDetail" + else: + url = "https://twitter.com/i/api/graphql/rU08O-YiXdr0IZfE7qaUMg/TweetDetail" variables = { "focalTweetId": tweet_id, "with_rux_injections": False, @@ -853,61 +963,15 @@ def fetch_tweet_by_id( "withVoice": True, } - features = { - "rweb_video_screen_enabled": False, - "profile_label_improvements_pcf_label_in_post_enabled": True, - "responsive_web_profile_redirect_enabled": False, - "rweb_tipjar_consumption_enabled": False, - "verified_phone_label_enabled": False, - "creator_subscriptions_tweet_preview_api_enabled": True, - "responsive_web_graphql_timeline_navigation_enabled": True, - "responsive_web_graphql_skip_user_profile_image_extensions_enabled": False, - "premium_content_api_read_enabled": False, - "communities_web_enable_tweet_community_results_fetch": True, - "c9s_tweet_anatomy_moderator_badge_enabled": True, - "responsive_web_grok_analyze_button_fetch_trends_enabled": False, - "responsive_web_grok_analyze_post_followups_enabled": True, - "responsive_web_jetfuel_frame": True, - "responsive_web_grok_share_attachment_enabled": True, - "responsive_web_grok_annotations_enabled": True, - "articles_preview_enabled": True, - "responsive_web_edit_tweet_api_enabled": True, - "graphql_is_translatable_rweb_tweet_is_translatable_enabled": True, - "view_counts_everywhere_api_enabled": True, - "longform_notetweets_consumption_enabled": True, - "responsive_web_twitter_article_tweet_consumption_enabled": True, - "content_disclosure_indicator_enabled": True, - "content_disclosure_ai_generated_indicator_enabled": True, - "responsive_web_grok_show_grok_translated_post": False, - "responsive_web_grok_analysis_button_from_backend": True, - "post_ctas_fetch_enabled": True, - "freedom_of_speech_not_reach_fetch_enabled": True, - "standardized_nudges_misinfo": True, - "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": True, - "longform_notetweets_rich_text_read_enabled": True, - "longform_notetweets_inline_media_enabled": False, - "responsive_web_grok_image_annotation_enabled": True, - "responsive_web_grok_imagine_annotation_enabled": True, - "responsive_web_grok_community_note_auto_translation_is_enabled": False, - "responsive_web_enhance_cards_enabled": False, - } - - field_toggles = { - "withArticleRichContentState": True, - "withArticlePlainText": True, - "withArticleSummaryText": True, - "withArticleVoiceOver": True, - "withGrokAnalyze": False, - "withDisallowedReplyControls": False, - } params = { "variables": json.dumps(variables), - "features": json.dumps(features), - "fieldToggles": json.dumps(field_toggles), + "features": DEFAULT_FEATURES_JSON, + "fieldToggles": DEFAULT_FIELD_TOGGLES_JSON, } + _rate_limit(delay_between_requests) response = scraper.session.get(url, params=params) if response.status_code == 200: - response_data = response.json() + response_data = parse_json_bytes(response.content) if response_data: print(f" ✓ Fetched using direct GraphQL request") else: @@ -929,6 +993,7 @@ def fetch_tweet_by_id( # Method 1: Try tweets_details() if available (note: plural "tweets") if response_data is None and hasattr(scraper, "tweets_details"): try: + _rate_limit(delay_between_requests) response_data = scraper.tweets_details([tweet_id]) if response_data: print(f" ✓ Fetched using tweets_details()") @@ -958,10 +1023,18 @@ def fetch_tweet_by_id( error_msg += f"Last error: {last_error}" raise Exception(error_msg) - # Extract tweet from response - tweet_result = extract_tweet_from_response(response_data, tweet_id) + # Extract tweets from response and cache in discovered_tweets + if response_data: + found_tweets = extract_all_tweets_from_response(response_data) + if discovered_tweets is not None: + discovered_tweets.update(found_tweets) + if tweet_id in found_tweets: + return found_tweets[tweet_id] + tweet_result = extract_tweet_from_response(response_data, tweet_id) if tweet_result: + if discovered_tweets is not None: + discovered_tweets[tweet_id] = tweet_result return tweet_result else: # Debug: print response structure @@ -984,7 +1057,11 @@ def fetch_tweet_by_id( time.sleep(wait_time) if retry_count < 5: # Max 5 retries for rate limits return fetch_tweet_by_id( - scraper, tweet_id, retry_count + 1, delay_between_requests + scraper, + tweet_id, + retry_count + 1, + delay_between_requests, + discovered_tweets=discovered_tweets, ) else: print(f" ❌ Max retries reached for tweet {tweet_id}") @@ -994,7 +1071,11 @@ def fetch_tweet_by_id( if retry_count < 1: time.sleep(delay_between_requests * 3) return fetch_tweet_by_id( - scraper, tweet_id, retry_count + 1, delay_between_requests + scraper, + tweet_id, + retry_count + 1, + delay_between_requests, + discovered_tweets=discovered_tweets, ) else: print(f" ⚠ Warning: Error fetching tweet {tweet_id}: {error_msg}") @@ -1034,7 +1115,7 @@ def extract_related_tweet_ids(tweet_data: Dict) -> List[str]: def scrape_tweets_recursive( - scraper: Scraper, + scraper: Any, tweet_id: str, scraped_tweets: Dict[str, Dict], output_dir: str, @@ -1054,6 +1135,7 @@ def scrape_tweets_recursive( max_replied_to_tweets_recursion_depth: int, delay_between_requests: float, replied_to_depth: int = 0, + discovered_tweets: Optional[Dict[str, Dict]] = None, ) -> None: """ Recursively scrape tweets (quoted, retweeted, replied-to). @@ -1094,7 +1176,10 @@ def scrape_tweets_recursive( # Fetch tweet print(f" {' ' * depth}→ Fetching tweet {tweet_id}...") tweet_result = fetch_tweet_by_id( - scraper, tweet_id, delay_between_requests=delay_between_requests + scraper, + tweet_id, + delay_between_requests=delay_between_requests, + discovered_tweets=discovered_tweets, ) if not tweet_result: @@ -1113,13 +1198,14 @@ def scrape_tweets_recursive( bare_scrape=current_bare_scrape, advanced_info=current_advanced_info, ) + session = getattr(scraper, "session", None) # Download avatar if enabled if download_avatars and not is_replied_to_tweet: author_id = tweet_data.get("author", {}).get("id") avatar_url = tweet_data.get("author", {}).get("avatar_url", "") if author_id and avatar_url: - avatar_path = download_avatar(avatar_url, author_id, avatars_dir) + avatar_path = download_avatar(avatar_url, author_id, avatars_dir, session=session) if avatar_path: tweet_data["author"]["avatar_local_path"] = os.path.relpath( avatar_path, output_dir @@ -1131,15 +1217,13 @@ def scrape_tweets_recursive( should_download_media = download_replied_to_tweets_media if should_download_media: - download_tweet_media(tweet_data, tweet_id, media_dir) + download_tweet_media(tweet_data, tweet_id, media_dir, session=session) if tweet_data.get("is_article") and tweet_data.get("article"): - download_article_media(tweet_data["article"], tweet_id, media_dir, output_dir) - + download_article_media(tweet_data["article"], tweet_id, media_dir, output_dir, session=session) # Save tweet to JSON file json_file = os.path.join(output_dir, f"tweet-{tweet_id}.json") try: - with open(json_file, "w") as f: - json.dump(tweet_data, f, indent=2) + dump_json_file(json_file, tweet_data) except Exception as e: print( f" {' ' * depth}⚠ Warning: Failed to save JSON file for tweet {tweet_id}: {e}" @@ -1149,10 +1233,7 @@ def scrape_tweets_recursive( # Mark as scraped scraped_tweets[tweet_id] = tweet_data - # Rate limiting - if delay_between_requests > 0: - time.sleep(delay_between_requests) - + # Rate limiting is handled prior to outgoing requests in _rate_limit() # Recursively scrape related tweets if recursive and depth < max_depth - 1: related_ids = extract_related_tweet_ids(tweet_data) @@ -1180,8 +1261,8 @@ def scrape_tweets_recursive( max_replied_to_tweets_recursion_depth, delay_between_requests, replied_to_depth, + discovered_tweets, ) - # Handle replied-to tweets if scrape_replied_to_tweet or recursive_replied_to_tweets: in_reply_to_status_id = tweet_data.get("in_reply_to_status_id") @@ -1219,6 +1300,7 @@ def scrape_tweets_recursive( max_replied_to_tweets_recursion_depth, delay_between_requests, new_replied_to_depth, + discovered_tweets, ) @@ -1442,7 +1524,7 @@ def main(): cookie_dict = dict(item.split("=", 1) for item in cookie_str.split(";")) # Initialize scraper - scraper = Scraper(cookies=cookie_dict, save=False) + scraper = SimpleTwitterScraper(cookies=cookie_dict) # Load already scraped tweets (for resume) scraped_tweets = load_scraped_tweets(output_dir) @@ -1471,6 +1553,7 @@ def main(): } # Scrape tweets + discovered_tweets: Dict[str, Dict] = {} for idx, tweet_id in enumerate(remaining_tweet_ids, 1): print(f"\n[{idx}/{len(remaining_tweet_ids)}] Processing tweet {tweet_id}...") @@ -1495,6 +1578,7 @@ def main(): download_replied_to_tweets_media=args.download_replied_to_tweets_media, max_replied_to_tweets_recursion_depth=args.max_replied_to_tweets_recursion_depth, delay_between_requests=args.delay_between_requests, + discovered_tweets=discovered_tweets, ) stats["newly_scraped"] += 1 except Exception as e: @@ -1534,9 +1618,10 @@ def main(): } summary_file = os.path.join(output_dir, "scraping_summary.json") - with open(summary_file, "w") as f: - json.dump(summary, f, indent=2) - + try: + dump_json_file(summary_file, summary) + except Exception as e: + print(f"⚠ Warning: Failed to save summary file: {e}") # Print final summary print(f"\n{'=' * 80}") print("Scraping complete!")