id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
5,200
imdbpy.pot
cinemagoer_cinemagoer/imdb/locale/imdbpy.pot
# Gettext message file for imdbpy msgid "" msgstr "" "Project-Id-Version: imdbpy\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: YYYY-MM-DD HH:MM+0000\n" "Last-Translator: YOUR NAME <YOUR@EMAIL>\n" "Language-Team: TEAM NAME <TEAM@EMAIL>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "Language-Code: en\n" "Language-Name: English\n" "Preferred-Encodings: utf-8\n" "Domain: imdbpy\n" # Default: Actor msgid "actor" msgstr "" # Default: Actress msgid "actress" msgstr "" # Default: Adaption msgid "adaption" msgstr "" # Default: Additional information msgid "additional-information" msgstr "" # Default: Admissions msgid "admissions" msgstr "" # Default: Agent address msgid "agent-address" msgstr "" # Default: Airing msgid "airing" msgstr "" # Default: Akas msgid "akas" msgstr "" # Default: Akas from release info msgid "akas-from-release-info" msgstr "" # Default: All products msgid "all-products" msgstr "" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "" # Default: Alternate versions msgid "alternate-versions" msgstr "" # Default: Amazon reviews msgid "amazon-reviews" msgstr "" # Default: Analog left msgid "analog-left" msgstr "" # Default: Analog right msgid "analog-right" msgstr "" # Default: Animation department msgid "animation-department" msgstr "" # Default: Archive footage msgid "archive-footage" msgstr "" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "" # Default: Art department msgid "art-department" msgstr "" # Default: Art direction msgid "art-direction" msgstr "" # Default: Art director msgid "art-director" msgstr "" # Default: Article msgid "article" msgstr "" # Default: Asin msgid "asin" msgstr "" # Default: Aspect ratio msgid "aspect-ratio" msgstr "" # Default: Assigner msgid "assigner" msgstr "" # Default: Assistant director msgid "assistant-director" msgstr "" # Default: Auctions msgid "auctions" msgstr "" # Default: Audio noise msgid "audio-noise" msgstr "" # Default: Audio quality msgid "audio-quality" msgstr "" # Default: Award msgid "award" msgstr "" # Default: Awards msgid "awards" msgstr "" # Default: Biographical movies msgid "biographical-movies" msgstr "" # Default: Biography msgid "biography" msgstr "" # Default: Biography print msgid "biography-print" msgstr "" # Default: Birth date msgid "birth-date" msgstr "" # Default: Birth name msgid "birth-name" msgstr "" # Default: Birth notes msgid "birth-notes" msgstr "" # Default: Body msgid "body" msgstr "" # Default: Book msgid "book" msgstr "" # Default: Books msgid "books" msgstr "" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "" # Default: Budget msgid "budget" msgstr "" # Default: Business msgid "business" msgstr "" # Default: By arrangement with msgid "by-arrangement-with" msgstr "" # Default: Camera msgid "camera" msgstr "" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "" # Default: Canonical name msgid "canonical-name" msgstr "" # Default: Canonical series title msgid "canonical-series-title" msgstr "" # Default: Canonical title msgid "canonical-title" msgstr "" # Default: Cast msgid "cast" msgstr "" # Default: Casting department msgid "casting-department" msgstr "" # Default: Casting director msgid "casting-director" msgstr "" # Default: Catalog number msgid "catalog-number" msgstr "" # Default: Category msgid "category" msgstr "" # Default: Certificate msgid "certificate" msgstr "" # Default: Certificates msgid "certificates" msgstr "" # Default: Certification msgid "certification" msgstr "" # Default: Channel msgid "channel" msgstr "" # Default: Character msgid "character" msgstr "" # Default: Cinematographer msgid "cinematographer" msgstr "" # Default: Cinematographic process msgid "cinematographic-process" msgstr "" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "" # Default: Color information msgid "color-information" msgstr "" # Default: Color rendition msgid "color-rendition" msgstr "" # Default: Company msgid "company" msgstr "" # Default: Complete cast msgid "complete-cast" msgstr "" # Default: Complete crew msgid "complete-crew" msgstr "" # Default: Composer msgid "composer" msgstr "" # Default: Connections msgid "connections" msgstr "" # Default: Contrast msgid "contrast" msgstr "" # Default: Copyright holder msgid "copyright-holder" msgstr "" # Default: Costume department msgid "costume-department" msgstr "" # Default: Costume designer msgid "costume-designer" msgstr "" # Default: Countries msgid "countries" msgstr "" # Default: Country msgid "country" msgstr "" # Default: Courtesy of msgid "courtesy-of" msgstr "" # Default: Cover msgid "cover" msgstr "" # Default: Cover url msgid "cover-url" msgstr "" # Default: Crazy credits msgid "crazy-credits" msgstr "" # Default: Creator msgid "creator" msgstr "" # Default: Current role msgid "current-role" msgstr "" # Default: Database msgid "database" msgstr "" # Default: Date msgid "date" msgstr "" # Default: Death date msgid "death-date" msgstr "" # Default: Death notes msgid "death-notes" msgstr "" # Default: Demographic msgid "demographic" msgstr "" # Default: Description msgid "description" msgstr "" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "" # Default: Digital sound msgid "digital-sound" msgstr "" # Default: Director msgid "director" msgstr "" # Default: Disc format msgid "disc-format" msgstr "" # Default: Disc size msgid "disc-size" msgstr "" # Default: Distributors msgid "distributors" msgstr "" # Default: Dvd msgid "dvd" msgstr "" # Default: Dvd features msgid "dvd-features" msgstr "" # Default: Dvd format msgid "dvd-format" msgstr "" # Default: Dvds msgid "dvds" msgstr "" # Default: Dynamic range msgid "dynamic-range" msgstr "" # Default: Edited from msgid "edited-from" msgstr "" # Default: Edited into msgid "edited-into" msgstr "" # Default: Editor msgid "editor" msgstr "" # Default: Editorial department msgid "editorial-department" msgstr "" # Default: Episode msgid "episode" msgstr "" # Default: Episode of msgid "episode-of" msgstr "" # Default: Episode title msgid "episode-title" msgstr "" # Default: Episodes msgid "episodes" msgstr "" # Default: Episodes rating msgid "episodes-rating" msgstr "" # Default: Essays msgid "essays" msgstr "" # Default: External reviews msgid "external-reviews" msgstr "" # Default: Faqs msgid "faqs" msgstr "" # Default: Feature msgid "feature" msgstr "" # Default: Featured in msgid "featured-in" msgstr "" # Default: Features msgid "features" msgstr "" # Default: Film negative format msgid "film-negative-format" msgstr "" # Default: Filming dates msgid "filming-dates" msgstr "" # Default: Filmography msgid "filmography" msgstr "" # Default: Followed by msgid "followed-by" msgstr "" # Default: Follows msgid "follows" msgstr "" # Default: For msgid "for" msgstr "" # Default: Frequency response msgid "frequency-response" msgstr "" # Default: From msgid "from" msgstr "" # Default: Full article link msgid "full-article-link" msgstr "" # Default: Full size cover url msgid "full-size-cover-url" msgstr "" # Default: Full size headshot msgid "full-size-headshot" msgstr "" # Default: Genres msgid "genres" msgstr "" # Default: Goofs msgid "goofs" msgstr "" # Default: Gross msgid "gross" msgstr "" # Default: Group genre msgid "group-genre" msgstr "" # Default: Headshot msgid "headshot" msgstr "" # Default: Height msgid "height" msgstr "" # Default: Imdbindex msgid "imdbindex" msgstr "" # Default: In development msgid "in-development" msgstr "" # Default: Interview msgid "interview" msgstr "" # Default: Interviews msgid "interviews" msgstr "" # Default: Introduction msgid "introduction" msgstr "" # Default: Item msgid "item" msgstr "" # Default: Keywords msgid "keywords" msgstr "" # Default: Kind msgid "kind" msgstr "" # Default: Label msgid "label" msgstr "" # Default: Laboratory msgid "laboratory" msgstr "" # Default: Language msgid "language" msgstr "" # Default: Languages msgid "languages" msgstr "" # Default: Laserdisc msgid "laserdisc" msgstr "" # Default: Laserdisc title msgid "laserdisc-title" msgstr "" # Default: Length msgid "length" msgstr "" # Default: Line msgid "line" msgstr "" # Default: Link msgid "link" msgstr "" # Default: Link text msgid "link-text" msgstr "" # Default: Literature msgid "literature" msgstr "" # Default: Locations msgid "locations" msgstr "" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "" # Default: Long imdb name msgid "long-imdb-name" msgstr "" # Default: Long imdb title msgid "long-imdb-title" msgstr "" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "" # Default: Make up msgid "make-up" msgstr "" # Default: Master format msgid "master-format" msgstr "" # Default: Median msgid "median" msgstr "" # Default: Merchandising links msgid "merchandising-links" msgstr "" # Default: Mini biography msgid "mini-biography" msgstr "" # Default: Misc links msgid "misc-links" msgstr "" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "" # Default: Movie msgid "movie" msgstr "" # Default: Mpaa msgid "mpaa" msgstr "" # Default: Music department msgid "music-department" msgstr "" # Default: Name msgid "name" msgstr "" # Default: News msgid "news" msgstr "" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "" # Default: Nick names msgid "nick-names" msgstr "" # Default: Notes msgid "notes" msgstr "" # Default: Novel msgid "novel" msgstr "" # Default: Number msgid "number" msgstr "" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "" # Default: Number of episodes msgid "number-of-episodes" msgstr "" # Default: Number of seasons msgid "number-of-seasons" msgstr "" # Default: Number of sides msgid "number-of-sides" msgstr "" # Default: Number of votes msgid "number-of-votes" msgstr "" # Default: Official retail price msgid "official-retail-price" msgstr "" # Default: Official sites msgid "official-sites" msgstr "" # Default: Opening weekend msgid "opening-weekend" msgstr "" # Default: Original air date msgid "original-air-date" msgstr "" # Default: Original music msgid "original-music" msgstr "" # Default: Original title msgid "original-title" msgstr "" # Default: Other literature msgid "other-literature" msgstr "" # Default: Other works msgid "other-works" msgstr "" # Default: Parents guide msgid "parents-guide" msgstr "" # Default: Performed by msgid "performed-by" msgstr "" # Default: Person msgid "person" msgstr "" # Default: Photo sites msgid "photo-sites" msgstr "" # Default: Pictorial msgid "pictorial" msgstr "" # Default: Picture format msgid "picture-format" msgstr "" # Default: Plot msgid "plot" msgstr "" # Default: Plot outline msgid "plot-outline" msgstr "" # Default: Portrayed in msgid "portrayed-in" msgstr "" # Default: Pressing plant msgid "pressing-plant" msgstr "" # Default: Printed film format msgid "printed-film-format" msgstr "" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "" # Default: Producer msgid "producer" msgstr "" # Default: Production companies msgid "production-companies" msgstr "" # Default: Production country msgid "production-country" msgstr "" # Default: Production dates msgid "production-dates" msgstr "" # Default: Production design msgid "production-design" msgstr "" # Default: Production designer msgid "production-designer" msgstr "" # Default: Production manager msgid "production-manager" msgstr "" # Default: Production process protocol msgid "production-process-protocol" msgstr "" # Default: Quality of source msgid "quality-of-source" msgstr "" # Default: Quality program msgid "quality-program" msgstr "" # Default: Quote msgid "quote" msgstr "" # Default: Quotes msgid "quotes" msgstr "" # Default: Rating msgid "rating" msgstr "" # Default: Recommendations msgid "recommendations" msgstr "" # Default: Referenced in msgid "referenced-in" msgstr "" # Default: References msgid "references" msgstr "" # Default: Region msgid "region" msgstr "" # Default: Release country msgid "release-country" msgstr "" # Default: Release date msgid "release-date" msgstr "" # Default: Release dates msgid "release-dates" msgstr "" # Default: Remade as msgid "remade-as" msgstr "" # Default: Remake of msgid "remake-of" msgstr "" # Default: Rentals msgid "rentals" msgstr "" # Default: Result msgid "result" msgstr "" # Default: Review msgid "review" msgstr "" # Default: Review author msgid "review-author" msgstr "" # Default: Review kind msgid "review-kind" msgstr "" # Default: Runtime msgid "runtime" msgstr "" # Default: Runtimes msgid "runtimes" msgstr "" # Default: Salary history msgid "salary-history" msgstr "" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "" # Default: Season msgid "season" msgstr "" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "" # Default: Self msgid "self" msgstr "" # Default: Series animation department msgid "series-animation-department" msgstr "" # Default: Series art department msgid "series-art-department" msgstr "" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "" # Default: Series camera department msgid "series-camera-department" msgstr "" # Default: Series casting department msgid "series-casting-department" msgstr "" # Default: Series cinematographers msgid "series-cinematographers" msgstr "" # Default: Series costume department msgid "series-costume-department" msgstr "" # Default: Series editorial department msgid "series-editorial-department" msgstr "" # Default: Series editors msgid "series-editors" msgstr "" # Default: Series make up department msgid "series-make-up-department" msgstr "" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "" # Default: Series music department msgid "series-music-department" msgstr "" # Default: Series producers msgid "series-producers" msgstr "" # Default: Series production designers msgid "series-production-designers" msgstr "" # Default: Series production managers msgid "series-production-managers" msgstr "" # Default: Series sound department msgid "series-sound-department" msgstr "" # Default: Series special effects department msgid "series-special-effects-department" msgstr "" # Default: Series stunts msgid "series-stunts" msgstr "" # Default: Series title msgid "series-title" msgstr "" # Default: Series transportation department msgid "series-transportation-department" msgstr "" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "" # Default: Series writers msgid "series-writers" msgstr "" # Default: Series years msgid "series-years" msgstr "" # Default: Set decoration msgid "set-decoration" msgstr "" # Default: Sharpness msgid "sharpness" msgstr "" # Default: Similar to msgid "similar-to" msgstr "" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "" # Default: Sound clips msgid "sound-clips" msgstr "" # Default: Sound crew msgid "sound-crew" msgstr "" # Default: Sound encoding msgid "sound-encoding" msgstr "" # Default: Sound mix msgid "sound-mix" msgstr "" # Default: Soundtrack msgid "soundtrack" msgstr "" # Default: Spaciality msgid "spaciality" msgstr "" # Default: Special effects msgid "special-effects" msgstr "" # Default: Special effects companies msgid "special-effects-companies" msgstr "" # Default: Special effects department msgid "special-effects-department" msgstr "" # Default: Spin off msgid "spin-off" msgstr "" # Default: Spin off from msgid "spin-off-from" msgstr "" # Default: Spoofed in msgid "spoofed-in" msgstr "" # Default: Spoofs msgid "spoofs" msgstr "" # Default: Spouse msgid "spouse" msgstr "" # Default: Status of availablility msgid "status-of-availablility" msgstr "" # Default: Studio msgid "studio" msgstr "" # Default: Studios msgid "studios" msgstr "" # Default: Stunt performer msgid "stunt-performer" msgstr "" # Default: Stunts msgid "stunts" msgstr "" # Default: Subtitles msgid "subtitles" msgstr "" # Default: Supplement msgid "supplement" msgstr "" # Default: Supplements msgid "supplements" msgstr "" # Default: Synopsis msgid "synopsis" msgstr "" # Default: Taglines msgid "taglines" msgstr "" # Default: Tech info msgid "tech-info" msgstr "" # Default: Thanks msgid "thanks" msgstr "" # Default: Time msgid "time" msgstr "" # Default: Title msgid "title" msgstr "" # Default: Titles in this product msgid "titles-in-this-product" msgstr "" # Default: To msgid "to" msgstr "" # Default: Top 250 rank msgid "top-250-rank" msgstr "" # Default: Trade mark msgid "trade-mark" msgstr "" # Default: Transportation department msgid "transportation-department" msgstr "" # Default: Trivia msgid "trivia" msgstr "" # Default: Tv msgid "tv" msgstr "" # Default: Under license from msgid "under-license-from" msgstr "" # Default: Unknown link msgid "unknown-link" msgstr "" # Default: Upc msgid "upc" msgstr "" # Default: Version of msgid "version-of" msgstr "" # Default: Vhs msgid "vhs" msgstr "" # Default: Video msgid "video" msgstr "" # Default: Video artifacts msgid "video-artifacts" msgstr "" # Default: Video clips msgid "video-clips" msgstr "" # Default: Video noise msgid "video-noise" msgstr "" # Default: Video quality msgid "video-quality" msgstr "" # Default: Video standard msgid "video-standard" msgstr "" # Default: Visual effects msgid "visual-effects" msgstr "" # Default: Votes msgid "votes" msgstr "" # Default: Votes distribution msgid "votes-distribution" msgstr "" # Default: Weekend gross msgid "weekend-gross" msgstr "" # Default: Where now msgid "where-now" msgstr "" # Default: With msgid "with" msgstr "" # Default: Writer msgid "writer" msgstr "" # Default: Written by msgid "written-by" msgstr "" # Default: Year msgid "year" msgstr "" # Default: Zshops msgid "zshops" msgstr ""
18,867
Python
.py
979
17.942799
53
0.779403
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,201
imdbpy-de.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-de.po
# Gettext message file for imdbpy # Translators: # Martin Gri <[email protected]>, 2017 # Nils Welzk, 2013 # Raphael, 2014 # vaeng vaeng <[email protected]>, 2018 msgid "" msgstr "" "Project-Id-Version: Cinemagoer\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2018-11-14 12:49+0000\n" "Last-Translator: vaeng vaeng <[email protected]>\n" "Language-Team: German (http://www.transifex.com/davide_alberani/imdbpy/language/de/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Domain: imdbpy\n" "Language: de\n" "Language-Code: en\n" "Language-Name: English\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Preferred-Encodings: utf-8\n" # Default: Actor msgid "actor" msgstr "Schauspieler" # Default: Actress msgid "actress" msgstr "Schauspielerin" # Default: Adaption msgid "adaption" msgstr "Anpassung" # Default: Additional information msgid "additional-information" msgstr "zusätzliche Information" # Default: Admissions msgid "admissions" msgstr "Zulassung" # Default: Agent address msgid "agent-address" msgstr "Adresse des Agenten" # Default: Airing msgid "airing" msgstr "Belüftung" # Default: Akas msgid "akas" msgstr "Pseudonüme" # Default: Akas from release info msgid "akas-from-release-info" msgstr "auch bekannt von der Veröffentlichungsinfo" # Default: All products msgid "all-products" msgstr "Alle Produkte" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "Alternative Spachversionen von" # Default: Alternate versions msgid "alternate-versions" msgstr "Alternative Version" # Default: Amazon reviews msgid "amazon-reviews" msgstr "Amazon Rezensionen" # Default: Analog left msgid "analog-left" msgstr "analog-links" # Default: Analog right msgid "analog-right" msgstr "analog-rechts" # Default: Animation department msgid "animation-department" msgstr "animations Abteilung" # Default: Archive footage msgid "archive-footage" msgstr "Archivaufnahme" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "Kalkulatorische folgen" # Default: Art department msgid "art-department" msgstr "Kunst Abteilung" # Default: Art direction msgid "art-direction" msgstr "" # Default: Art director msgid "art-director" msgstr "Art Director" # Default: Article msgid "article" msgstr "Artikel" # Default: Asin msgid "asin" msgstr "" # Default: Aspect ratio msgid "aspect-ratio" msgstr "Seitenverhältnis" # Default: Assigner msgid "assigner" msgstr "Zuweiser" # Default: Assistant director msgid "assistant-director" msgstr "Chefzuweiser" # Default: Auctions msgid "auctions" msgstr "Auktionen" # Default: Audio noise msgid "audio-noise" msgstr "Audio rauschen" # Default: Audio quality msgid "audio-quality" msgstr "Audio Qualität" # Default: Award msgid "award" msgstr "Auszeichnung" # Default: Awards msgid "awards" msgstr "Auszeichnungen" # Default: Biographical movies msgid "biographical-movies" msgstr "Filmbiographie" # Default: Biography msgid "biography" msgstr "Biographie" # Default: Biography print msgid "biography-print" msgstr "Biographiebuch" # Default: Birth date msgid "birth-date" msgstr "Geburtsdatum" # Default: Birth name msgid "birth-name" msgstr "Geburtsname" # Default: Birth notes msgid "birth-notes" msgstr "Geburtsnotizen" # Default: Body msgid "body" msgstr "Körper" # Default: Book msgid "book" msgstr "Buch" # Default: Books msgid "books" msgstr "Bücher" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "" # Default: Budget msgid "budget" msgstr "Kosten" # Default: Business msgid "business" msgstr "Geschäft" # Default: By arrangement with msgid "by-arrangement-with" msgstr "eine Vereinbarung mit" # Default: Camera msgid "camera" msgstr "Kamera" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "Abteilung für Kamera und Elektronik" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "Aussagekräftiger Titel der Folge" # Default: Canonical name msgid "canonical-name" msgstr "Aussagekräftiger Name" # Default: Canonical series title msgid "canonical-series-title" msgstr "Aussagekräftiger Serien Titel" # Default: Canonical title msgid "canonical-title" msgstr "Aussagekräftiger Titel" # Default: Cast msgid "cast" msgstr "Besetzung" # Default: Casting department msgid "casting-department" msgstr "Abteilung für Rollenverteilung" # Default: Casting director msgid "casting-director" msgstr "Abteilungsleiter für Rollenverteilung" # Default: Catalog number msgid "catalog-number" msgstr "Katalog Nummer" # Default: Category msgid "category" msgstr "Kategorie" # Default: Certificate msgid "certificate" msgstr "Zertifikat" # Default: Certificates msgid "certificates" msgstr "Zertifikate" # Default: Certification msgid "certification" msgstr "Bescheinigung" # Default: Channel msgid "channel" msgstr "Kanal" # Default: Character msgid "character" msgstr "Persönlichkeit" # Default: Cinematographer msgid "cinematographer" msgstr "Kameramann" # Default: Cinematographic process msgid "cinematographic-process" msgstr "Kinematograpischer Prozess" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "Farbinfo" # Default: Color information msgid "color-information" msgstr "Farbinformationen" # Default: Color rendition msgid "color-rendition" msgstr "Farbwiedergabe" # Default: Company msgid "company" msgstr "Firma" # Default: Complete cast msgid "complete-cast" msgstr "" # Default: Complete crew msgid "complete-crew" msgstr "Komplettes Team" # Default: Composer msgid "composer" msgstr "Komponist" # Default: Connections msgid "connections" msgstr "Verbindungen" # Default: Contrast msgid "contrast" msgstr "Kontrast" # Default: Copyright holder msgid "copyright-holder" msgstr "Besitzer der Kopierrechte" # Default: Costume department msgid "costume-department" msgstr "Abteilung für Kostüme" # Default: Costume designer msgid "costume-designer" msgstr "Kostümdesigner" # Default: Countries msgid "countries" msgstr "Länder" # Default: Country msgid "country" msgstr "Land" # Default: Courtesy of msgid "courtesy-of" msgstr "mit freundlicher Genehmigung von" # Default: Cover msgid "cover" msgstr "Cover" # Default: Cover url msgid "cover-url" msgstr "Cover-URL" # Default: Crazy credits msgid "crazy-credits" msgstr "" # Default: Creator msgid "creator" msgstr "Ersteller" # Default: Current role msgid "current-role" msgstr "Aktuelle Rolle" # Default: Database msgid "database" msgstr "Datenbank" # Default: Date msgid "date" msgstr "Datum" # Default: Death date msgid "death-date" msgstr "Todestag" # Default: Death notes msgid "death-notes" msgstr "Notizen zum Tod" # Default: Demographic msgid "demographic" msgstr "demographisch" # Default: Description msgid "description" msgstr "Beschreibung" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "Dialog Verständlichkeit" # Default: Digital sound msgid "digital-sound" msgstr "Digitaler Sound" # Default: Director msgid "director" msgstr "Direktor" # Default: Disc format msgid "disc-format" msgstr "Diskettenformat" # Default: Disc size msgid "disc-size" msgstr "Diskettengröße" # Default: Distributors msgid "distributors" msgstr "Händler" # Default: Dvd msgid "dvd" msgstr "DVD" # Default: Dvd features msgid "dvd-features" msgstr "dvd-features" # Default: Dvd format msgid "dvd-format" msgstr "dvd-format" # Default: Dvds msgid "dvds" msgstr "DVDs" # Default: Dynamic range msgid "dynamic-range" msgstr "dynamische Länge" # Default: Edited from msgid "edited-from" msgstr "bearbeitet von" # Default: Edited into msgid "edited-into" msgstr "Eingefügt" # Default: Editor msgid "editor" msgstr "Editor" # Default: Editorial department msgid "editorial-department" msgstr "Abteilung für Leitartikel" # Default: Episode msgid "episode" msgstr "Episode" # Default: Episode of msgid "episode-of" msgstr "Episode von" # Default: Episode title msgid "episode-title" msgstr "Episodentitel" # Default: Episodes msgid "episodes" msgstr "Episoden" # Default: Episodes rating msgid "episodes-rating" msgstr "Episoden Bewertung" # Default: Essays msgid "essays" msgstr "Sammlung" # Default: External reviews msgid "external-reviews" msgstr "Externer Bericht" # Default: Faqs msgid "faqs" msgstr "FAQs" # Default: Feature msgid "feature" msgstr "Merkmal" # Default: Featured in msgid "featured-in" msgstr "" # Default: Features msgid "features" msgstr "Merkmale" # Default: Film negative format msgid "film-negative-format" msgstr "" # Default: Filming dates msgid "filming-dates" msgstr "Drehtermine" # Default: Filmography msgid "filmography" msgstr "Filmografie" # Default: Followed by msgid "followed-by" msgstr "gefolgt von" # Default: Follows msgid "follows" msgstr "folgt" # Default: For msgid "for" msgstr "für" # Default: Frequency response msgid "frequency-response" msgstr "antwort Häufigkeit" # Default: From msgid "from" msgstr "von" # Default: Full article link msgid "full-article-link" msgstr "Link zum vollen Artikel" # Default: Full size cover url msgid "full-size-cover-url" msgstr "URL zum Cover in voller Größe" # Default: Full size headshot msgid "full-size-headshot" msgstr "Portait in voller Größe" # Default: Genres msgid "genres" msgstr "Genres" # Default: Goofs msgid "goofs" msgstr "Filmfehler" # Default: Gross msgid "gross" msgstr "Einnahmen" # Default: Group genre msgid "group-genre" msgstr "Genre Gruppe" # Default: Headshot msgid "headshot" msgstr "Portrait" # Default: Height msgid "height" msgstr "Höhe" # Default: Imdbindex msgid "imdbindex" msgstr "IMdB Index" # Default: In development msgid "in-development" msgstr "In der Entwicklung" # Default: Interview msgid "interview" msgstr "Interview" # Default: Interviews msgid "interviews" msgstr "Interviews" # Default: Introduction msgid "introduction" msgstr "Vorstellung" # Default: Item msgid "item" msgstr "Gegenstand" # Default: Keywords msgid "keywords" msgstr "Schlüsselwörter" # Default: Kind msgid "kind" msgstr "so in der Art" # Default: Label msgid "label" msgstr "Bezeichnung" # Default: Laboratory msgid "laboratory" msgstr "Labor" # Default: Language msgid "language" msgstr "Sprache" # Default: Languages msgid "languages" msgstr "Sprachen" # Default: Laserdisc msgid "laserdisc" msgstr "Laserdisc" # Default: Laserdisc title msgid "laserdisc-title" msgstr "Laserdisc Titel" # Default: Length msgid "length" msgstr "Länge" # Default: Line msgid "line" msgstr "Linie" # Default: Link msgid "link" msgstr "Link" # Default: Link text msgid "link-text" msgstr "Link Text" # Default: Literature msgid "literature" msgstr "Literatur" # Default: Locations msgid "locations" msgstr "Standorte" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "langer IMdB Aussagekräftiger Name" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "langer IMdB Aussagekräftiger Titel" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "langer IMdB Folgentitel" # Default: Long imdb name msgid "long-imdb-name" msgstr "langer IMdB Name" # Default: Long imdb title msgid "long-imdb-title" msgstr "langer IMdB Titel" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "Titelseiten Foto" # Default: Make up msgid "make-up" msgstr "Makeup" # Default: Master format msgid "master-format" msgstr "Master Format" # Default: Median msgid "median" msgstr "durchschnitt" # Default: Merchandising links msgid "merchandising-links" msgstr "Link zu Fanartikeln" # Default: Mini biography msgid "mini-biography" msgstr "kleine Biographie" # Default: Misc links msgid "misc-links" msgstr "andere Links" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "diverse Firmen" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "andere Crew" # Default: Movie msgid "movie" msgstr "Film" # Default: Mpaa msgid "mpaa" msgstr "Film ID" # Default: Music department msgid "music-department" msgstr "Abteilung für Musik" # Default: Name msgid "name" msgstr "Name" # Default: News msgid "news" msgstr "Nachrichten" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "Newsgruppen Berichte" # Default: Nick names msgid "nick-names" msgstr "Spitznamen" # Default: Notes msgid "notes" msgstr "Anmerkungen" # Default: Novel msgid "novel" msgstr "Roman" # Default: Number msgid "number" msgstr "Zahl" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "Anzahl der Kapitel Stops" # Default: Number of episodes msgid "number-of-episodes" msgstr "Anzahl der Folgen" # Default: Number of seasons msgid "number-of-seasons" msgstr "Anzahl der Staffel(n)" # Default: Number of sides msgid "number-of-sides" msgstr "Anzahl der Seiten" # Default: Number of votes msgid "number-of-votes" msgstr "Anzahl der Stimmen" # Default: Official retail price msgid "official-retail-price" msgstr "Offizieller Verkaufspreis" # Default: Official sites msgid "official-sites" msgstr "Offizielle Seiten" # Default: Opening weekend msgid "opening-weekend" msgstr "Eröffnungswochenende" # Default: Original air date msgid "original-air-date" msgstr "Originales Ausstrahlungsdatum" # Default: Original music msgid "original-music" msgstr "Original Musik" # Default: Original title msgid "original-title" msgstr "Original Titel" # Default: Other literature msgid "other-literature" msgstr "andere Literatur" # Default: Other works msgid "other-works" msgstr "andere Arbeiten" # Default: Parents guide msgid "parents-guide" msgstr "Anleitung für Eltern" # Default: Performed by msgid "performed-by" msgstr "durchgeführt von" # Default: Person msgid "person" msgstr "Person" # Default: Photo sites msgid "photo-sites" msgstr "Foto Seiten" # Default: Pictorial msgid "pictorial" msgstr "illustriert" # Default: Picture format msgid "picture-format" msgstr "Foto Format" # Default: Plot msgid "plot" msgstr "Handlung" # Default: Plot outline msgid "plot-outline" msgstr "Abspann" # Default: Portrayed in msgid "portrayed-in" msgstr "Dargestellt" # Default: Pressing plant msgid "pressing-plant" msgstr "Druckwerk" # Default: Printed film format msgid "printed-film-format" msgstr "gedrucktes Film Format" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "gedruckte Medien Berichte" # Default: Producer msgid "producer" msgstr "Produzent" # Default: Production companies msgid "production-companies" msgstr "Produktionsfirmen" # Default: Production country msgid "production-country" msgstr "Produktionsland" # Default: Production dates msgid "production-dates" msgstr "Produktionsdatum" # Default: Production design msgid "production-design" msgstr "Produktstionsdesign" # Default: Production designer msgid "production-designer" msgstr "Produktionsdesigner" # Default: Production manager msgid "production-manager" msgstr "Produktionsmanager" # Default: Production process protocol msgid "production-process-protocol" msgstr "Produktions Ablaufprotokoll" # Default: Quality of source msgid "quality-of-source" msgstr "Qualität der Quelle" # Default: Quality program msgid "quality-program" msgstr "Qualitätsprogramm" # Default: Quote msgid "quote" msgstr "Zitat" # Default: Quotes msgid "quotes" msgstr "Zitate" # Default: Rating msgid "rating" msgstr "Bewertung" # Default: Recommendations msgid "recommendations" msgstr "Empfehlungen" # Default: Referenced in msgid "referenced-in" msgstr "Verweis auf" # Default: References msgid "references" msgstr "Verweis" # Default: Region msgid "region" msgstr "Region" # Default: Release country msgid "release-country" msgstr "Veröffentlichungsland" # Default: Release date msgid "release-date" msgstr "Veröffentlichungsdatum" # Default: Release dates msgid "release-dates" msgstr "Veröffentlichungstermine" # Default: Remade as msgid "remade-as" msgstr "Wiederaufmachung als" # Default: Remake of msgid "remake-of" msgstr "Remake von" # Default: Rentals msgid "rentals" msgstr "Leigebühr" # Default: Result msgid "result" msgstr "Ergebnis" # Default: Review msgid "review" msgstr "Kritik" # Default: Review author msgid "review-author" msgstr "Kritik Autor" # Default: Review kind msgid "review-kind" msgstr "Kritik Art" # Default: Runtime msgid "runtime" msgstr "Laufzeit" # Default: Runtimes msgid "runtimes" msgstr "Laufzeiten" # Default: Salary history msgid "salary-history" msgstr "Gehaltsverlauf" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "" # Default: Season msgid "season" msgstr "Staffel" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "Stellvertretender Direktor" # Default: Self msgid "self" msgstr "selbst" # Default: Series animation department msgid "series-animation-department" msgstr "Abteilung für Serienanimation" # Default: Series art department msgid "series-art-department" msgstr "" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "" # Default: Series camera department msgid "series-camera-department" msgstr "" # Default: Series casting department msgid "series-casting-department" msgstr "" # Default: Series cinematographers msgid "series-cinematographers" msgstr "" # Default: Series costume department msgid "series-costume-department" msgstr "" # Default: Series editorial department msgid "series-editorial-department" msgstr "" # Default: Series editors msgid "series-editors" msgstr "" # Default: Series make up department msgid "series-make-up-department" msgstr "" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "Verschiedene (Serie)" # Default: Series music department msgid "series-music-department" msgstr "Abteilung für Musik (Serie)" # Default: Series producers msgid "series-producers" msgstr "Serien Hersteller" # Default: Series production designers msgid "series-production-designers" msgstr "Produktionsdesign (Serie)" # Default: Series production managers msgid "series-production-managers" msgstr "Manager der Serie" # Default: Series sound department msgid "series-sound-department" msgstr "Abteilung für Sound-Serien" # Default: Series special effects department msgid "series-special-effects-department" msgstr "Abteilung für Spezialeffekte-Serien" # Default: Series stunts msgid "series-stunts" msgstr "Serien Stunts" # Default: Series title msgid "series-title" msgstr "Serien Titel" # Default: Series transportation department msgid "series-transportation-department" msgstr "" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "Abteilung für Visuelle Effekte / Serien" # Default: Series writers msgid "series-writers" msgstr "Serienschreiber" # Default: Series years msgid "series-years" msgstr "Serien Jahre" # Default: Set decoration msgid "set-decoration" msgstr "Set Dekoration" # Default: Sharpness msgid "sharpness" msgstr "Schärfe" # Default: Similar to msgid "similar-to" msgstr "vergleichbar mit" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "" # Default: Sound clips msgid "sound-clips" msgstr "Sound Clips" # Default: Sound crew msgid "sound-crew" msgstr "Sound Crew" # Default: Sound encoding msgid "sound-encoding" msgstr "Klangkodierung" # Default: Sound mix msgid "sound-mix" msgstr "Sound Mix" # Default: Soundtrack msgid "soundtrack" msgstr "Soundtrack" # Default: Spaciality msgid "spaciality" msgstr "Räumlichkeit" # Default: Special effects msgid "special-effects" msgstr "Spezialeffekte" # Default: Special effects companies msgid "special-effects-companies" msgstr "Firma für Spezialeffekte" # Default: Special effects department msgid "special-effects-department" msgstr "Abteilung für Spezialeffekte" # Default: Spin off msgid "spin-off" msgstr "Nebenprodukt" # Default: Spin off from msgid "spin-off-from" msgstr "Nebenprodukt von" # Default: Spoofed in msgid "spoofed-in" msgstr "Parodiert in" # Default: Spoofs msgid "spoofs" msgstr "Parodie" # Default: Spouse msgid "spouse" msgstr "Gattin" # Default: Status of availablility msgid "status-of-availablility" msgstr "Verfügbarkeitsstatus" # Default: Studio msgid "studio" msgstr "Studio" # Default: Studios msgid "studios" msgstr "Studios" # Default: Stunt performer msgid "stunt-performer" msgstr "Stunt-Darsteller" # Default: Stunts msgid "stunts" msgstr "Stunts" # Default: Subtitles msgid "subtitles" msgstr "Untertitel" # Default: Supplement msgid "supplement" msgstr "Ergänzung" # Default: Supplements msgid "supplements" msgstr "Ergänzungen" # Default: Synopsis msgid "synopsis" msgstr "Zusammenfassung" # Default: Taglines msgid "taglines" msgstr "Slogan" # Default: Tech info msgid "tech-info" msgstr "Technische Informationen" # Default: Thanks msgid "thanks" msgstr "Danke" # Default: Time msgid "time" msgstr "Zeit" # Default: Title msgid "title" msgstr "Titel" # Default: Titles in this product msgid "titles-in-this-product" msgstr "Titel in dem Produkt" # Default: To msgid "to" msgstr "zu" # Default: Top 250 rank msgid "top-250-rank" msgstr "Top 250 platzierung" # Default: Trade mark msgid "trade-mark" msgstr "Warenzeichen" # Default: Transportation department msgid "transportation-department" msgstr "Speditionsunternehmen" # Default: Trivia msgid "trivia" msgstr "Nichtigkeiten" # Default: Tv msgid "tv" msgstr "TV" # Default: Under license from msgid "under-license-from" msgstr "lizensiert von" # Default: Unknown link msgid "unknown-link" msgstr "Unbekannter Link" # Default: Upc msgid "upc" msgstr "" # Default: Version of msgid "version-of" msgstr "Version von" # Default: Vhs msgid "vhs" msgstr "VHS" # Default: Video msgid "video" msgstr "Video" # Default: Video artifacts msgid "video-artifacts" msgstr "Video Ausschnitte" # Default: Video clips msgid "video-clips" msgstr "Video Clips" # Default: Video noise msgid "video-noise" msgstr "Video Rauschen" # Default: Video quality msgid "video-quality" msgstr "Video Qualität" # Default: Video standard msgid "video-standard" msgstr "Video Standart" # Default: Visual effects msgid "visual-effects" msgstr "Visuelle Effekte" # Default: Votes msgid "votes" msgstr "Stimmen" # Default: Votes distribution msgid "votes-distribution" msgstr "Abstimmungsverteilung" # Default: Weekend gross msgid "weekend-gross" msgstr "Einspielungen am ersten Wochenende" # Default: Where now msgid "where-now" msgstr "wo jetzt " # Default: With msgid "with" msgstr "mit" # Default: Writer msgid "writer" msgstr "Autor" # Default: Written by msgid "written-by" msgstr "Geschrieben von" # Default: Year msgid "year" msgstr "Jahr" # Default: Zshops msgid "zshops" msgstr ""
23,174
Python
.py
985
22.137056
88
0.810227
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,202
imdbpy-en.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-en.po
# Gettext message file for imdbpy msgid "" msgstr "" "Project-Id-Version: imdbpy\n" "POT-Creation-Date: 2009-04-16 14:27+0000\n" "PO-Revision-Date: YYYY-MM-DD HH:MM+0000\n" "Last-Translator: YOUR NAME <YOUR@EMAIL>\n" "Language-Team: TEAM NAME <TEAM@EMAIL>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "Language-Code: en\n" "Language-Name: English\n" "Preferred-Encodings: utf-8\n" "Domain: imdbpy\n" # Default: Actor msgid "actor" msgstr "Actor" # Default: Actress msgid "actress" msgstr "Actress" # Default: Adaption msgid "adaption" msgstr "Adaption" # Default: Additional information msgid "additional-information" msgstr "Additional information" # Default: Admissions msgid "admissions" msgstr "Admissions" # Default: Agent address msgid "agent-address" msgstr "Agent address" # Default: Airing msgid "airing" msgstr "Airing" # Default: Akas msgid "akas" msgstr "Akas" # Default: All products msgid "all-products" msgstr "All products" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "Alternate language version of" # Default: Alternate versions msgid "alternate-versions" msgstr "Alternate versions" # Default: Amazon reviews msgid "amazon-reviews" msgstr "Amazon reviews" # Default: Analog left msgid "analog-left" msgstr "Analog left" # Default: Analog right msgid "analog-right" msgstr "Analog right" # Default: Animation department msgid "animation-department" msgstr "Animation department" # Default: Archive footage msgid "archive-footage" msgstr "Archive footage" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "Arithmetic mean" # Default: Art department msgid "art-department" msgstr "Art department" # Default: Art direction msgid "art-direction" msgstr "Art direction" # Default: Art director msgid "art-director" msgstr "Art director" # Default: Article msgid "article" msgstr "Article" # Default: Asin msgid "asin" msgstr "Asin" # Default: Aspect ratio msgid "aspect-ratio" msgstr "Aspect ratio" # Default: Assigner msgid "assigner" msgstr "Assigner" # Default: Assistant director msgid "assistant-director" msgstr "Assistant director" # Default: Auctions msgid "auctions" msgstr "Auctions" # Default: Audio noise msgid "audio-noise" msgstr "Audio noise" # Default: Audio quality msgid "audio-quality" msgstr "Audio quality" # Default: Award msgid "award" msgstr "Award" # Default: Awards msgid "awards" msgstr "Awards" # Default: Biographical movies msgid "biographical-movies" msgstr "Biographical movies" # Default: Biography msgid "biography" msgstr "Biography" # Default: Biography print msgid "biography-print" msgstr "Biography print" # Default: Birth date msgid "birth-date" msgstr "Birth date" # Default: Birth name msgid "birth-name" msgstr "Birth name" # Default: Birth notes msgid "birth-notes" msgstr "Birth notes" # Default: Body msgid "body" msgstr "Body" # Default: Book msgid "book" msgstr "Book" # Default: Books msgid "books" msgstr "Books" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "Bottom 100 rank" # Default: Budget msgid "budget" msgstr "Budget" # Default: Business msgid "business" msgstr "Business" # Default: By arrangement with msgid "by-arrangement-with" msgstr "By arrangement with" # Default: Camera msgid "camera" msgstr "Camera" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "Camera and electrical department" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "Canonical episode title" # Default: Canonical name msgid "canonical-name" msgstr "Canonical name" # Default: Canonical series title msgid "canonical-series-title" msgstr "Canonical series title" # Default: Canonical title msgid "canonical-title" msgstr "Canonical title" # Default: Cast msgid "cast" msgstr "Cast" # Default: Casting department msgid "casting-department" msgstr "Casting department" # Default: Casting director msgid "casting-director" msgstr "Casting director" # Default: Catalog number msgid "catalog-number" msgstr "Catalog number" # Default: Category msgid "category" msgstr "Category" # Default: Certificate msgid "certificate" msgstr "Certificate" # Default: Certificates msgid "certificates" msgstr "Certificates" # Default: Certification msgid "certification" msgstr "Certification" # Default: Channel msgid "channel" msgstr "Channel" # Default: Character msgid "character" msgstr "Character" # Default: Cinematographer msgid "cinematographer" msgstr "Cinematographer" # Default: Cinematographic process msgid "cinematographic-process" msgstr "Cinematographic process" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "Close captions teletext ld g" # Default: Color info msgid "color-info" msgstr "Color info" # Default: Color information msgid "color-information" msgstr "Color information" # Default: Color rendition msgid "color-rendition" msgstr "Color rendition" # Default: Company msgid "company" msgstr "Company" # Default: Complete cast msgid "complete-cast" msgstr "Complete cast" # Default: Complete crew msgid "complete-crew" msgstr "Complete crew" # Default: Composer msgid "composer" msgstr "Composer" # Default: Connections msgid "connections" msgstr "Connections" # Default: Contrast msgid "contrast" msgstr "Contrast" # Default: Copyright holder msgid "copyright-holder" msgstr "Copyright holder" # Default: Costume department msgid "costume-department" msgstr "Costume department" # Default: Costume designer msgid "costume-designer" msgstr "Costume designer" # Default: Countries msgid "countries" msgstr "Countries" # Default: Country msgid "country" msgstr "Country" # Default: Courtesy of msgid "courtesy-of" msgstr "Courtesy of" # Default: Cover msgid "cover" msgstr "Cover" # Default: Cover url msgid "cover-url" msgstr "Cover url" # Default: Crazy credits msgid "crazy-credits" msgstr "Crazy credits" # Default: Creator msgid "creator" msgstr "Creator" # Default: Current role msgid "current-role" msgstr "Current role" # Default: Database msgid "database" msgstr "Database" # Default: Date msgid "date" msgstr "Date" # Default: Death date msgid "death-date" msgstr "Death date" # Default: Death notes msgid "death-notes" msgstr "Death notes" # Default: Demographic msgid "demographic" msgstr "Demographic" # Default: Description msgid "description" msgstr "Description" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "Dialogue intellegibility" # Default: Digital sound msgid "digital-sound" msgstr "Digital sound" # Default: Director msgid "director" msgstr "Director" # Default: Disc format msgid "disc-format" msgstr "Disc format" # Default: Disc size msgid "disc-size" msgstr "Disc size" # Default: Distributors msgid "distributors" msgstr "Distributors" # Default: Dvd msgid "dvd" msgstr "Dvd" # Default: Dvd features msgid "dvd-features" msgstr "Dvd features" # Default: Dvd format msgid "dvd-format" msgstr "Dvd format" # Default: Dvds msgid "dvds" msgstr "Dvds" # Default: Dynamic range msgid "dynamic-range" msgstr "Dynamic range" # Default: Edited from msgid "edited-from" msgstr "Edited from" # Default: Edited into msgid "edited-into" msgstr "Edited into" # Default: Editor msgid "editor" msgstr "Editor" # Default: Editorial department msgid "editorial-department" msgstr "Editorial department" # Default: Episode msgid "episode" msgstr "Episode" # Default: Episode of msgid "episode-of" msgstr "Episode of" # Default: Episode title msgid "episode-title" msgstr "Episode title" # Default: Episodes msgid "episodes" msgstr "Episodes" # Default: Episodes rating msgid "episodes-rating" msgstr "Episodes rating" # Default: Essays msgid "essays" msgstr "Essays" # Default: External reviews msgid "external-reviews" msgstr "External reviews" # Default: Faqs msgid "faqs" msgstr "Faqs" # Default: Featured in msgid "featured-in" msgstr "Featured in" # Default: Features msgid "features" msgstr "Features" # Default: Film negative format msgid "film-negative-format" msgstr "Film negative format" # Default: Filming dates msgid "filming-dates" msgstr "Filming dates" # Default: Filmography msgid "filmography" msgstr "Filmography" # Default: Followed by msgid "followed-by" msgstr "Followed by" # Default: Follows msgid "follows" msgstr "Follows" # Default: For msgid "for" msgstr "For" # Default: Frequency response msgid "frequency-response" msgstr "Frequency response" # Default: From msgid "from" msgstr "From" # Default: Full article link msgid "full-article-link" msgstr "Full article link" # Default: Genres msgid "genres" msgstr "Genres" # Default: Goofs msgid "goofs" msgstr "Goofs" # Default: Gross msgid "gross" msgstr "Gross" # Default: Group genre msgid "group-genre" msgstr "Group genre" # Default: Headshot msgid "headshot" msgstr "Headshot" # Default: Height msgid "height" msgstr "Height" # Default: Imdbindex msgid "imdbindex" msgstr "Imdbindex" # Default: Interview msgid "interview" msgstr "Interview" # Default: Interviews msgid "interviews" msgstr "Interviews" # Default: Introduction msgid "introduction" msgstr "Introduction" # Default: Item msgid "item" msgstr "Item" # Default: Keywords msgid "keywords" msgstr "Keywords" # Default: Kind msgid "kind" msgstr "Kind" # Default: Label msgid "label" msgstr "Label" # Default: Laboratory msgid "laboratory" msgstr "Laboratory" # Default: Language msgid "language" msgstr "Language" # Default: Languages msgid "languages" msgstr "Languages" # Default: Laserdisc msgid "laserdisc" msgstr "Laserdisc" # Default: Laserdisc title msgid "laserdisc-title" msgstr "Laserdisc title" # Default: Length msgid "length" msgstr "Length" # Default: Line msgid "line" msgstr "Line" # Default: Link msgid "link" msgstr "Link" # Default: Link text msgid "link-text" msgstr "Link text" # Default: Literature msgid "literature" msgstr "Literature" # Default: Locations msgid "locations" msgstr "Locations" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "Long imdb canonical name" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "Long imdb canonical title" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "Long imdb episode title" # Default: Long imdb name msgid "long-imdb-name" msgstr "Long imdb name" # Default: Long imdb title msgid "long-imdb-title" msgstr "Long imdb title" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "Magazine cover photo" # Default: Make up msgid "make-up" msgstr "Make up" # Default: Master format msgid "master-format" msgstr "Master format" # Default: Median msgid "median" msgstr "Median" # Default: Merchandising links msgid "merchandising-links" msgstr "Merchandising links" # Default: Mini biography msgid "mini-biography" msgstr "Mini biography" # Default: Misc links msgid "misc-links" msgstr "Misc links" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "Miscellaneous companies" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "Miscellaneous crew" # Default: Movie msgid "movie" msgstr "Movie" # Default: Mpaa msgid "mpaa" msgstr "Mpaa" # Default: Music department msgid "music-department" msgstr "Music department" # Default: Name msgid "name" msgstr "Name" # Default: News msgid "news" msgstr "News" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "Newsgroup reviews" # Default: Nick names msgid "nick-names" msgstr "Nick names" # Default: Notes msgid "notes" msgstr "Notes" # Default: Novel msgid "novel" msgstr "Novel" # Default: Number msgid "number" msgstr "Number" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "Number of chapter stops" # Default: Number of episodes msgid "number-of-episodes" msgstr "Number of episodes" # Default: Number of seasons msgid "number-of-seasons" msgstr "Number of seasons" # Default: Number of sides msgid "number-of-sides" msgstr "Number of sides" # Default: Number of votes msgid "number-of-votes" msgstr "Number of votes" # Default: Official retail price msgid "official-retail-price" msgstr "Official retail price" # Default: Official sites msgid "official-sites" msgstr "Official sites" # Default: Opening weekend msgid "opening-weekend" msgstr "Opening weekend" # Default: Original air date msgid "original-air-date" msgstr "Original air date" # Default: Original music msgid "original-music" msgstr "Original music" # Default: Original title msgid "original-title" msgstr "Original title" # Default: Other literature msgid "other-literature" msgstr "Other literature" # Default: Other works msgid "other-works" msgstr "Other works" # Default: Parents guide msgid "parents-guide" msgstr "Parents guide" # Default: Performed by msgid "performed-by" msgstr "Performed by" # Default: Person msgid "person" msgstr "Person" # Default: Photo sites msgid "photo-sites" msgstr "Photo sites" # Default: Pictorial msgid "pictorial" msgstr "Pictorial" # Default: Picture format msgid "picture-format" msgstr "Picture format" # Default: Plot msgid "plot" msgstr "Plot" # Default: Plot outline msgid "plot-outline" msgstr "Plot outline" # Default: Portrayed in msgid "portrayed-in" msgstr "Portrayed in" # Default: Pressing plant msgid "pressing-plant" msgstr "Pressing plant" # Default: Printed film format msgid "printed-film-format" msgstr "Printed film format" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "Printed media reviews" # Default: Producer msgid "producer" msgstr "Producer" # Default: Production companies msgid "production-companies" msgstr "Production companies" # Default: Production country msgid "production-country" msgstr "Production country" # Default: Production dates msgid "production-dates" msgstr "Production dates" # Default: Production design msgid "production-design" msgstr "Production design" # Default: Production designer msgid "production-designer" msgstr "Production designer" # Default: Production manager msgid "production-manager" msgstr "Production manager" # Default: Production process protocol msgid "production-process-protocol" msgstr "Production process protocol" # Default: Quality of source msgid "quality-of-source" msgstr "Quality of source" # Default: Quality program msgid "quality-program" msgstr "Quality program" # Default: Quote msgid "quote" msgstr "Quote" # Default: Quotes msgid "quotes" msgstr "Quotes" # Default: Rating msgid "rating" msgstr "Rating" # Default: Recommendations msgid "recommendations" msgstr "Recommendations" # Default: Referenced in msgid "referenced-in" msgstr "Referenced in" # Default: References msgid "references" msgstr "References" # Default: Region msgid "region" msgstr "Region" # Default: Release country msgid "release-country" msgstr "Release country" # Default: Release date msgid "release-date" msgstr "Release date" # Default: Release dates msgid "release-dates" msgstr "Release dates" # Default: Remade as msgid "remade-as" msgstr "Remade as" # Default: Remake of msgid "remake-of" msgstr "Remake of" # Default: Rentals msgid "rentals" msgstr "Rentals" # Default: Result msgid "result" msgstr "Result" # Default: Review msgid "review" msgstr "Review" # Default: Review author msgid "review-author" msgstr "Review author" # Default: Review kind msgid "review-kind" msgstr "Review kind" # Default: Runtime msgid "runtime" msgstr "Runtime" # Default: Runtimes msgid "runtimes" msgstr "Runtimes" # Default: Salary history msgid "salary-history" msgstr "Salary history" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "Screenplay teleplay" # Default: Season msgid "season" msgstr "Season" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "Second unit director or assistant director" # Default: Self msgid "self" msgstr "Self" # Default: Series animation department msgid "series-animation-department" msgstr "Series animation department" # Default: Series art department msgid "series-art-department" msgstr "Series art department" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "Series assistant directors" # Default: Series camera department msgid "series-camera-department" msgstr "Series camera department" # Default: Series casting department msgid "series-casting-department" msgstr "Series casting department" # Default: Series cinematographers msgid "series-cinematographers" msgstr "Series cinematographers" # Default: Series costume department msgid "series-costume-department" msgstr "Series costume department" # Default: Series editorial department msgid "series-editorial-department" msgstr "Series editorial department" # Default: Series editors msgid "series-editors" msgstr "Series editors" # Default: Series make up department msgid "series-make-up-department" msgstr "Series make up department" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "Series miscellaneous" # Default: Series music department msgid "series-music-department" msgstr "Series music department" # Default: Series producers msgid "series-producers" msgstr "Series producers" # Default: Series production designers msgid "series-production-designers" msgstr "Series production designers" # Default: Series production managers msgid "series-production-managers" msgstr "Series production managers" # Default: Series sound department msgid "series-sound-department" msgstr "Series sound department" # Default: Series special effects department msgid "series-special-effects-department" msgstr "Series special effects department" # Default: Series stunts msgid "series-stunts" msgstr "Series stunts" # Default: Series title msgid "series-title" msgstr "Series title" # Default: Series transportation department msgid "series-transportation-department" msgstr "Series transportation department" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "Series visual effects department" # Default: Series writers msgid "series-writers" msgstr "Series writers" # Default: Series years msgid "series-years" msgstr "Series years" # Default: Set decoration msgid "set-decoration" msgstr "Set decoration" # Default: Sharpness msgid "sharpness" msgstr "Sharpness" # Default: Similar to msgid "similar-to" msgstr "Similar to" # Default: Sound clips msgid "sound-clips" msgstr "Sound clips" # Default: Sound crew msgid "sound-crew" msgstr "Sound crew" # Default: Sound encoding msgid "sound-encoding" msgstr "Sound encoding" # Default: Sound mix msgid "sound-mix" msgstr "Sound mix" # Default: Soundtrack msgid "soundtrack" msgstr "Soundtrack" # Default: Spaciality msgid "spaciality" msgstr "Spaciality" # Default: Special effects msgid "special-effects" msgstr "Special effects" # Default: Special effects companies msgid "special-effects-companies" msgstr "Special effects companies" # Default: Special effects department msgid "special-effects-department" msgstr "Special effects department" # Default: Spin off msgid "spin-off" msgstr "Spin off" # Default: Spin off from msgid "spin-off-from" msgstr "Spin off from" # Default: Spoofed in msgid "spoofed-in" msgstr "Spoofed in" # Default: Spoofs msgid "spoofs" msgstr "Spoofs" # Default: Spouse msgid "spouse" msgstr "Spouse" # Default: Status of availablility msgid "status-of-availablility" msgstr "Status of availablility" # Default: Studio msgid "studio" msgstr "Studio" # Default: Studios msgid "studios" msgstr "Studios" # Default: Stunt performer msgid "stunt-performer" msgstr "Stunt performer" # Default: Stunts msgid "stunts" msgstr "Stunts" # Default: Subtitles msgid "subtitles" msgstr "Subtitles" # Default: Supplement msgid "supplement" msgstr "Supplement" # Default: Supplements msgid "supplements" msgstr "Supplements" # Default: Synopsis msgid "synopsis" msgstr "Synopsis" # Default: Taglines msgid "taglines" msgstr "Taglines" # Default: Tech info msgid "tech-info" msgstr "Tech info" # Default: Thanks msgid "thanks" msgstr "Thanks" # Default: Time msgid "time" msgstr "Time" # Default: Title msgid "title" msgstr "Title" # Default: Titles in this product msgid "titles-in-this-product" msgstr "Titles in this product" # Default: To msgid "to" msgstr "To" # Default: Top 250 rank msgid "top-250-rank" msgstr "Top 250 rank" # Default: Trade mark msgid "trade-mark" msgstr "Trade mark" # Default: Transportation department msgid "transportation-department" msgstr "Transportation department" # Default: Trivia msgid "trivia" msgstr "Trivia" # Default: Under license from msgid "under-license-from" msgstr "Under license from" # Default: Unknown link msgid "unknown-link" msgstr "Unknown link" # Default: Upc msgid "upc" msgstr "Upc" # Default: Version of msgid "version-of" msgstr "Version of" # Default: Vhs msgid "vhs" msgstr "Vhs" # Default: Video artifacts msgid "video-artifacts" msgstr "Video artifacts" # Default: Video clips msgid "video-clips" msgstr "Video clips" # Default: Video noise msgid "video-noise" msgstr "Video noise" # Default: Video quality msgid "video-quality" msgstr "Video quality" # Default: Video standard msgid "video-standard" msgstr "Video standard" # Default: Visual effects msgid "visual-effects" msgstr "Visual effects" # Default: Votes msgid "votes" msgstr "Votes" # Default: Votes distribution msgid "votes-distribution" msgstr "Votes distribution" # Default: Weekend gross msgid "weekend-gross" msgstr "Weekend gross" # Default: Where now msgid "where-now" msgstr "Where now" # Default: With msgid "with" msgstr "With" # Default: Writer msgid "writer" msgstr "Writer" # Default: Written by msgid "written-by" msgstr "Written by" # Default: Year msgid "year" msgstr "Year" # Default: Zshops msgid "zshops" msgstr "Zshops"
21,974
Python
.py
946
21.899577
53
0.808273
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,203
imdbpy-es.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-es.po
# Gettext message file for imdbpy # Translators: # strel, 2013 msgid "" msgstr "" "Project-Id-Version: Cinemagoer\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2016-03-28 20:40+0000\n" "Last-Translator: strel\n" "Language-Team: Spanish (http://www.transifex.com/davide_alberani/imdbpy/language/es/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Domain: imdbpy\n" "Language: es\n" "Language-Code: en\n" "Language-Name: English\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Preferred-Encodings: utf-8\n" # Default: Actor msgid "actor" msgstr "actor" # Default: Actress msgid "actress" msgstr "actriz" # Default: Adaption msgid "adaption" msgstr "adaptación" # Default: Additional information msgid "additional-information" msgstr "información-adicional" # Default: Admissions msgid "admissions" msgstr "facturación" # Default: Agent address msgid "agent-address" msgstr "dirección-del-agente" # Default: Airing msgid "airing" msgstr "estreno-televisivo" # Default: Akas msgid "akas" msgstr "alias" # Default: Akas from release info msgid "akas-from-release-info" msgstr "alias-en-los-datos-de-publicación" # Default: All products msgid "all-products" msgstr "todos-los-productos" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "versión-con-distinto-idioma-de" # Default: Alternate versions msgid "alternate-versions" msgstr "versiones-distintas" # Default: Amazon reviews msgid "amazon-reviews" msgstr "revisiones-de-amazon" # Default: Analog left msgid "analog-left" msgstr "izquierda-analógico" # Default: Analog right msgid "analog-right" msgstr "análogo-derecha" # Default: Animation department msgid "animation-department" msgstr "departamento-de-animación" # Default: Archive footage msgid "archive-footage" msgstr "video-de-archivo" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "media-aritmética" # Default: Art department msgid "art-department" msgstr "departamento-artístico" # Default: Art direction msgid "art-direction" msgstr "dirección-artística" # Default: Art director msgid "art-director" msgstr "director-artístico" # Default: Article msgid "article" msgstr "artículo" # Default: Asin msgid "asin" msgstr "asin" # Default: Aspect ratio msgid "aspect-ratio" msgstr "relación-de-aspecto" # Default: Assigner msgid "assigner" msgstr "director" # Default: Assistant director msgid "assistant-director" msgstr "asistente-de-dirección" # Default: Auctions msgid "auctions" msgstr "subastas" # Default: Audio noise msgid "audio-noise" msgstr "audio-ruido" # Default: Audio quality msgid "audio-quality" msgstr "calidad-del-audio" # Default: Award msgid "award" msgstr "premio" # Default: Awards msgid "awards" msgstr "premios" # Default: Biographical movies msgid "biographical-movies" msgstr "películas-biográficas" # Default: Biography msgid "biography" msgstr "biografía" # Default: Biography print msgid "biography-print" msgstr "biografía-impresa" # Default: Birth date msgid "birth-date" msgstr "fecha-de-nacimiento" # Default: Birth name msgid "birth-name" msgstr "nombre-de-pila" # Default: Birth notes msgid "birth-notes" msgstr "notas-de-nacimiento" # Default: Body msgid "body" msgstr "cuerpo" # Default: Book msgid "book" msgstr "libro" # Default: Books msgid "books" msgstr "libros" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "ranking-de-los-últimos-100" # Default: Budget msgid "budget" msgstr "presupuesto" # Default: Business msgid "business" msgstr "negocio" # Default: By arrangement with msgid "by-arrangement-with" msgstr "por-acuerdo-con" # Default: Camera msgid "camera" msgstr "cámara" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "departamento-de-cámara-y-eléctrico" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "título-canónico-de-episodio" # Default: Canonical name msgid "canonical-name" msgstr "nombre-canónico" # Default: Canonical series title msgid "canonical-series-title" msgstr "título-canónico-de-serie" # Default: Canonical title msgid "canonical-title" msgstr "título-canónico" # Default: Cast msgid "cast" msgstr "selección" # Default: Casting department msgid "casting-department" msgstr "departamento-de-selección" # Default: Casting director msgid "casting-director" msgstr "director-de-selección" # Default: Catalog number msgid "catalog-number" msgstr "número-de-catálogo" # Default: Category msgid "category" msgstr "categoría" # Default: Certificate msgid "certificate" msgstr "certificado" # Default: Certificates msgid "certificates" msgstr "certificados" # Default: Certification msgid "certification" msgstr "certificación" # Default: Channel msgid "channel" msgstr "canal" # Default: Character msgid "character" msgstr "personaje" # Default: Cinematographer msgid "cinematographer" msgstr "técnico-de-cámara" # Default: Cinematographic process msgid "cinematographic-process" msgstr "proceso-de-rodaje" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "cerrar-subtítulos-teletexto-ld-g" # Default: Color info msgid "color-info" msgstr "info-de-color" # Default: Color information msgid "color-information" msgstr "información-de-color" # Default: Color rendition msgid "color-rendition" msgstr "fidelidad-de-color" # Default: Company msgid "company" msgstr "compañía" # Default: Complete cast msgid "complete-cast" msgstr "selección-completa" # Default: Complete crew msgid "complete-crew" msgstr "equipo-completo" # Default: Composer msgid "composer" msgstr "compositor" # Default: Connections msgid "connections" msgstr "conexiones" # Default: Contrast msgid "contrast" msgstr "contraste" # Default: Copyright holder msgid "copyright-holder" msgstr "tenerdor-del-copyright" # Default: Costume department msgid "costume-department" msgstr "departamento-de-vestuario" # Default: Costume designer msgid "costume-designer" msgstr "diseñador-de-vestuario" # Default: Countries msgid "countries" msgstr "países" # Default: Country msgid "country" msgstr "país" # Default: Courtesy of msgid "courtesy-of" msgstr "cortesía-de" # Default: Cover msgid "cover" msgstr "cubierta" # Default: Cover url msgid "cover-url" msgstr "url-de-la-cubierta" # Default: Crazy credits msgid "crazy-credits" msgstr "créditos-locos" # Default: Creator msgid "creator" msgstr "creador" # Default: Current role msgid "current-role" msgstr "papel-actual" # Default: Database msgid "database" msgstr "base-de-datos" # Default: Date msgid "date" msgstr "fecha" # Default: Death date msgid "death-date" msgstr "fecha-de-fallecimiento" # Default: Death notes msgid "death-notes" msgstr "notas-de-fallecimiento" # Default: Demographic msgid "demographic" msgstr "demografía" # Default: Description msgid "description" msgstr "descripción" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "diálogo-inteligible" # Default: Digital sound msgid "digital-sound" msgstr "sonido-digital" # Default: Director msgid "director" msgstr "director" # Default: Disc format msgid "disc-format" msgstr "formato-de-disco" # Default: Disc size msgid "disc-size" msgstr "tamaño-de-disco" # Default: Distributors msgid "distributors" msgstr "distribuidor" # Default: Dvd msgid "dvd" msgstr "dvd" # Default: Dvd features msgid "dvd-features" msgstr "características-de-dvd" # Default: Dvd format msgid "dvd-format" msgstr "formato-de-dvd" # Default: Dvds msgid "dvds" msgstr "dvds" # Default: Dynamic range msgid "dynamic-range" msgstr "rango-dinámico" # Default: Edited from msgid "edited-from" msgstr "editado-desde" # Default: Edited into msgid "edited-into" msgstr "editado-a" # Default: Editor msgid "editor" msgstr "editor" # Default: Editorial department msgid "editorial-department" msgstr "departamento-editorial" # Default: Episode msgid "episode" msgstr "episodio" # Default: Episode of msgid "episode-of" msgstr "episodio-de" # Default: Episode title msgid "episode-title" msgstr "título-del-episodio" # Default: Episodes msgid "episodes" msgstr "episodios" # Default: Episodes rating msgid "episodes-rating" msgstr "valoración-de-episodios" # Default: Essays msgid "essays" msgstr "ensayos" # Default: External reviews msgid "external-reviews" msgstr "reseñas-externas" # Default: Faqs msgid "faqs" msgstr "faqs-(preguntas-frecuentes)" # Default: Feature msgid "feature" msgstr "aparición" # Default: Featured in msgid "featured-in" msgstr "aparecido-en" # Default: Features msgid "features" msgstr "apariciones" # Default: Film negative format msgid "film-negative-format" msgstr "formato-de-negativo-de-película" # Default: Filming dates msgid "filming-dates" msgstr "fechas-de-filmación" # Default: Filmography msgid "filmography" msgstr "filmografía" # Default: Followed by msgid "followed-by" msgstr "seguido-por" # Default: Follows msgid "follows" msgstr "sigue-a" # Default: For msgid "for" msgstr "para" # Default: Frequency response msgid "frequency-response" msgstr "respuesta-de-frecuencia" # Default: From msgid "from" msgstr "desde" # Default: Full article link msgid "full-article-link" msgstr "enlace-al-artículo-completo" # Default: Full size cover url msgid "full-size-cover-url" msgstr "url-a-la-caratula-de-tamaño-completo" # Default: Full size headshot msgid "full-size-headshot" msgstr "retrato-de-tamaño-completo" # Default: Genres msgid "genres" msgstr "géneros" # Default: Goofs msgid "goofs" msgstr "gazapos" # Default: Gross msgid "gross" msgstr "recaudación-bruta" # Default: Group genre msgid "group-genre" msgstr "género-del-grupo" # Default: Headshot msgid "headshot" msgstr "retrato" # Default: Height msgid "height" msgstr "altura" # Default: Imdbindex msgid "imdbindex" msgstr "íncide-imdb" # Default: In development msgid "in-development" msgstr "en-desarrollo" # Default: Interview msgid "interview" msgstr "entrevista" # Default: Interviews msgid "interviews" msgstr "entrevistas" # Default: Introduction msgid "introduction" msgstr "introducción" # Default: Item msgid "item" msgstr "elemento" # Default: Keywords msgid "keywords" msgstr "contraseñas" # Default: Kind msgid "kind" msgstr "clase" # Default: Label msgid "label" msgstr "etiqueta" # Default: Laboratory msgid "laboratory" msgstr "laboratorio" # Default: Language msgid "language" msgstr "idioma" # Default: Languages msgid "languages" msgstr "idiomas" # Default: Laserdisc msgid "laserdisc" msgstr "laserdisc" # Default: Laserdisc title msgid "laserdisc-title" msgstr "título-del-laserdisc" # Default: Length msgid "length" msgstr "duración" # Default: Line msgid "line" msgstr "línea" # Default: Link msgid "link" msgstr "enlace" # Default: Link text msgid "link-text" msgstr "texto-del-enlace" # Default: Literature msgid "literature" msgstr "escritos" # Default: Locations msgid "locations" msgstr "localizaciones" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "nombre-canónico-largo-de-imdb" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "título-canónico-largo-de-imdb" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "título-largo-de-episodio-de-imdb" # Default: Long imdb name msgid "long-imdb-name" msgstr "nombre-largo-de-imdb" # Default: Long imdb title msgid "long-imdb-title" msgstr "título-largo-de-imdb" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "foto-de-cubierta-de-magazine" # Default: Make up msgid "make-up" msgstr "maquillaje" # Default: Master format msgid "master-format" msgstr "formato-maestro" # Default: Median msgid "median" msgstr "mediana" # Default: Merchandising links msgid "merchandising-links" msgstr "enlaces-de-merchandising" # Default: Mini biography msgid "mini-biography" msgstr "mini-biografía" # Default: Misc links msgid "misc-links" msgstr "enlaces-varios" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "compañías-varias" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "personal-vario" # Default: Movie msgid "movie" msgstr "película" # Default: Mpaa msgid "mpaa" msgstr "mpaa" # Default: Music department msgid "music-department" msgstr "departamento-musical" # Default: Name msgid "name" msgstr "nombre" # Default: News msgid "news" msgstr "noticias" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "reseñas-de-grupos-de-noticias" # Default: Nick names msgid "nick-names" msgstr "apodos" # Default: Notes msgid "notes" msgstr "notas" # Default: Novel msgid "novel" msgstr "novela" # Default: Number msgid "number" msgstr "número" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "número-de-pausas-del-capítulo" # Default: Number of episodes msgid "number-of-episodes" msgstr "número-de-episodios" # Default: Number of seasons msgid "number-of-seasons" msgstr "número-de-temporadas" # Default: Number of sides msgid "number-of-sides" msgstr "número-de-caras" # Default: Number of votes msgid "number-of-votes" msgstr "número-de-votos" # Default: Official retail price msgid "official-retail-price" msgstr "precio-minorista-oficial" # Default: Official sites msgid "official-sites" msgstr "sitios-oficiales" # Default: Opening weekend msgid "opening-weekend" msgstr "fin-de-semana-inaugural" # Default: Original air date msgid "original-air-date" msgstr "fecha-de-emisión-original" # Default: Original music msgid "original-music" msgstr "música-original" # Default: Original title msgid "original-title" msgstr "título-original" # Default: Other literature msgid "other-literature" msgstr "otros-escritos" # Default: Other works msgid "other-works" msgstr "otros-trabajos" # Default: Parents guide msgid "parents-guide" msgstr "guía-parental" # Default: Performed by msgid "performed-by" msgstr "interpretado-por" # Default: Person msgid "person" msgstr "persona" # Default: Photo sites msgid "photo-sites" msgstr "lugares-fotografiados" # Default: Pictorial msgid "pictorial" msgstr "reportaje-fotográfico" # Default: Picture format msgid "picture-format" msgstr "formato-de-fotografía" # Default: Plot msgid "plot" msgstr "trama" # Default: Plot outline msgid "plot-outline" msgstr "resumen-de-la-trama" # Default: Portrayed in msgid "portrayed-in" msgstr "representado-en" # Default: Pressing plant msgid "pressing-plant" msgstr "fábrica-de-copias" # Default: Printed film format msgid "printed-film-format" msgstr "formato-de-película-impresa" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "reseñas-en-medios-escritos" # Default: Producer msgid "producer" msgstr "productor" # Default: Production companies msgid "production-companies" msgstr "compañías-de-la-producción" # Default: Production country msgid "production-country" msgstr "país-de-la-producción" # Default: Production dates msgid "production-dates" msgstr "fechas-de-producción" # Default: Production design msgid "production-design" msgstr "diseño-de-producción" # Default: Production designer msgid "production-designer" msgstr "diseñador-de-producción" # Default: Production manager msgid "production-manager" msgstr "director-de-producción" # Default: Production process protocol msgid "production-process-protocol" msgstr "protocolo-de-proceso-de-producción" # Default: Quality of source msgid "quality-of-source" msgstr "calidad-del-original" # Default: Quality program msgid "quality-program" msgstr "programa-de-calidad" # Default: Quote msgid "quote" msgstr "cita" # Default: Quotes msgid "quotes" msgstr "citas" # Default: Rating msgid "rating" msgstr "valoración" # Default: Recommendations msgid "recommendations" msgstr "recomendaciones" # Default: Referenced in msgid "referenced-in" msgstr "referenciado-en" # Default: References msgid "references" msgstr "referencias" # Default: Region msgid "region" msgstr "región" # Default: Release country msgid "release-country" msgstr "país-de-estreno" # Default: Release date msgid "release-date" msgstr "fecha-de-estreno" # Default: Release dates msgid "release-dates" msgstr "fechas-de-estreno" # Default: Remade as msgid "remade-as" msgstr "reversionado-como" # Default: Remake of msgid "remake-of" msgstr "refrito-de" # Default: Rentals msgid "rentals" msgstr "recaudación-por-alquileres" # Default: Result msgid "result" msgstr "resultado" # Default: Review msgid "review" msgstr "reseña" # Default: Review author msgid "review-author" msgstr "autor-de-la-reseña" # Default: Review kind msgid "review-kind" msgstr "tipo-de-reseña" # Default: Runtime msgid "runtime" msgstr "duración" # Default: Runtimes msgid "runtimes" msgstr "duraciones" # Default: Salary history msgid "salary-history" msgstr "historial-salarial" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "guiones-cinematrográfico-y-televisivo" # Default: Season msgid "season" msgstr "temporada" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "segundo-director-de-unidad-o-asistente-de-dirección" # Default: Self msgid "self" msgstr "auto" # Default: Series animation department msgid "series-animation-department" msgstr "departamento-de-animación-de-la-serie" # Default: Series art department msgid "series-art-department" msgstr "departamento-artístico-de-la-serie" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "asistentes-de-dirección-de-la-serie" # Default: Series camera department msgid "series-camera-department" msgstr "departamento-de-cámaras-de-la-serie" # Default: Series casting department msgid "series-casting-department" msgstr "departamento-de-selección-de-la-serie" # Default: Series cinematographers msgid "series-cinematographers" msgstr "técnicos-de-cámara-de-la-serie" # Default: Series costume department msgid "series-costume-department" msgstr "departamento-de-vestuario-de-la-serie" # Default: Series editorial department msgid "series-editorial-department" msgstr "departamento-editorial-de-la-serie" # Default: Series editors msgid "series-editors" msgstr "editores-de-la-serie" # Default: Series make up department msgid "series-make-up-department" msgstr "departamento-de-maquillaje-de-la-serie" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "series-varias" # Default: Series music department msgid "series-music-department" msgstr "departamento-musical-de-la-serie" # Default: Series producers msgid "series-producers" msgstr "productores-de-la-serie" # Default: Series production designers msgid "series-production-designers" msgstr "diseñadores-de-producción-de-la-serie" # Default: Series production managers msgid "series-production-managers" msgstr "directores-de-producción-de-la-serie" # Default: Series sound department msgid "series-sound-department" msgstr "departamento-de-sonido-de-la-serie" # Default: Series special effects department msgid "series-special-effects-department" msgstr "departamento-de-efectos-especiales-de-la-serie" # Default: Series stunts msgid "series-stunts" msgstr "acrobacias-de-la-serie" # Default: Series title msgid "series-title" msgstr "título" # Default: Series transportation department msgid "series-transportation-department" msgstr "departamento-de-transporte-de-la-serie" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "departamento-de-efectos-visuales-de-la-serie" # Default: Series writers msgid "series-writers" msgstr "guionistas-de-la-serie" # Default: Series years msgid "series-years" msgstr "años-de-la-serie" # Default: Set decoration msgid "set-decoration" msgstr "decoración-del-set" # Default: Sharpness msgid "sharpness" msgstr "agudeza" # Default: Similar to msgid "similar-to" msgstr "similar-a" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "título-canónico-inteligente-del-episodio" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "título-canónico-inteligente-de-la-serie" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "título-canónico-inteligente" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "título-canónico-inteligente-largo-de-imdb" # Default: Sound clips msgid "sound-clips" msgstr "audio-clips" # Default: Sound crew msgid "sound-crew" msgstr "equipo-de-audio" # Default: Sound encoding msgid "sound-encoding" msgstr "compresión-de-audio" # Default: Sound mix msgid "sound-mix" msgstr "mezcla-de-audio" # Default: Soundtrack msgid "soundtrack" msgstr "banda-sonora" # Default: Spaciality msgid "spaciality" msgstr "espacialidad" # Default: Special effects msgid "special-effects" msgstr "efectos-especiales" # Default: Special effects companies msgid "special-effects-companies" msgstr "compañías-de-efectos-especiales" # Default: Special effects department msgid "special-effects-department" msgstr "departamento-de-efectos-especiales" # Default: Spin off msgid "spin-off" msgstr "secuela" # Default: Spin off from msgid "spin-off-from" msgstr "secuela-de" # Default: Spoofed in msgid "spoofed-in" msgstr "paradiado-en" # Default: Spoofs msgid "spoofs" msgstr "parodias" # Default: Spouse msgid "spouse" msgstr "esposa" # Default: Status of availablility msgid "status-of-availablility" msgstr "estado-de-disponibilidad" # Default: Studio msgid "studio" msgstr "estudio" # Default: Studios msgid "studios" msgstr "estudios" # Default: Stunt performer msgid "stunt-performer" msgstr "especialista-de-acrobacias" # Default: Stunts msgid "stunts" msgstr "acrobacias" # Default: Subtitles msgid "subtitles" msgstr "subtítulos" # Default: Supplement msgid "supplement" msgstr "suplemento" # Default: Supplements msgid "supplements" msgstr "suplementos" # Default: Synopsis msgid "synopsis" msgstr "sinopsis" # Default: Taglines msgid "taglines" msgstr "eslogan" # Default: Tech info msgid "tech-info" msgstr "información-técnica" # Default: Thanks msgid "thanks" msgstr "gracias" # Default: Time msgid "time" msgstr "hora" # Default: Title msgid "title" msgstr "título" # Default: Titles in this product msgid "titles-in-this-product" msgstr "títulos-en-este-producto" # Default: To msgid "to" msgstr "a" # Default: Top 250 rank msgid "top-250-rank" msgstr "primeros-250-de-la-clasificación" # Default: Trade mark msgid "trade-mark" msgstr "marca-registrada" # Default: Transportation department msgid "transportation-department" msgstr "departamento-de-transporte" # Default: Trivia msgid "trivia" msgstr "curiosidades" # Default: Tv msgid "tv" msgstr "tv" # Default: Under license from msgid "under-license-from" msgstr "bajo-licencia-de" # Default: Unknown link msgid "unknown-link" msgstr "enlace-desconocido" # Default: Upc msgid "upc" msgstr "upc" # Default: Version of msgid "version-of" msgstr "versión-de" # Default: Vhs msgid "vhs" msgstr "vhs" # Default: Video msgid "video" msgstr "vídeo" # Default: Video artifacts msgid "video-artifacts" msgstr "efectos-de-vídeo" # Default: Video clips msgid "video-clips" msgstr "vídeo-clips" # Default: Video noise msgid "video-noise" msgstr "vídeo-ruido" # Default: Video quality msgid "video-quality" msgstr "calidad-de-vídeo" # Default: Video standard msgid "video-standard" msgstr "estandar-de-vídeo" # Default: Visual effects msgid "visual-effects" msgstr "efectos-visuales" # Default: Votes msgid "votes" msgstr "votos" # Default: Votes distribution msgid "votes-distribution" msgstr "distribución-de-votos" # Default: Weekend gross msgid "weekend-gross" msgstr "recaudación-bruta-del-fin-de-semana" # Default: Where now msgid "where-now" msgstr "dónde-está-ahora" # Default: With msgid "with" msgstr "con" # Default: Writer msgid "writer" msgstr "escritor" # Default: Written by msgid "written-by" msgstr "escrito-por" # Default: Year msgid "year" msgstr "año" # Default: Zshops msgid "zshops" msgstr "amazon-zshops"
24,257
Python
.py
982
23.205703
89
0.809066
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,204
imdbpy-bg.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-bg.po
# Gettext message file for imdbpy # Translators: # Атанас Ковачки <[email protected]>, 2014 msgid "" msgstr "" "Project-Id-Version: Cinemagoer\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2018-12-29 20:34+0000\n" "Last-Translator: Атанас Ковачки <[email protected]>\n" "Language-Team: Bulgarian (http://www.transifex.com/davide_alberani/imdbpy/language/bg/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Domain: imdbpy\n" "Language: bg\n" "Language-Code: en\n" "Language-Name: English\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Preferred-Encodings: utf-8\n" # Default: Actor msgid "actor" msgstr "актьор" # Default: Actress msgid "actress" msgstr "актриса" # Default: Adaption msgid "adaption" msgstr "адаптация" # Default: Additional information msgid "additional-information" msgstr "допълнителна информация" # Default: Admissions msgid "admissions" msgstr "" # Default: Agent address msgid "agent-address" msgstr "" # Default: Airing msgid "airing" msgstr "" # Default: Akas msgid "akas" msgstr "" # Default: Akas from release info msgid "akas-from-release-info" msgstr "" # Default: All products msgid "all-products" msgstr "всички продукти" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "" # Default: Alternate versions msgid "alternate-versions" msgstr "" # Default: Amazon reviews msgid "amazon-reviews" msgstr "" # Default: Analog left msgid "analog-left" msgstr "" # Default: Analog right msgid "analog-right" msgstr "" # Default: Animation department msgid "animation-department" msgstr "" # Default: Archive footage msgid "archive-footage" msgstr "" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "" # Default: Art department msgid "art-department" msgstr "" # Default: Art direction msgid "art-direction" msgstr "" # Default: Art director msgid "art-director" msgstr "арт директор" # Default: Article msgid "article" msgstr "" # Default: Asin msgid "asin" msgstr "" # Default: Aspect ratio msgid "aspect-ratio" msgstr "" # Default: Assigner msgid "assigner" msgstr "" # Default: Assistant director msgid "assistant-director" msgstr "" # Default: Auctions msgid "auctions" msgstr "" # Default: Audio noise msgid "audio-noise" msgstr "" # Default: Audio quality msgid "audio-quality" msgstr "" # Default: Award msgid "award" msgstr "награда" # Default: Awards msgid "awards" msgstr "награди" # Default: Biographical movies msgid "biographical-movies" msgstr "" # Default: Biography msgid "biography" msgstr "биография" # Default: Biography print msgid "biography-print" msgstr "" # Default: Birth date msgid "birth-date" msgstr "рождена дата" # Default: Birth name msgid "birth-name" msgstr "" # Default: Birth notes msgid "birth-notes" msgstr "" # Default: Body msgid "body" msgstr "" # Default: Book msgid "book" msgstr "книга" # Default: Books msgid "books" msgstr "книги" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "" # Default: Budget msgid "budget" msgstr "бюджет" # Default: Business msgid "business" msgstr "" # Default: By arrangement with msgid "by-arrangement-with" msgstr "" # Default: Camera msgid "camera" msgstr "камера" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "" # Default: Canonical name msgid "canonical-name" msgstr "" # Default: Canonical series title msgid "canonical-series-title" msgstr "" # Default: Canonical title msgid "canonical-title" msgstr "" # Default: Cast msgid "cast" msgstr "" # Default: Casting department msgid "casting-department" msgstr "" # Default: Casting director msgid "casting-director" msgstr "кастинг директор" # Default: Catalog number msgid "catalog-number" msgstr "" # Default: Category msgid "category" msgstr "категория" # Default: Certificate msgid "certificate" msgstr "сертификат" # Default: Certificates msgid "certificates" msgstr "сертификати" # Default: Certification msgid "certification" msgstr "сертифициране" # Default: Channel msgid "channel" msgstr "канал" # Default: Character msgid "character" msgstr "характер" # Default: Cinematographer msgid "cinematographer" msgstr "кинематограф" # Default: Cinematographic process msgid "cinematographic-process" msgstr "" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "" # Default: Color information msgid "color-information" msgstr "" # Default: Color rendition msgid "color-rendition" msgstr "" # Default: Company msgid "company" msgstr "компания" # Default: Complete cast msgid "complete-cast" msgstr "" # Default: Complete crew msgid "complete-crew" msgstr "" # Default: Composer msgid "composer" msgstr "композитор" # Default: Connections msgid "connections" msgstr "връзки" # Default: Contrast msgid "contrast" msgstr "контраст" # Default: Copyright holder msgid "copyright-holder" msgstr "" # Default: Costume department msgid "costume-department" msgstr "" # Default: Costume designer msgid "costume-designer" msgstr "" # Default: Countries msgid "countries" msgstr "страни" # Default: Country msgid "country" msgstr "страна" # Default: Courtesy of msgid "courtesy-of" msgstr "" # Default: Cover msgid "cover" msgstr "" # Default: Cover url msgid "cover-url" msgstr "" # Default: Crazy credits msgid "crazy-credits" msgstr "" # Default: Creator msgid "creator" msgstr "създател" # Default: Current role msgid "current-role" msgstr "" # Default: Database msgid "database" msgstr "база данни" # Default: Date msgid "date" msgstr "дата" # Default: Death date msgid "death-date" msgstr "дата на смъртта" # Default: Death notes msgid "death-notes" msgstr "" # Default: Demographic msgid "demographic" msgstr "" # Default: Description msgid "description" msgstr "описание" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "" # Default: Digital sound msgid "digital-sound" msgstr "" # Default: Director msgid "director" msgstr "директор" # Default: Disc format msgid "disc-format" msgstr "формат на диска" # Default: Disc size msgid "disc-size" msgstr "размер на диска" # Default: Distributors msgid "distributors" msgstr "дистрибутори" # Default: Dvd msgid "dvd" msgstr "dvd" # Default: Dvd features msgid "dvd-features" msgstr "dvd характеристики" # Default: Dvd format msgid "dvd-format" msgstr "dvd формат" # Default: Dvds msgid "dvds" msgstr "dvd-та" # Default: Dynamic range msgid "dynamic-range" msgstr "динамичен обхват" # Default: Edited from msgid "edited-from" msgstr "" # Default: Edited into msgid "edited-into" msgstr "" # Default: Editor msgid "editor" msgstr "редактор" # Default: Editorial department msgid "editorial-department" msgstr "" # Default: Episode msgid "episode" msgstr "епизод" # Default: Episode of msgid "episode-of" msgstr "епизод от" # Default: Episode title msgid "episode-title" msgstr "име на епизода" # Default: Episodes msgid "episodes" msgstr "епизоди" # Default: Episodes rating msgid "episodes-rating" msgstr "рейтинг на епизодите" # Default: Essays msgid "essays" msgstr "" # Default: External reviews msgid "external-reviews" msgstr "външни рецензии" # Default: Faqs msgid "faqs" msgstr "" # Default: Feature msgid "feature" msgstr "" # Default: Featured in msgid "featured-in" msgstr "" # Default: Features msgid "features" msgstr "" # Default: Film negative format msgid "film-negative-format" msgstr "" # Default: Filming dates msgid "filming-dates" msgstr "" # Default: Filmography msgid "filmography" msgstr "филмография" # Default: Followed by msgid "followed-by" msgstr "последван от" # Default: Follows msgid "follows" msgstr "последователи" # Default: For msgid "for" msgstr "" # Default: Frequency response msgid "frequency-response" msgstr "" # Default: From msgid "from" msgstr "" # Default: Full article link msgid "full-article-link" msgstr "" # Default: Full size cover url msgid "full-size-cover-url" msgstr "" # Default: Full size headshot msgid "full-size-headshot" msgstr "" # Default: Genres msgid "genres" msgstr "жанрове" # Default: Goofs msgid "goofs" msgstr "" # Default: Gross msgid "gross" msgstr "" # Default: Group genre msgid "group-genre" msgstr "" # Default: Headshot msgid "headshot" msgstr "" # Default: Height msgid "height" msgstr "" # Default: Imdbindex msgid "imdbindex" msgstr "imdb индекс" # Default: In development msgid "in-development" msgstr "" # Default: Interview msgid "interview" msgstr "интервю" # Default: Interviews msgid "interviews" msgstr "интервюта" # Default: Introduction msgid "introduction" msgstr "въведение" # Default: Item msgid "item" msgstr "елемент" # Default: Keywords msgid "keywords" msgstr "ключови думи" # Default: Kind msgid "kind" msgstr "" # Default: Label msgid "label" msgstr "етикет" # Default: Laboratory msgid "laboratory" msgstr "лаборатория" # Default: Language msgid "language" msgstr "език" # Default: Languages msgid "languages" msgstr "езици" # Default: Laserdisc msgid "laserdisc" msgstr "лазерен диск" # Default: Laserdisc title msgid "laserdisc-title" msgstr "име на лазерения диск" # Default: Length msgid "length" msgstr "продължителност" # Default: Line msgid "line" msgstr "" # Default: Link msgid "link" msgstr "връзка" # Default: Link text msgid "link-text" msgstr "текст за връзката" # Default: Literature msgid "literature" msgstr "литература" # Default: Locations msgid "locations" msgstr "местоположения" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "" # Default: Long imdb name msgid "long-imdb-name" msgstr "" # Default: Long imdb title msgid "long-imdb-title" msgstr "" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "" # Default: Make up msgid "make-up" msgstr "" # Default: Master format msgid "master-format" msgstr "" # Default: Median msgid "median" msgstr "" # Default: Merchandising links msgid "merchandising-links" msgstr "" # Default: Mini biography msgid "mini-biography" msgstr "" # Default: Misc links msgid "misc-links" msgstr "" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "" # Default: Movie msgid "movie" msgstr "филм" # Default: Mpaa msgid "mpaa" msgstr "mpaa" # Default: Music department msgid "music-department" msgstr "музикален департамент" # Default: Name msgid "name" msgstr "име" # Default: News msgid "news" msgstr "новини" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "" # Default: Nick names msgid "nick-names" msgstr "" # Default: Notes msgid "notes" msgstr "бележки" # Default: Novel msgid "novel" msgstr "роман" # Default: Number msgid "number" msgstr "номер" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "" # Default: Number of episodes msgid "number-of-episodes" msgstr "" # Default: Number of seasons msgid "number-of-seasons" msgstr "" # Default: Number of sides msgid "number-of-sides" msgstr "" # Default: Number of votes msgid "number-of-votes" msgstr "" # Default: Official retail price msgid "official-retail-price" msgstr "" # Default: Official sites msgid "official-sites" msgstr "официалени сайтове" # Default: Opening weekend msgid "opening-weekend" msgstr "" # Default: Original air date msgid "original-air-date" msgstr "" # Default: Original music msgid "original-music" msgstr "" # Default: Original title msgid "original-title" msgstr "" # Default: Other literature msgid "other-literature" msgstr "" # Default: Other works msgid "other-works" msgstr "" # Default: Parents guide msgid "parents-guide" msgstr "" # Default: Performed by msgid "performed-by" msgstr "" # Default: Person msgid "person" msgstr "персона" # Default: Photo sites msgid "photo-sites" msgstr "" # Default: Pictorial msgid "pictorial" msgstr "" # Default: Picture format msgid "picture-format" msgstr "" # Default: Plot msgid "plot" msgstr "" # Default: Plot outline msgid "plot-outline" msgstr "" # Default: Portrayed in msgid "portrayed-in" msgstr "" # Default: Pressing plant msgid "pressing-plant" msgstr "" # Default: Printed film format msgid "printed-film-format" msgstr "" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "" # Default: Producer msgid "producer" msgstr "продуцент" # Default: Production companies msgid "production-companies" msgstr "производствени компании" # Default: Production country msgid "production-country" msgstr "производствена страна" # Default: Production dates msgid "production-dates" msgstr "" # Default: Production design msgid "production-design" msgstr "" # Default: Production designer msgid "production-designer" msgstr "" # Default: Production manager msgid "production-manager" msgstr "" # Default: Production process protocol msgid "production-process-protocol" msgstr "" # Default: Quality of source msgid "quality-of-source" msgstr "" # Default: Quality program msgid "quality-program" msgstr "" # Default: Quote msgid "quote" msgstr "цитат" # Default: Quotes msgid "quotes" msgstr "цитати" # Default: Rating msgid "rating" msgstr "рейтинг" # Default: Recommendations msgid "recommendations" msgstr "препоръки" # Default: Referenced in msgid "referenced-in" msgstr "" # Default: References msgid "references" msgstr "референции" # Default: Region msgid "region" msgstr "регион" # Default: Release country msgid "release-country" msgstr "" # Default: Release date msgid "release-date" msgstr "" # Default: Release dates msgid "release-dates" msgstr "" # Default: Remade as msgid "remade-as" msgstr "" # Default: Remake of msgid "remake-of" msgstr "" # Default: Rentals msgid "rentals" msgstr "" # Default: Result msgid "result" msgstr "резултат" # Default: Review msgid "review" msgstr "рецензия" # Default: Review author msgid "review-author" msgstr "автор на рецензията" # Default: Review kind msgid "review-kind" msgstr "" # Default: Runtime msgid "runtime" msgstr "времетраене" # Default: Runtimes msgid "runtimes" msgstr "" # Default: Salary history msgid "salary-history" msgstr "" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "" # Default: Season msgid "season" msgstr "сезон" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "" # Default: Self msgid "self" msgstr "" # Default: Series animation department msgid "series-animation-department" msgstr "" # Default: Series art department msgid "series-art-department" msgstr "" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "" # Default: Series camera department msgid "series-camera-department" msgstr "" # Default: Series casting department msgid "series-casting-department" msgstr "" # Default: Series cinematographers msgid "series-cinematographers" msgstr "" # Default: Series costume department msgid "series-costume-department" msgstr "" # Default: Series editorial department msgid "series-editorial-department" msgstr "" # Default: Series editors msgid "series-editors" msgstr "" # Default: Series make up department msgid "series-make-up-department" msgstr "" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "" # Default: Series music department msgid "series-music-department" msgstr "" # Default: Series producers msgid "series-producers" msgstr "" # Default: Series production designers msgid "series-production-designers" msgstr "" # Default: Series production managers msgid "series-production-managers" msgstr "" # Default: Series sound department msgid "series-sound-department" msgstr "" # Default: Series special effects department msgid "series-special-effects-department" msgstr "" # Default: Series stunts msgid "series-stunts" msgstr "" # Default: Series title msgid "series-title" msgstr "име на серията" # Default: Series transportation department msgid "series-transportation-department" msgstr "" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "" # Default: Series writers msgid "series-writers" msgstr "" # Default: Series years msgid "series-years" msgstr "" # Default: Set decoration msgid "set-decoration" msgstr "" # Default: Sharpness msgid "sharpness" msgstr "" # Default: Similar to msgid "similar-to" msgstr "" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "" # Default: Sound clips msgid "sound-clips" msgstr "" # Default: Sound crew msgid "sound-crew" msgstr "" # Default: Sound encoding msgid "sound-encoding" msgstr "" # Default: Sound mix msgid "sound-mix" msgstr "" # Default: Soundtrack msgid "soundtrack" msgstr "саундтрак" # Default: Spaciality msgid "spaciality" msgstr "" # Default: Special effects msgid "special-effects" msgstr "специални ефекти" # Default: Special effects companies msgid "special-effects-companies" msgstr "" # Default: Special effects department msgid "special-effects-department" msgstr "" # Default: Spin off msgid "spin-off" msgstr "" # Default: Spin off from msgid "spin-off-from" msgstr "" # Default: Spoofed in msgid "spoofed-in" msgstr "" # Default: Spoofs msgid "spoofs" msgstr "" # Default: Spouse msgid "spouse" msgstr "" # Default: Status of availablility msgid "status-of-availablility" msgstr "" # Default: Studio msgid "studio" msgstr "студио" # Default: Studios msgid "studios" msgstr "студиа" # Default: Stunt performer msgid "stunt-performer" msgstr "" # Default: Stunts msgid "stunts" msgstr "" # Default: Subtitles msgid "subtitles" msgstr "субтитри" # Default: Supplement msgid "supplement" msgstr "допълнение" # Default: Supplements msgid "supplements" msgstr "допълнения" # Default: Synopsis msgid "synopsis" msgstr "синопсис" # Default: Taglines msgid "taglines" msgstr "подзаглавия" # Default: Tech info msgid "tech-info" msgstr "" # Default: Thanks msgid "thanks" msgstr "" # Default: Time msgid "time" msgstr "време" # Default: Title msgid "title" msgstr "име" # Default: Titles in this product msgid "titles-in-this-product" msgstr "" # Default: To msgid "to" msgstr "" # Default: Top 250 rank msgid "top-250-rank" msgstr "" # Default: Trade mark msgid "trade-mark" msgstr "търговска марка" # Default: Transportation department msgid "transportation-department" msgstr "" # Default: Trivia msgid "trivia" msgstr "любопитно" # Default: Tv msgid "tv" msgstr "тв" # Default: Under license from msgid "under-license-from" msgstr "" # Default: Unknown link msgid "unknown-link" msgstr "" # Default: Upc msgid "upc" msgstr "" # Default: Version of msgid "version-of" msgstr "" # Default: Vhs msgid "vhs" msgstr "" # Default: Video msgid "video" msgstr "видео" # Default: Video artifacts msgid "video-artifacts" msgstr "" # Default: Video clips msgid "video-clips" msgstr "" # Default: Video noise msgid "video-noise" msgstr "" # Default: Video quality msgid "video-quality" msgstr "" # Default: Video standard msgid "video-standard" msgstr "" # Default: Visual effects msgid "visual-effects" msgstr "" # Default: Votes msgid "votes" msgstr "гласа" # Default: Votes distribution msgid "votes-distribution" msgstr "" # Default: Weekend gross msgid "weekend-gross" msgstr "" # Default: Where now msgid "where-now" msgstr "" # Default: With msgid "with" msgstr "" # Default: Writer msgid "writer" msgstr "сценарист" # Default: Written by msgid "written-by" msgstr "" # Default: Year msgid "year" msgstr "година" # Default: Zshops msgid "zshops" msgstr ""
21,161
Python
.py
982
19.150713
91
0.789961
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,205
imdbpy-ar.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-ar.po
# Gettext message file for imdbpy # Translators: # Rajaa Jalil <[email protected]>, 2013 msgid "" msgstr "" "Project-Id-Version: Cinemagoer\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2016-03-28 20:40+0000\n" "Last-Translator: Rajaa Jalil <[email protected]>\n" "Language-Team: Arabic (http://www.transifex.com/davide_alberani/imdbpy/language/ar/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Domain: imdbpy\n" "Language: ar\n" "Language-Code: en\n" "Language-Name: English\n" "Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;\n" "Preferred-Encodings: utf-8\n" # Default: Actor msgid "actor" msgstr "ممثل" # Default: Actress msgid "actress" msgstr "ممثلة" # Default: Adaption msgid "adaption" msgstr "إقتباس" # Default: Additional information msgid "additional-information" msgstr "معلومات إضافية" # Default: Admissions msgid "admissions" msgstr "" # Default: Agent address msgid "agent-address" msgstr "" # Default: Airing msgid "airing" msgstr "" # Default: Akas msgid "akas" msgstr "" # Default: Akas from release info msgid "akas-from-release-info" msgstr "" # Default: All products msgid "all-products" msgstr "" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "" # Default: Alternate versions msgid "alternate-versions" msgstr "" # Default: Amazon reviews msgid "amazon-reviews" msgstr "" # Default: Analog left msgid "analog-left" msgstr "" # Default: Analog right msgid "analog-right" msgstr "" # Default: Animation department msgid "animation-department" msgstr "" # Default: Archive footage msgid "archive-footage" msgstr "" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "" # Default: Art department msgid "art-department" msgstr "" # Default: Art direction msgid "art-direction" msgstr "" # Default: Art director msgid "art-director" msgstr "" # Default: Article msgid "article" msgstr "مقال" # Default: Asin msgid "asin" msgstr "" # Default: Aspect ratio msgid "aspect-ratio" msgstr "" # Default: Assigner msgid "assigner" msgstr "" # Default: Assistant director msgid "assistant-director" msgstr "" # Default: Auctions msgid "auctions" msgstr "" # Default: Audio noise msgid "audio-noise" msgstr "" # Default: Audio quality msgid "audio-quality" msgstr "جودة الصوت" # Default: Award msgid "award" msgstr "جائزة" # Default: Awards msgid "awards" msgstr "جوائز" # Default: Biographical movies msgid "biographical-movies" msgstr "" # Default: Biography msgid "biography" msgstr "" # Default: Biography print msgid "biography-print" msgstr "" # Default: Birth date msgid "birth-date" msgstr "تاريخ الميلاد" # Default: Birth name msgid "birth-name" msgstr "" # Default: Birth notes msgid "birth-notes" msgstr "" # Default: Body msgid "body" msgstr "جسد" # Default: Book msgid "book" msgstr "كتاب" # Default: Books msgid "books" msgstr "كتب" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "" # Default: Budget msgid "budget" msgstr "" # Default: Business msgid "business" msgstr "" # Default: By arrangement with msgid "by-arrangement-with" msgstr "" # Default: Camera msgid "camera" msgstr "كاميرا" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "" # Default: Canonical name msgid "canonical-name" msgstr "" # Default: Canonical series title msgid "canonical-series-title" msgstr "" # Default: Canonical title msgid "canonical-title" msgstr "" # Default: Cast msgid "cast" msgstr "" # Default: Casting department msgid "casting-department" msgstr "" # Default: Casting director msgid "casting-director" msgstr "" # Default: Catalog number msgid "catalog-number" msgstr "" # Default: Category msgid "category" msgstr "فئة" # Default: Certificate msgid "certificate" msgstr "شهادة" # Default: Certificates msgid "certificates" msgstr "شهادات" # Default: Certification msgid "certification" msgstr "" # Default: Channel msgid "channel" msgstr "قناة" # Default: Character msgid "character" msgstr "شخصية" # Default: Cinematographer msgid "cinematographer" msgstr "" # Default: Cinematographic process msgid "cinematographic-process" msgstr "" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "" # Default: Color information msgid "color-information" msgstr "" # Default: Color rendition msgid "color-rendition" msgstr "" # Default: Company msgid "company" msgstr "شركة" # Default: Complete cast msgid "complete-cast" msgstr "" # Default: Complete crew msgid "complete-crew" msgstr "" # Default: Composer msgid "composer" msgstr "مؤلف" # Default: Connections msgid "connections" msgstr "" # Default: Contrast msgid "contrast" msgstr "" # Default: Copyright holder msgid "copyright-holder" msgstr "" # Default: Costume department msgid "costume-department" msgstr "" # Default: Costume designer msgid "costume-designer" msgstr "" # Default: Countries msgid "countries" msgstr "بلدان" # Default: Country msgid "country" msgstr "بلد" # Default: Courtesy of msgid "courtesy-of" msgstr "" # Default: Cover msgid "cover" msgstr "" # Default: Cover url msgid "cover-url" msgstr "" # Default: Crazy credits msgid "crazy-credits" msgstr "" # Default: Creator msgid "creator" msgstr "" # Default: Current role msgid "current-role" msgstr "" # Default: Database msgid "database" msgstr "قاعدة البيانات" # Default: Date msgid "date" msgstr "تاريخ" # Default: Death date msgid "death-date" msgstr "" # Default: Death notes msgid "death-notes" msgstr "" # Default: Demographic msgid "demographic" msgstr "ديموغرافي" # Default: Description msgid "description" msgstr "وصف" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "" # Default: Digital sound msgid "digital-sound" msgstr "" # Default: Director msgid "director" msgstr "مخرج" # Default: Disc format msgid "disc-format" msgstr "" # Default: Disc size msgid "disc-size" msgstr "" # Default: Distributors msgid "distributors" msgstr "موزعون" # Default: Dvd msgid "dvd" msgstr "dvd" # Default: Dvd features msgid "dvd-features" msgstr "" # Default: Dvd format msgid "dvd-format" msgstr "" # Default: Dvds msgid "dvds" msgstr "" # Default: Dynamic range msgid "dynamic-range" msgstr "" # Default: Edited from msgid "edited-from" msgstr "" # Default: Edited into msgid "edited-into" msgstr "" # Default: Editor msgid "editor" msgstr "محرر" # Default: Editorial department msgid "editorial-department" msgstr "" # Default: Episode msgid "episode" msgstr "حلقة" # Default: Episode of msgid "episode-of" msgstr "" # Default: Episode title msgid "episode-title" msgstr "" # Default: Episodes msgid "episodes" msgstr "حلقات" # Default: Episodes rating msgid "episodes-rating" msgstr "" # Default: Essays msgid "essays" msgstr "" # Default: External reviews msgid "external-reviews" msgstr "" # Default: Faqs msgid "faqs" msgstr "" # Default: Feature msgid "feature" msgstr "" # Default: Featured in msgid "featured-in" msgstr "" # Default: Features msgid "features" msgstr "" # Default: Film negative format msgid "film-negative-format" msgstr "" # Default: Filming dates msgid "filming-dates" msgstr "" # Default: Filmography msgid "filmography" msgstr "" # Default: Followed by msgid "followed-by" msgstr "" # Default: Follows msgid "follows" msgstr "" # Default: For msgid "for" msgstr "ل" # Default: Frequency response msgid "frequency-response" msgstr "" # Default: From msgid "from" msgstr "من" # Default: Full article link msgid "full-article-link" msgstr "" # Default: Full size cover url msgid "full-size-cover-url" msgstr "" # Default: Full size headshot msgid "full-size-headshot" msgstr "" # Default: Genres msgid "genres" msgstr "أنواع" # Default: Goofs msgid "goofs" msgstr "" # Default: Gross msgid "gross" msgstr "" # Default: Group genre msgid "group-genre" msgstr "" # Default: Headshot msgid "headshot" msgstr "" # Default: Height msgid "height" msgstr "" # Default: Imdbindex msgid "imdbindex" msgstr "" # Default: In development msgid "in-development" msgstr "" # Default: Interview msgid "interview" msgstr "حوار" # Default: Interviews msgid "interviews" msgstr "" # Default: Introduction msgid "introduction" msgstr "مقدمة" # Default: Item msgid "item" msgstr "" # Default: Keywords msgid "keywords" msgstr "" # Default: Kind msgid "kind" msgstr "" # Default: Label msgid "label" msgstr "" # Default: Laboratory msgid "laboratory" msgstr "مختبر" # Default: Language msgid "language" msgstr "لغة" # Default: Languages msgid "languages" msgstr "لغات" # Default: Laserdisc msgid "laserdisc" msgstr "" # Default: Laserdisc title msgid "laserdisc-title" msgstr "" # Default: Length msgid "length" msgstr "" # Default: Line msgid "line" msgstr "" # Default: Link msgid "link" msgstr "رابط" # Default: Link text msgid "link-text" msgstr "" # Default: Literature msgid "literature" msgstr "" # Default: Locations msgid "locations" msgstr "مواقع" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "" # Default: Long imdb name msgid "long-imdb-name" msgstr "" # Default: Long imdb title msgid "long-imdb-title" msgstr "" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "" # Default: Make up msgid "make-up" msgstr "" # Default: Master format msgid "master-format" msgstr "" # Default: Median msgid "median" msgstr "" # Default: Merchandising links msgid "merchandising-links" msgstr "" # Default: Mini biography msgid "mini-biography" msgstr "" # Default: Misc links msgid "misc-links" msgstr "" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "" # Default: Movie msgid "movie" msgstr "فيلم" # Default: Mpaa msgid "mpaa" msgstr "" # Default: Music department msgid "music-department" msgstr "" # Default: Name msgid "name" msgstr "إسم" # Default: News msgid "news" msgstr "أخبار" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "" # Default: Nick names msgid "nick-names" msgstr "" # Default: Notes msgid "notes" msgstr "" # Default: Novel msgid "novel" msgstr "رواية" # Default: Number msgid "number" msgstr "رقم" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "" # Default: Number of episodes msgid "number-of-episodes" msgstr "" # Default: Number of seasons msgid "number-of-seasons" msgstr "" # Default: Number of sides msgid "number-of-sides" msgstr "" # Default: Number of votes msgid "number-of-votes" msgstr "" # Default: Official retail price msgid "official-retail-price" msgstr "" # Default: Official sites msgid "official-sites" msgstr "" # Default: Opening weekend msgid "opening-weekend" msgstr "" # Default: Original air date msgid "original-air-date" msgstr "" # Default: Original music msgid "original-music" msgstr "" # Default: Original title msgid "original-title" msgstr "" # Default: Other literature msgid "other-literature" msgstr "" # Default: Other works msgid "other-works" msgstr "" # Default: Parents guide msgid "parents-guide" msgstr "" # Default: Performed by msgid "performed-by" msgstr "" # Default: Person msgid "person" msgstr "شخص" # Default: Photo sites msgid "photo-sites" msgstr "" # Default: Pictorial msgid "pictorial" msgstr "" # Default: Picture format msgid "picture-format" msgstr "" # Default: Plot msgid "plot" msgstr "حبكة" # Default: Plot outline msgid "plot-outline" msgstr "" # Default: Portrayed in msgid "portrayed-in" msgstr "" # Default: Pressing plant msgid "pressing-plant" msgstr "" # Default: Printed film format msgid "printed-film-format" msgstr "" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "" # Default: Producer msgid "producer" msgstr "منتج" # Default: Production companies msgid "production-companies" msgstr "" # Default: Production country msgid "production-country" msgstr "" # Default: Production dates msgid "production-dates" msgstr "" # Default: Production design msgid "production-design" msgstr "" # Default: Production designer msgid "production-designer" msgstr "" # Default: Production manager msgid "production-manager" msgstr "" # Default: Production process protocol msgid "production-process-protocol" msgstr "" # Default: Quality of source msgid "quality-of-source" msgstr "" # Default: Quality program msgid "quality-program" msgstr "" # Default: Quote msgid "quote" msgstr "مقتبس" # Default: Quotes msgid "quotes" msgstr "مقتبسات" # Default: Rating msgid "rating" msgstr "تقييم" # Default: Recommendations msgid "recommendations" msgstr "" # Default: Referenced in msgid "referenced-in" msgstr "" # Default: References msgid "references" msgstr "" # Default: Region msgid "region" msgstr "" # Default: Release country msgid "release-country" msgstr "" # Default: Release date msgid "release-date" msgstr "" # Default: Release dates msgid "release-dates" msgstr "" # Default: Remade as msgid "remade-as" msgstr "" # Default: Remake of msgid "remake-of" msgstr "" # Default: Rentals msgid "rentals" msgstr "" # Default: Result msgid "result" msgstr "نتيجة" # Default: Review msgid "review" msgstr "" # Default: Review author msgid "review-author" msgstr "" # Default: Review kind msgid "review-kind" msgstr "" # Default: Runtime msgid "runtime" msgstr "" # Default: Runtimes msgid "runtimes" msgstr "" # Default: Salary history msgid "salary-history" msgstr "" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "" # Default: Season msgid "season" msgstr "موسم" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "" # Default: Self msgid "self" msgstr "" # Default: Series animation department msgid "series-animation-department" msgstr "" # Default: Series art department msgid "series-art-department" msgstr "" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "" # Default: Series camera department msgid "series-camera-department" msgstr "" # Default: Series casting department msgid "series-casting-department" msgstr "" # Default: Series cinematographers msgid "series-cinematographers" msgstr "" # Default: Series costume department msgid "series-costume-department" msgstr "" # Default: Series editorial department msgid "series-editorial-department" msgstr "" # Default: Series editors msgid "series-editors" msgstr "" # Default: Series make up department msgid "series-make-up-department" msgstr "" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "" # Default: Series music department msgid "series-music-department" msgstr "" # Default: Series producers msgid "series-producers" msgstr "" # Default: Series production designers msgid "series-production-designers" msgstr "" # Default: Series production managers msgid "series-production-managers" msgstr "" # Default: Series sound department msgid "series-sound-department" msgstr "" # Default: Series special effects department msgid "series-special-effects-department" msgstr "" # Default: Series stunts msgid "series-stunts" msgstr "" # Default: Series title msgid "series-title" msgstr "" # Default: Series transportation department msgid "series-transportation-department" msgstr "" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "" # Default: Series writers msgid "series-writers" msgstr "" # Default: Series years msgid "series-years" msgstr "" # Default: Set decoration msgid "set-decoration" msgstr "" # Default: Sharpness msgid "sharpness" msgstr "" # Default: Similar to msgid "similar-to" msgstr "" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "" # Default: Sound clips msgid "sound-clips" msgstr "" # Default: Sound crew msgid "sound-crew" msgstr "" # Default: Sound encoding msgid "sound-encoding" msgstr "" # Default: Sound mix msgid "sound-mix" msgstr "" # Default: Soundtrack msgid "soundtrack" msgstr "" # Default: Spaciality msgid "spaciality" msgstr "إختصاص" # Default: Special effects msgid "special-effects" msgstr "" # Default: Special effects companies msgid "special-effects-companies" msgstr "" # Default: Special effects department msgid "special-effects-department" msgstr "" # Default: Spin off msgid "spin-off" msgstr "" # Default: Spin off from msgid "spin-off-from" msgstr "" # Default: Spoofed in msgid "spoofed-in" msgstr "" # Default: Spoofs msgid "spoofs" msgstr "" # Default: Spouse msgid "spouse" msgstr "زوج" # Default: Status of availablility msgid "status-of-availablility" msgstr "" # Default: Studio msgid "studio" msgstr "استوديو" # Default: Studios msgid "studios" msgstr "استوديوهات" # Default: Stunt performer msgid "stunt-performer" msgstr "" # Default: Stunts msgid "stunts" msgstr "" # Default: Subtitles msgid "subtitles" msgstr "" # Default: Supplement msgid "supplement" msgstr "" # Default: Supplements msgid "supplements" msgstr "" # Default: Synopsis msgid "synopsis" msgstr "" # Default: Taglines msgid "taglines" msgstr "" # Default: Tech info msgid "tech-info" msgstr "" # Default: Thanks msgid "thanks" msgstr "بفضل" # Default: Time msgid "time" msgstr "وقت" # Default: Title msgid "title" msgstr "عنوان" # Default: Titles in this product msgid "titles-in-this-product" msgstr "" # Default: To msgid "to" msgstr "إلى" # Default: Top 250 rank msgid "top-250-rank" msgstr "" # Default: Trade mark msgid "trade-mark" msgstr "" # Default: Transportation department msgid "transportation-department" msgstr "" # Default: Trivia msgid "trivia" msgstr "" # Default: Tv msgid "tv" msgstr "تلفزيون" # Default: Under license from msgid "under-license-from" msgstr "" # Default: Unknown link msgid "unknown-link" msgstr "" # Default: Upc msgid "upc" msgstr "upc" # Default: Version of msgid "version-of" msgstr "" # Default: Vhs msgid "vhs" msgstr "vhs" # Default: Video msgid "video" msgstr "فيديو" # Default: Video artifacts msgid "video-artifacts" msgstr "" # Default: Video clips msgid "video-clips" msgstr "" # Default: Video noise msgid "video-noise" msgstr "" # Default: Video quality msgid "video-quality" msgstr "" # Default: Video standard msgid "video-standard" msgstr "" # Default: Visual effects msgid "visual-effects" msgstr "" # Default: Votes msgid "votes" msgstr "أصوات" # Default: Votes distribution msgid "votes-distribution" msgstr "" # Default: Weekend gross msgid "weekend-gross" msgstr "" # Default: Where now msgid "where-now" msgstr "" # Default: With msgid "with" msgstr "مع" # Default: Writer msgid "writer" msgstr "كاتب" # Default: Written by msgid "written-by" msgstr "" # Default: Year msgid "year" msgstr "سنة" # Default: Zshops msgid "zshops" msgstr ""
19,765
Python
.py
982
18.461303
129
0.7814
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,206
__init__.py
cinemagoer_cinemagoer/imdb/locale/__init__.py
# Copyright 2009 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This package provides scripts and files for internationalization of Cinemagoer. """ from __future__ import absolute_import, division, print_function, unicode_literals import gettext import os LOCALE_DIR = os.path.dirname(__file__) translation = gettext.translation('imdbpy', LOCALE_DIR) _ = translation.gettext
1,071
Python
.py
24
43.416667
82
0.785029
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,207
imdbpy-it.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-it.po
# Gettext message file for imdbpy msgid "" msgstr "" "Project-Id-Version: imdbpy\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2009-07-03 13:00+0000\n" "Last-Translator: Davide Alberani <[email protected]>\n" "Language-Team: Davide Alberani <[email protected]>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Language-Code: it\n" "Language-Name: Italian\n" "Preferred-Encodings: utf-8\n" "Domain: imdbpy\n" # Default: Actor msgid "actor" msgstr "Attore" # Default: Actress msgid "actress" msgstr "Attrice" # Default: Adaption msgid "adaption" msgstr "Adattamento" # Default: Additional information msgid "additional-information" msgstr "Ulteriori informazioni" # Default: Admissions msgid "admissions" msgstr "Biglietti venduti" # Default: Agent address msgid "agent-address" msgstr "Indirizzo dell'agente" # Default: Airing msgid "airing" msgstr "In onda" # Default: Akas msgid "akas" msgstr "Alias" # Default: Akas from release info msgid "akas-from-release-info" msgstr "Alias dalle informazioni di rilascio" # Default: All products msgid "all-products" msgstr "Tutti i prodotti" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "Versione in altra lingua di" # Default: Alternate versions msgid "alternate-versions" msgstr "Versioni alternative" # Default: Amazon reviews msgid "amazon-reviews" msgstr "Recensione di Amazon" # Default: Analog left msgid "analog-left" msgstr "Analogico sinistro" # Default: Analog right msgid "analog-right" msgstr "Analogico destro" # Default: Animation department msgid "animation-department" msgstr "Dipartimento animazione" # Default: Archive footage msgid "archive-footage" msgstr "Materiale d'archivio" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "Media aritmetica" # Default: Art department msgid "art-department" msgstr "Dipartimento artistico" # Default: Art direction msgid "art-direction" msgstr "Direzione artistica" # Default: Art director msgid "art-director" msgstr "Direttore artistico" # Default: Article msgid "article" msgstr "Articolo" # Default: Asin msgid "asin" msgstr "Asin" # Default: Aspect ratio msgid "aspect-ratio" msgstr "Rapporto d'aspetto" # Default: Assigner msgid "assigner" msgstr "Assegnatario" # Default: Assistant director msgid "assistant-director" msgstr "Assistente regista" # Default: Auctions msgid "auctions" msgstr "Aste" # Default: Audio noise msgid "audio-noise" msgstr "Rumore audio" # Default: Audio quality msgid "audio-quality" msgstr "Qualità audio" # Default: Award msgid "award" msgstr "Premio" # Default: Awards msgid "awards" msgstr "Premi" # Default: Biographical movies msgid "biographical-movies" msgstr "Film biografici" # Default: Biography msgid "biography" msgstr "Biografia" # Default: Biography print msgid "biography-print" msgstr "Biografia" # Default: Birth date msgid "birth-date" msgstr "Data di nascita" # Default: Birth name msgid "birth-name" msgstr "Nome di nascita" # Default: Birth notes msgid "birth-notes" msgstr "Note di nascita" # Default: Body msgid "body" msgstr "Corpo" # Default: Book msgid "book" msgstr "Libro" # Default: Books msgid "books" msgstr "Libri" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "Posizione nella bottom 100" # Default: Budget msgid "budget" msgstr "Bilancio" # Default: Business msgid "business" msgstr "Affari" # Default: By arrangement with msgid "by-arrangement-with" msgstr "Arrangiamento con" # Default: Camera msgid "camera" msgstr "Cinepresa" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "Cinepresa e dipartimento elettrico" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "Titolo dell'episodio in forma canonica" # Default: Canonical name msgid "canonical-name" msgstr "Nome in forma canonica" # Default: Canonical series title msgid "canonical-series-title" msgstr "Titolo della serie in forma canonica" # Default: Canonical title msgid "canonical-title" msgstr "Titolo in forma canonica" # Default: Cast msgid "cast" msgstr "Cast" # Default: Casting department msgid "casting-department" msgstr "Casting" # Default: Casting director msgid "casting-director" msgstr "Direttore del casting" # Default: Catalog number msgid "catalog-number" msgstr "Numero di catalogo" # Default: Category msgid "category" msgstr "Categoria" # Default: Certificate msgid "certificate" msgstr "Certificazione" # Default: Certificates msgid "certificates" msgstr "Certificazioni" # Default: Certification msgid "certification" msgstr "Certificazioni" # Default: Channel msgid "channel" msgstr "Canale" # Default: Character msgid "character" msgstr "Personaggio" # Default: Cinematographer msgid "cinematographer" msgstr "Fotografia" # Default: Cinematographic process msgid "cinematographic-process" msgstr "Processo cinematografico" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "Colore" # Default: Color information msgid "color-information" msgstr "Informazioni sul colore" # Default: Color rendition msgid "color-rendition" msgstr "Resa dei colori" # Default: Company msgid "company" msgstr "Compagnia" # Default: Complete cast msgid "complete-cast" msgstr "Cast completo" # Default: Complete crew msgid "complete-crew" msgstr "Troupe completa" # Default: Composer msgid "composer" msgstr "Compositore" # Default: Connections msgid "connections" msgstr "Collegamenti" # Default: Contrast msgid "contrast" msgstr "Contrasto" # Default: Copyright holder msgid "copyright-holder" msgstr "Detentore dei diritti d'autore" # Default: Costume department msgid "costume-department" msgstr "Dipartimento costumi" # Default: Costume designer msgid "costume-designer" msgstr "Costumista" # Default: Countries msgid "countries" msgstr "Paesi" # Default: Country msgid "country" msgstr "Paese" # Default: Courtesy of msgid "courtesy-of" msgstr "Cortesia di" # Default: Cover msgid "cover" msgstr "Copertina" # Default: Cover url msgid "cover-url" msgstr "Locandina" # Default: Crazy credits msgid "crazy-credits" msgstr "Titoli pazzi" # Default: Creator msgid "creator" msgstr "Creatore" # Default: Current role msgid "current-role" msgstr "Ruolo" # Default: Database msgid "database" msgstr "Database" # Default: Date msgid "date" msgstr "Data" # Default: Death date msgid "death-date" msgstr "Data di morte" # Default: Death notes msgid "death-notes" msgstr "Note di morte" # Default: Demographic msgid "demographic" msgstr "Spaccato demografico" # Default: Description msgid "description" msgstr "Descrizione" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "Comprensibilità dei dialoghi" # Default: Digital sound msgid "digital-sound" msgstr "Suono digitale" # Default: Director msgid "director" msgstr "Regista" # Default: Disc format msgid "disc-format" msgstr "Formato del disco" # Default: Disc size msgid "disc-size" msgstr "Dimensione del disco" # Default: Distributors msgid "distributors" msgstr "Distributori" # Default: Dvd msgid "dvd" msgstr "Dvd" # Default: Dvd features msgid "dvd-features" msgstr "Caratteristiche del DVD" # Default: Dvd format msgid "dvd-format" msgstr "Formato del DVD" # Default: Dvds msgid "dvds" msgstr "Dvd" # Default: Dynamic range msgid "dynamic-range" msgstr "Intervallo dinamico" # Default: Edited from msgid "edited-from" msgstr "Tratto da" # Default: Edited into msgid "edited-into" msgstr "Montato in" # Default: Editor msgid "editor" msgstr "Editore" # Default: Editorial department msgid "editorial-department" msgstr "Dipartimento editoriale" # Default: Episode msgid "episode" msgstr "Episodio" # Default: Episode of msgid "episode-of" msgstr "Episodio di" # Default: Episode title msgid "episode-title" msgstr "Titolo dell'episodio" # Default: Episodes msgid "episodes" msgstr "Episodi" # Default: Episodes rating msgid "episodes-rating" msgstr "Voto degli episodi" # Default: Essays msgid "essays" msgstr "Saggi" # Default: External reviews msgid "external-reviews" msgstr "Recensioni esterne" # Default: Faqs msgid "faqs" msgstr "Domande ricorrenti" # Default: Feature msgid "feature" msgstr "Caratteristica" # Default: Featured in msgid "featured-in" msgstr "Ripreso in" # Default: Features msgid "features" msgstr "Caratteristiche" # Default: Film negative format msgid "film-negative-format" msgstr "Formato del negativo" # Default: Filming dates msgid "filming-dates" msgstr "Data delle riprese" # Default: Filmography msgid "filmography" msgstr "Filmografia" # Default: Followed by msgid "followed-by" msgstr "Seguito da" # Default: Follows msgid "follows" msgstr "Segue" # Default: For msgid "for" msgstr "Per" # Default: Frequency response msgid "frequency-response" msgstr "Frequenze di risposta" # Default: From msgid "from" msgstr "Da" # Default: Full article link msgid "full-article-link" msgstr "Collegamento all'articolo completo" # Default: Full size cover url msgid "full-size-cover-url" msgstr "URL della copertina nelle dimensioni originali" # Default: Full size headshot msgid "full-size-headshot" msgstr "Ritratto nelle dimensioni originali" # Default: Genres msgid "genres" msgstr "Generi" # Default: Goofs msgid "goofs" msgstr "Errori" # Default: Gross msgid "gross" msgstr "Lordo" # Default: Group genre msgid "group-genre" msgstr "" # Default: Headshot msgid "headshot" msgstr "Foto" # Default: Height msgid "height" msgstr "Altezza" # Default: Imdbindex msgid "imdbindex" msgstr "" # Default: In development msgid "in-development" msgstr "In sviluppo" # Default: Interview msgid "interview" msgstr "Intervista" # Default: Interviews msgid "interviews" msgstr "Interviste" # Default: Introduction msgid "introduction" msgstr "Introduzione" # Default: Item msgid "item" msgstr "Elemento" # Default: Keywords msgid "keywords" msgstr "Parole chiave" # Default: Kind msgid "kind" msgstr "Tipo" # Default: Label msgid "label" msgstr "Etichetta" # Default: Laboratory msgid "laboratory" msgstr "Laboratorio" # Default: Language msgid "language" msgstr "Lingua" # Default: Languages msgid "languages" msgstr "Lingue" # Default: Laserdisc msgid "laserdisc" msgstr "Laserdisc" # Default: Laserdisc title msgid "laserdisc-title" msgstr "Titolo del laserdisc" # Default: Length msgid "length" msgstr "Durata" # Default: Line msgid "line" msgstr "Battuta" # Default: Link msgid "link" msgstr "Collegamento" # Default: Link text msgid "link-text" msgstr "Testo del link" # Default: Literature msgid "literature" msgstr "Letteratura" # Default: Locations msgid "locations" msgstr "Luoghi" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "Nome canonico IMDb lungo" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "Titolo canonico IMDb lungo" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "Titolo dell'episodio canonico IMDb lungo" # Default: Long imdb name msgid "long-imdb-name" msgstr "Nome IMDb lungo" # Default: Long imdb title msgid "long-imdb-title" msgstr "Titolo IMDb lungo" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "Foto di copertina" # Default: Make up msgid "make-up" msgstr "Trucco" # Default: Master format msgid "master-format" msgstr "Formato del master" # Default: Median msgid "median" msgstr "Mediana" # Default: Merchandising links msgid "merchandising-links" msgstr "Collegamenti al merchandising" # Default: Mini biography msgid "mini-biography" msgstr "Biografia" # Default: Misc links msgid "misc-links" msgstr "Altri collegamenti" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "Altre compagnie" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "Altra troupe" # Default: Movie msgid "movie" msgstr "Film" # Default: Mpaa msgid "mpaa" msgstr "Visto MPAA" # Default: Music department msgid "music-department" msgstr "Dipartimento musicale" # Default: Name msgid "name" msgstr "Nome" # Default: News msgid "news" msgstr "Notizie" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "Recensioni dai gruppi di discussione" # Default: Nick names msgid "nick-names" msgstr "Soprannomi" # Default: Notes msgid "notes" msgstr "Note" # Default: Novel msgid "novel" msgstr "Novella" # Default: Number msgid "number" msgstr "Numero" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "Numero di interruzioni di capitolo" # Default: Number of episodes msgid "number-of-episodes" msgstr "Numero di episodi" # Default: Number of seasons msgid "number-of-seasons" msgstr "Numero di stagioni" # Default: Number of sides msgid "number-of-sides" msgstr "Numero di lati" # Default: Number of votes msgid "number-of-votes" msgstr "Numero di voti" # Default: Official retail price msgid "official-retail-price" msgstr "Prezzo ufficiale al pubblico" # Default: Official sites msgid "official-sites" msgstr "Siti ufficiali" # Default: Opening weekend msgid "opening-weekend" msgstr "Weekend d'apertura" # Default: Original air date msgid "original-air-date" msgstr "Data della prima messa in onda" # Default: Original music msgid "original-music" msgstr "Musica originale" # Default: Original title msgid "original-title" msgstr "Titolo originale" # Default: Other literature msgid "other-literature" msgstr "Altre opere letterarie" # Default: Other works msgid "other-works" msgstr "Altri lavori" # Default: Parents guide msgid "parents-guide" msgstr "Guida per i genitori" # Default: Performed by msgid "performed-by" msgstr "Eseguito da" # Default: Person msgid "person" msgstr "Persona" # Default: Photo sites msgid "photo-sites" msgstr "Siti con fotografie" # Default: Pictorial msgid "pictorial" msgstr "Ritratto" # Default: Picture format msgid "picture-format" msgstr "Formato dell'immagine" # Default: Plot msgid "plot" msgstr "Trama" # Default: Plot outline msgid "plot-outline" msgstr "Trama in breve" # Default: Portrayed in msgid "portrayed-in" msgstr "Rappresentato in" # Default: Pressing plant msgid "pressing-plant" msgstr "Impianto di stampa" # Default: Printed film format msgid "printed-film-format" msgstr "Formato della pellicola" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "Recensioni su carta stampata" # Default: Producer msgid "producer" msgstr "Produttore" # Default: Production companies msgid "production-companies" msgstr "Compagnie di produzione" # Default: Production country msgid "production-country" msgstr "Paese di produzione" # Default: Production dates msgid "production-dates" msgstr "Date di produzione" # Default: Production design msgid "production-design" msgstr "Design di produzione" # Default: Production designer msgid "production-designer" msgstr "Designer di produzione" # Default: Production manager msgid "production-manager" msgstr "Manager di produzione" # Default: Production process protocol msgid "production-process-protocol" msgstr "Controllo del processo di produzione" # Default: Quality of source msgid "quality-of-source" msgstr "Qualità dell'originale" # Default: Quality program msgid "quality-program" msgstr "Programma di Qualità" # Default: Quote msgid "quote" msgstr "Citazione" # Default: Quotes msgid "quotes" msgstr "Citazioni" # Default: Rating msgid "rating" msgstr "Voto" # Default: Recommendations msgid "recommendations" msgstr "Raccomandazioni" # Default: Referenced in msgid "referenced-in" msgstr "Citato in" # Default: References msgid "references" msgstr "Cita" # Default: Region msgid "region" msgstr "Regione" # Default: Release country msgid "release-country" msgstr "Paese d'uscita" # Default: Release date msgid "release-date" msgstr "Data d'uscita" # Default: Release dates msgid "release-dates" msgstr "Date d'uscita" # Default: Remade as msgid "remade-as" msgstr "Rifatto come" # Default: Remake of msgid "remake-of" msgstr "Rifacimento di" # Default: Rentals msgid "rentals" msgstr "Noleggi" # Default: Result msgid "result" msgstr "Risultato" # Default: Review msgid "review" msgstr "Recensione" # Default: Review author msgid "review-author" msgstr "Autore della recensione" # Default: Review kind msgid "review-kind" msgstr "Tipo di recensione" # Default: Runtime msgid "runtime" msgstr "Durata" # Default: Runtimes msgid "runtimes" msgstr "Durate" # Default: Salary history msgid "salary-history" msgstr "Stipendi" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "" # Default: Season msgid "season" msgstr "Stagione" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "Regista della seconda unità o aiuto regista" # Default: Self msgid "self" msgstr "Se stesso" # Default: Series animation department msgid "series-animation-department" msgstr "Dipartimento animazione della serie" # Default: Series art department msgid "series-art-department" msgstr "Dipartimento artistico della serie" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "Assistenti registi della serie" # Default: Series camera department msgid "series-camera-department" msgstr "" # Default: Series casting department msgid "series-casting-department" msgstr "" # Default: Series cinematographers msgid "series-cinematographers" msgstr "" # Default: Series costume department msgid "series-costume-department" msgstr "" # Default: Series editorial department msgid "series-editorial-department" msgstr "" # Default: Series editors msgid "series-editors" msgstr "" # Default: Series make up department msgid "series-make-up-department" msgstr "" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "" # Default: Series music department msgid "series-music-department" msgstr "" # Default: Series producers msgid "series-producers" msgstr "" # Default: Series production designers msgid "series-production-designers" msgstr "" # Default: Series production managers msgid "series-production-managers" msgstr "" # Default: Series sound department msgid "series-sound-department" msgstr "Dipartimento sonoro della serie" # Default: Series special effects department msgid "series-special-effects-department" msgstr "Dipartimento effetti speciali della serie" # Default: Series stunts msgid "series-stunts" msgstr "Controfigure della serie" # Default: Series title msgid "series-title" msgstr "Titolo della serie" # Default: Series transportation department msgid "series-transportation-department" msgstr "" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "" # Default: Series writers msgid "series-writers" msgstr "Scrittori della serie" # Default: Series years msgid "series-years" msgstr "Anni della serie" # Default: Set decoration msgid "set-decoration" msgstr "Decorazione del set" # Default: Sharpness msgid "sharpness" msgstr "" # Default: Similar to msgid "similar-to" msgstr "Simile a" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "Titolo canonico intelligente dell'episodio" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "Titolo canonico intelligente della serie" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "Titolo canonico intelligente" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "Titolo canonico lungo intelligente" # Default: Sound clips msgid "sound-clips" msgstr "" # Default: Sound crew msgid "sound-crew" msgstr "" # Default: Sound encoding msgid "sound-encoding" msgstr "Codifica sonora" # Default: Sound mix msgid "sound-mix" msgstr "Mix audio" # Default: Soundtrack msgid "soundtrack" msgstr "Colonna sonora" # Default: Spaciality msgid "spaciality" msgstr "Specialità" # Default: Special effects msgid "special-effects" msgstr "Effetti speciali" # Default: Special effects companies msgid "special-effects-companies" msgstr "Compagnie di effetti speciali" # Default: Special effects department msgid "special-effects-department" msgstr "Dipartimento effetti speciali" # Default: Spin off msgid "spin-off" msgstr "Derivati" # Default: Spin off from msgid "spin-off-from" msgstr "Deriva da" # Default: Spoofed in msgid "spoofed-in" msgstr "Preso in giro in" # Default: Spoofs msgid "spoofs" msgstr "Prende in giro" # Default: Spouse msgid "spouse" msgstr "Coniuge" # Default: Status of availablility msgid "status-of-availablility" msgstr "Disponibilità" # Default: Studio msgid "studio" msgstr "Studio" # Default: Studios msgid "studios" msgstr "Studi" # Default: Stunt performer msgid "stunt-performer" msgstr "" # Default: Stunts msgid "stunts" msgstr "Stuntman" # Default: Subtitles msgid "subtitles" msgstr "Sottotitoli" # Default: Supplement msgid "supplement" msgstr "Extra" # Default: Supplements msgid "supplements" msgstr "Extra" # Default: Synopsis msgid "synopsis" msgstr "Compendio della trama" # Default: Taglines msgid "taglines" msgstr "Slogan" # Default: Tech info msgid "tech-info" msgstr "Informazioni tecniche" # Default: Thanks msgid "thanks" msgstr "Ringraziamenti" # Default: Time msgid "time" msgstr "Tempo" # Default: Title msgid "title" msgstr "Titolo" # Default: Titles in this product msgid "titles-in-this-product" msgstr "Titoli in questo prodotto" # Default: To msgid "to" msgstr "A" # Default: Top 250 rank msgid "top-250-rank" msgstr "Posizione nella top 250" # Default: Trade mark msgid "trade-mark" msgstr "Marchio registrato" # Default: Transportation department msgid "transportation-department" msgstr "Dipartimento trasporti" # Default: Trivia msgid "trivia" msgstr "Frivolezze" # Default: Tv msgid "tv" msgstr "Tv" # Default: Under license from msgid "under-license-from" msgstr "Sotto licenza da" # Default: Unknown link msgid "unknown-link" msgstr "Collegamento sconosciuto" # Default: Upc msgid "upc" msgstr "" # Default: Version of msgid "version-of" msgstr "Versione di" # Default: Vhs msgid "vhs" msgstr "VHS" # Default: Video msgid "video" msgstr "Video" # Default: Video artifacts msgid "video-artifacts" msgstr "Imperfezioni video" # Default: Video clips msgid "video-clips" msgstr "Video clips" # Default: Video noise msgid "video-noise" msgstr "Rumore video" # Default: Video quality msgid "video-quality" msgstr "Qualità video" # Default: Video standard msgid "video-standard" msgstr "Standard video" # Default: Visual effects msgid "visual-effects" msgstr "Effetti visivi" # Default: Votes msgid "votes" msgstr "Voti" # Default: Votes distribution msgid "votes-distribution" msgstr "Distribuzione dei voti" # Default: Weekend gross msgid "weekend-gross" msgstr "Lordo del primo fine settimana" # Default: Where now msgid "where-now" msgstr "Cosa sta facendo ora" # Default: With msgid "with" msgstr "Con" # Default: Writer msgid "writer" msgstr "Scrittore" # Default: Written by msgid "written-by" msgstr "Scritto da" # Default: Year msgid "year" msgstr "Anno" # Default: Zshops msgid "zshops" msgstr ""
23,271
Python
.py
979
22.434116
56
0.807904
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,208
imdbpy-tr.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-tr.po
# Gettext message file for imdbpy msgid "" msgstr "" "Project-Id-Version: imdbpy\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2009-04-21 19:04+0200\n" "Last-Translator: H. Turgut Uyar <[email protected]>\n" "Language-Team: Cinemagoer Türkçe <[email protected]>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "Language-Code: tr\n" "Language-Name: Türkçe\n" "Preferred-Encodings: utf-8\n" "Domain: imdbpy\n" # Default: Actor msgid "actor" msgstr "Oyuncu" # Default: Actress msgid "actress" msgstr "Oyuncu" # Default: Adaption msgid "adaption" msgstr "" # Default: Additional information msgid "additional-information" msgstr "Ek bilgi" # Default: Admissions msgid "admissions" msgstr "" # Default: Agent address msgid "agent-address" msgstr "" # Default: Airing msgid "airing" msgstr "Yayımlanma" # Default: Akas msgid "akas" msgstr "Diğer başlıklar" # Default: Akas from release info msgid "akas-from-release-info" msgstr "" # Default: All products msgid "all-products" msgstr "Bütün ürünler" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "" # Default: Alternate versions msgid "alternate-versions" msgstr "" # Default: Amazon reviews msgid "amazon-reviews" msgstr "Amazon eleştirileri" # Default: Analog left msgid "analog-left" msgstr "Analog sol" # Default: Analog right msgid "analog-right" msgstr "Analog sağ" # Default: Animation department msgid "animation-department" msgstr "Animasyon departmanı" # Default: Archive footage msgid "archive-footage" msgstr "Arşiv çekimleri" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "Aritmetik ortalama" # Default: Art department msgid "art-department" msgstr "Sanat departmanı" # Default: Art direction msgid "art-direction" msgstr "Sanat yönetmenliği" # Default: Art director msgid "art-director" msgstr "Sanat yönetmeni" # Default: Article msgid "article" msgstr "" # Default: Asin msgid "asin" msgstr "ASIN" # Default: Aspect ratio msgid "aspect-ratio" msgstr "En-boy oranı" # Default: Assigner msgid "assigner" msgstr "Veren" # Default: Assistant director msgid "assistant-director" msgstr "Yardımcı yönetmen" # Default: Auctions msgid "auctions" msgstr "Açık artırmalar" # Default: Audio noise msgid "audio-noise" msgstr "Ses gürültüsü" # Default: Audio quality msgid "audio-quality" msgstr "Ses kalitesi" # Default: Award msgid "award" msgstr "Ödül" # Default: Awards msgid "awards" msgstr "Ödüller" # Default: Biographical movies msgid "biographical-movies" msgstr "Biyografik filmler" # Default: Biography msgid "biography" msgstr "Biyografi" # Default: Biography print msgid "biography-print" msgstr "Basılı biyografi" # Default: Birth date msgid "birth-date" msgstr "Doğum tarihi" # Default: Birth name msgid "birth-name" msgstr "Asıl ismi" # Default: Birth notes msgid "birth-notes" msgstr "Doğum notları" # Default: Body msgid "body" msgstr "Metin" # Default: Book msgid "book" msgstr "Kitap" # Default: Books msgid "books" msgstr "Kitaplar" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "En kötü 100 içindeki sırası" # Default: Budget msgid "budget" msgstr "Bütçe" # Default: Business msgid "business" msgstr "Gişe" # Default: By arrangement with msgid "by-arrangement-with" msgstr "" # Default: Camera msgid "camera" msgstr "Kamera" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "Kamera ve elektrik departmanı" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "" # Default: Canonical name msgid "canonical-name" msgstr "" # Default: Canonical series title msgid "canonical-series-title" msgstr "" # Default: Canonical title msgid "canonical-title" msgstr "" # Default: Cast msgid "cast" msgstr "Oynayanlar" # Default: Casting department msgid "casting-department" msgstr "Oyuncu seçme departmanı" # Default: Casting director msgid "casting-director" msgstr "Oyuncu seçme yönetmeni" # Default: Catalog number msgid "catalog-number" msgstr "Katalog numarası" # Default: Category msgid "category" msgstr "Kategori" # Default: Certificate msgid "certificate" msgstr "Sertifika" # Default: Certificates msgid "certificates" msgstr "Sertifikalar" # Default: Certification msgid "certification" msgstr "" # Default: Channel msgid "channel" msgstr "Kanal" # Default: Character msgid "character" msgstr "Karakter" # Default: Cinematographer msgid "cinematographer" msgstr "Kameraman" # Default: Cinematographic process msgid "cinematographic-process" msgstr "" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "Renk bilgisi" # Default: Color information msgid "color-information" msgstr "Renk bilgisi" # Default: Color rendition msgid "color-rendition" msgstr "" # Default: Company msgid "company" msgstr "Şirket" # Default: Complete cast msgid "complete-cast" msgstr "Bütün oynayanlar" # Default: Complete crew msgid "complete-crew" msgstr "Bütün çalışanlar" # Default: Composer msgid "composer" msgstr "Besteci" # Default: Connections msgid "connections" msgstr "Bağlantılar" # Default: Contrast msgid "contrast" msgstr "Kontrast" # Default: Copyright holder msgid "copyright-holder" msgstr "Telif sahibi" # Default: Costume department msgid "costume-department" msgstr "Kostüm departmanı" # Default: Costume designer msgid "costume-designer" msgstr "Kostüm tasarımcısı" # Default: Countries msgid "countries" msgstr "Ülkeler" # Default: Country msgid "country" msgstr "Ülke" # Default: Courtesy of msgid "courtesy-of" msgstr "" # Default: Cover msgid "cover" msgstr "Poster" # Default: Cover url msgid "cover-url" msgstr "Poster adresi" # Default: Crazy credits msgid "crazy-credits" msgstr "" # Default: Creator msgid "creator" msgstr "Yaratıcı" # Default: Current role msgid "current-role" msgstr "Şimdiki rol" # Default: Database msgid "database" msgstr "Veritabanı" # Default: Date msgid "date" msgstr "Tarih" # Default: Death date msgid "death-date" msgstr "Ölüm tarihi" # Default: Death notes msgid "death-notes" msgstr "Ölüm notları" # Default: Demographic msgid "demographic" msgstr "Demografi" # Default: Description msgid "description" msgstr "Tarif" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "" # Default: Digital sound msgid "digital-sound" msgstr "Dijital ses" # Default: Director msgid "director" msgstr "Yönetmen" # Default: Disc format msgid "disc-format" msgstr "Disk formatı" # Default: Disc size msgid "disc-size" msgstr "Disk boyu" # Default: Distributors msgid "distributors" msgstr "Dağıtıcılar" # Default: Dvd msgid "dvd" msgstr "DVD" # Default: Dvd features msgid "dvd-features" msgstr "DVD özellikleri" # Default: Dvd format msgid "dvd-format" msgstr "DVD formatı" # Default: Dvds msgid "dvds" msgstr "DVD'ler" # Default: Dynamic range msgid "dynamic-range" msgstr "" # Default: Edited from msgid "edited-from" msgstr "" # Default: Edited into msgid "edited-into" msgstr "" # Default: Editor msgid "editor" msgstr "Montajcı" # Default: Editorial department msgid "editorial-department" msgstr "Montaj departmanı" # Default: Episode msgid "episode" msgstr "Bölüm" # Default: Episode of msgid "episode-of" msgstr "Dizi" # Default: Episode title msgid "episode-title" msgstr "Bölüm başlığı" # Default: Episodes msgid "episodes" msgstr "Bölümler" # Default: Episodes rating msgid "episodes-rating" msgstr "Bölüm puanı" # Default: Essays msgid "essays" msgstr "Denemeler" # Default: External reviews msgid "external-reviews" msgstr "Harici eleştiriler" # Default: Faqs msgid "faqs" msgstr "SSS" # Default: Feature msgid "feature" msgstr "" # Default: Featured in msgid "featured-in" msgstr "" # Default: Features msgid "features" msgstr "" # Default: Film negative format msgid "film-negative-format" msgstr "Film negatif formatı" # Default: Filming dates msgid "filming-dates" msgstr "Çekim tarihleri" # Default: Filmography msgid "filmography" msgstr "Filmografi" # Default: Followed by msgid "followed-by" msgstr "Peşinden gelen film" # Default: Follows msgid "follows" msgstr "Peşinden geldiği film" # Default: For msgid "for" msgstr "Film" # Default: Frequency response msgid "frequency-response" msgstr "" # Default: From msgid "from" msgstr "" # Default: Full article link msgid "full-article-link" msgstr "" # Default: Full size cover url msgid "full-size-cover-url" msgstr "" # Default: Full size headshot msgid "full-size-headshot" msgstr "" # Default: Genres msgid "genres" msgstr "Türler" # Default: Goofs msgid "goofs" msgstr "Hatalar" # Default: Gross msgid "gross" msgstr "Hasılat" # Default: Group genre msgid "group-genre" msgstr "" # Default: Headshot msgid "headshot" msgstr "Resim" # Default: Height msgid "height" msgstr "Boy" # Default: Imdbindex msgid "imdbindex" msgstr "" # Default: In development msgid "in-development" msgstr "" # Default: Interview msgid "interview" msgstr "Söyleşi" # Default: Interviews msgid "interviews" msgstr "Söyleşiler" # Default: Introduction msgid "introduction" msgstr "İlk filmi" # Default: Item msgid "item" msgstr "" # Default: Keywords msgid "keywords" msgstr "Anahtar sözcükler" # Default: Kind msgid "kind" msgstr "Tip" # Default: Label msgid "label" msgstr "" # Default: Laboratory msgid "laboratory" msgstr "Laboratuar" # Default: Language msgid "language" msgstr "Dil" # Default: Languages msgid "languages" msgstr "Diller" # Default: Laserdisc msgid "laserdisc" msgstr "Lazer Disk" # Default: Laserdisc title msgid "laserdisc-title" msgstr "" # Default: Length msgid "length" msgstr "Süre" # Default: Line msgid "line" msgstr "Replik" # Default: Link msgid "link" msgstr "Bağlantı" # Default: Link text msgid "link-text" msgstr "Bağlantı metni" # Default: Literature msgid "literature" msgstr "Edebiyat" # Default: Locations msgid "locations" msgstr "Çekim yerleri" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "IMDb uzun bölüm başlığı" # Default: Long imdb name msgid "long-imdb-name" msgstr "IMDb uzun ismi" # Default: Long imdb title msgid "long-imdb-title" msgstr "IMDb uzun başlığı" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "Dergi kapağı resmi" # Default: Make up msgid "make-up" msgstr "Makyaj" # Default: Master format msgid "master-format" msgstr "Master format" # Default: Median msgid "median" msgstr "Orta değer" # Default: Merchandising links msgid "merchandising-links" msgstr "" # Default: Mini biography msgid "mini-biography" msgstr "Mini biyografi" # Default: Misc links msgid "misc-links" msgstr "" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "" # Default: Movie msgid "movie" msgstr "Film" # Default: Mpaa msgid "mpaa" msgstr "MPAA" # Default: Music department msgid "music-department" msgstr "Müzik departmanı" # Default: Name msgid "name" msgstr "İsim" # Default: News msgid "news" msgstr "Haberler" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "Haber grubu eleştirileri" # Default: Nick names msgid "nick-names" msgstr "Takma isimler" # Default: Notes msgid "notes" msgstr "Notlar" # Default: Novel msgid "novel" msgstr "Roman" # Default: Number msgid "number" msgstr "Sayı" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "" # Default: Number of episodes msgid "number-of-episodes" msgstr "Bölüm sayısı" # Default: Number of seasons msgid "number-of-seasons" msgstr "Sezon sayısı" # Default: Number of sides msgid "number-of-sides" msgstr "" # Default: Number of votes msgid "number-of-votes" msgstr "Oy sayısı" # Default: Official retail price msgid "official-retail-price" msgstr "Resmi perakende satış fiyatı" # Default: Official sites msgid "official-sites" msgstr "Resmi siteler" # Default: Opening weekend msgid "opening-weekend" msgstr "Açılış haftasonu" # Default: Original air date msgid "original-air-date" msgstr "İlk yayımlanma tarihi" # Default: Original music msgid "original-music" msgstr "Orijinal müzik" # Default: Original title msgid "original-title" msgstr "" # Default: Other literature msgid "other-literature" msgstr "" # Default: Other works msgid "other-works" msgstr "Diğer çalışmalar" # Default: Parents guide msgid "parents-guide" msgstr "Ana-baba kılavuzu" # Default: Performed by msgid "performed-by" msgstr "İcra eden" # Default: Person msgid "person" msgstr "Kişi" # Default: Photo sites msgid "photo-sites" msgstr "Fotoğraf siteleri" # Default: Pictorial msgid "pictorial" msgstr "" # Default: Picture format msgid "picture-format" msgstr "Resim formatı" # Default: Plot msgid "plot" msgstr "Konu" # Default: Plot outline msgid "plot-outline" msgstr "Konu kısa özeti" # Default: Portrayed in msgid "portrayed-in" msgstr "" # Default: Pressing plant msgid "pressing-plant" msgstr "" # Default: Printed film format msgid "printed-film-format" msgstr "Basılı film formatı" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "Basın eleştirileri" # Default: Producer msgid "producer" msgstr "Yapımcı" # Default: Production companies msgid "production-companies" msgstr "Yapım şirketleri" # Default: Production country msgid "production-country" msgstr "Yapımcı ülke" # Default: Production dates msgid "production-dates" msgstr "Yapım tarihleri" # Default: Production design msgid "production-design" msgstr "Yapım tasarımı" # Default: Production designer msgid "production-designer" msgstr "Yapım tasarımcısı" # Default: Production manager msgid "production-manager" msgstr "Yapım yöneticisi" # Default: Production process protocol msgid "production-process-protocol" msgstr "" # Default: Quality of source msgid "quality-of-source" msgstr "" # Default: Quality program msgid "quality-program" msgstr "" # Default: Quote msgid "quote" msgstr "Alıntı" # Default: Quotes msgid "quotes" msgstr "Alıntılar" # Default: Rating msgid "rating" msgstr "Puan" # Default: Recommendations msgid "recommendations" msgstr "Tavsiyeler" # Default: Referenced in msgid "referenced-in" msgstr "Gönderme yapılan filmler" # Default: References msgid "references" msgstr "Gönderme yaptığı filmler" # Default: Region msgid "region" msgstr "Bölge" # Default: Release country msgid "release-country" msgstr "" # Default: Release date msgid "release-date" msgstr "" # Default: Release dates msgid "release-dates" msgstr "" # Default: Remade as msgid "remade-as" msgstr "Yeniden çekilişi" # Default: Remake of msgid "remake-of" msgstr "Yeniden çekimi olduğu film" # Default: Rentals msgid "rentals" msgstr "Kiralamalar" # Default: Result msgid "result" msgstr "Sonuç" # Default: Review msgid "review" msgstr "Eleştiri" # Default: Review author msgid "review-author" msgstr "Eleştiri yazarı" # Default: Review kind msgid "review-kind" msgstr "Eleştiri tipi" # Default: Runtime msgid "runtime" msgstr "Süre" # Default: Runtimes msgid "runtimes" msgstr "Süreler" # Default: Salary history msgid "salary-history" msgstr "Üçret tarihçesi" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "Senaryo" # Default: Season msgid "season" msgstr "Sezon" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "İkinci birim yönetmeni ya da yardımcı yönetmen" # Default: Self msgid "self" msgstr "Kendisi" # Default: Series animation department msgid "series-animation-department" msgstr "Dizinin animasyon departmanı" # Default: Series art department msgid "series-art-department" msgstr "Dizinin sanat departmanı" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "Dizinin yardımcı yönetmenleri" # Default: Series camera department msgid "series-camera-department" msgstr "Dizinin kamera departmanı" # Default: Series casting department msgid "series-casting-department" msgstr "Dizinin oyuncu seçimi departmanı" # Default: Series cinematographers msgid "series-cinematographers" msgstr "Dizinin kameramanları" # Default: Series costume department msgid "series-costume-department" msgstr "Dizinin kostüm departmanı" # Default: Series editorial department msgid "series-editorial-department" msgstr "Dizinin montaj departmanı" # Default: Series editors msgid "series-editors" msgstr "Dizinin montajcıları" # Default: Series make up department msgid "series-make-up-department" msgstr "Dizinin makyaj departmanı" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "" # Default: Series music department msgid "series-music-department" msgstr "Dizinin müzik departmanı" # Default: Series producers msgid "series-producers" msgstr "Dizinin yapımcıları" # Default: Series production designers msgid "series-production-designers" msgstr "Dizinin yapım tasarımcıları" # Default: Series production managers msgid "series-production-managers" msgstr "Dizinin yapım yöneticileri" # Default: Series sound department msgid "series-sound-department" msgstr "Dizinin ses departmanı" # Default: Series special effects department msgid "series-special-effects-department" msgstr "Dizinin özel efekt departmanı" # Default: Series stunts msgid "series-stunts" msgstr "Dizinin dublörleri" # Default: Series title msgid "series-title" msgstr "Dizinin başlığı" # Default: Series transportation department msgid "series-transportation-department" msgstr "Dizinin ulaşım departmanı" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "Dizinin görsel efekt departmanı" # Default: Series writers msgid "series-writers" msgstr "Dizinin yazarları" # Default: Series years msgid "series-years" msgstr "Dizinin yılları" # Default: Set decoration msgid "set-decoration" msgstr "Set dekorasyonu" # Default: Sharpness msgid "sharpness" msgstr "Keskinlik" # Default: Similar to msgid "similar-to" msgstr "Benzer" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "" # Default: Sound clips msgid "sound-clips" msgstr "Ses klipleri" # Default: Sound crew msgid "sound-crew" msgstr "Ses ekibi" # Default: Sound encoding msgid "sound-encoding" msgstr "Ses kodlaması" # Default: Sound mix msgid "sound-mix" msgstr "" # Default: Soundtrack msgid "soundtrack" msgstr "Film müzikleri" # Default: Spaciality msgid "spaciality" msgstr "" # Default: Special effects msgid "special-effects" msgstr "Özel efektler" # Default: Special effects companies msgid "special-effects-companies" msgstr "Özel efekt şirketleri" # Default: Special effects department msgid "special-effects-department" msgstr "Özel efekt departmanı" # Default: Spin off msgid "spin-off" msgstr "" # Default: Spin off from msgid "spin-off-from" msgstr "" # Default: Spoofed in msgid "spoofed-in" msgstr "Dalga geçildiği filmler" # Default: Spoofs msgid "spoofs" msgstr "Dalga geçtiği filmler" # Default: Spouse msgid "spouse" msgstr "Eşi" # Default: Status of availablility msgid "status-of-availablility" msgstr "" # Default: Studio msgid "studio" msgstr "Stüdyo" # Default: Studios msgid "studios" msgstr "Stüdyolar" # Default: Stunt performer msgid "stunt-performer" msgstr "" # Default: Stunts msgid "stunts" msgstr "Dublörler" # Default: Subtitles msgid "subtitles" msgstr "Altyazılar" # Default: Supplement msgid "supplement" msgstr "" # Default: Supplements msgid "supplements" msgstr "" # Default: Synopsis msgid "synopsis" msgstr "Sinopsis" # Default: Taglines msgid "taglines" msgstr "Spotlar" # Default: Tech info msgid "tech-info" msgstr "Teknik bilgi" # Default: Thanks msgid "thanks" msgstr "Teşekkürler" # Default: Time msgid "time" msgstr "Zaman" # Default: Title msgid "title" msgstr "Başlık" # Default: Titles in this product msgid "titles-in-this-product" msgstr "Bu üründeki başlıklar" # Default: To msgid "to" msgstr "Alan" # Default: Top 250 rank msgid "top-250-rank" msgstr "En iyi 250 içindeki sırası" # Default: Trade mark msgid "trade-mark" msgstr "Kendine has özelliği" # Default: Transportation department msgid "transportation-department" msgstr "Ulaşım departmanı" # Default: Trivia msgid "trivia" msgstr "İlginç notlar" # Default: Tv msgid "tv" msgstr "" # Default: Under license from msgid "under-license-from" msgstr "" # Default: Unknown link msgid "unknown-link" msgstr "" # Default: Upc msgid "upc" msgstr "" # Default: Version of msgid "version-of" msgstr "" # Default: Vhs msgid "vhs" msgstr "VHS" # Default: Video msgid "video" msgstr "" # Default: Video artifacts msgid "video-artifacts" msgstr "" # Default: Video clips msgid "video-clips" msgstr "Video klipleri" # Default: Video noise msgid "video-noise" msgstr "Video gürültüsü" # Default: Video quality msgid "video-quality" msgstr "Video kalitesi" # Default: Video standard msgid "video-standard" msgstr "Video standardı" # Default: Visual effects msgid "visual-effects" msgstr "Görsel efektler" # Default: Votes msgid "votes" msgstr "Oylar" # Default: Votes distribution msgid "votes-distribution" msgstr "Oyların dağılımı" # Default: Weekend gross msgid "weekend-gross" msgstr "Haftasonu hasılatı" # Default: Where now msgid "where-now" msgstr "Şu anda nerede" # Default: With msgid "with" msgstr "" # Default: Writer msgid "writer" msgstr "Yazar" # Default: Written by msgid "written-by" msgstr "Yazan" # Default: Year msgid "year" msgstr "Yıl" # Default: Zshops msgid "zshops" msgstr "ZShops"
22,303
Python
.py
979
21.129724
55
0.802572
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,209
imdbpy-fr.po
cinemagoer_cinemagoer/imdb/locale/imdbpy-fr.po
# Gettext message file for imdbpy # Translators: # lukophron, 2014-2016 # Rajaa Jalil <[email protected]>, 2013 # lkppo, 2012 msgid "" msgstr "" "Project-Id-Version: Cinemagoer\n" "POT-Creation-Date: 2010-03-18 14:35+0000\n" "PO-Revision-Date: 2016-03-20 05:27+0000\n" "Last-Translator: lukophron\n" "Language-Team: French (http://www.transifex.com/davide_alberani/imdbpy/language/fr/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Domain: imdbpy\n" "Language: fr\n" "Language-Code: en\n" "Language-Name: English\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" "Preferred-Encodings: utf-8\n" # Default: Actor msgid "actor" msgstr "acteur" # Default: Actress msgid "actress" msgstr "actrice" # Default: Adaption msgid "adaption" msgstr "adaptation" # Default: Additional information msgid "additional-information" msgstr "information-additionnelle" # Default: Admissions msgid "admissions" msgstr "entrées" # Default: Agent address msgid "agent-address" msgstr "" # Default: Airing msgid "airing" msgstr "en-diffusion" # Default: Akas msgid "akas" msgstr "alias" # Default: Akas from release info msgid "akas-from-release-info" msgstr "alias-depuis-info-sortie" # Default: All products msgid "all-products" msgstr "" # Default: Alternate language version of msgid "alternate-language-version-of" msgstr "" # Default: Alternate versions msgid "alternate-versions" msgstr "" # Default: Amazon reviews msgid "amazon-reviews" msgstr "critiques-amazon" # Default: Analog left msgid "analog-left" msgstr "" # Default: Analog right msgid "analog-right" msgstr "" # Default: Animation department msgid "animation-department" msgstr "département-animation" # Default: Archive footage msgid "archive-footage" msgstr "" # Default: Arithmetic mean msgid "arithmetic-mean" msgstr "" # Default: Art department msgid "art-department" msgstr "" # Default: Art direction msgid "art-direction" msgstr "" # Default: Art director msgid "art-director" msgstr "" # Default: Article msgid "article" msgstr "article" # Default: Asin msgid "asin" msgstr "asin" # Default: Aspect ratio msgid "aspect-ratio" msgstr "" # Default: Assigner msgid "assigner" msgstr "" # Default: Assistant director msgid "assistant-director" msgstr "" # Default: Auctions msgid "auctions" msgstr "" # Default: Audio noise msgid "audio-noise" msgstr "" # Default: Audio quality msgid "audio-quality" msgstr "" # Default: Award msgid "award" msgstr "récompense" # Default: Awards msgid "awards" msgstr "récompenses" # Default: Biographical movies msgid "biographical-movies" msgstr "" # Default: Biography msgid "biography" msgstr "biographie" # Default: Biography print msgid "biography-print" msgstr "" # Default: Birth date msgid "birth-date" msgstr "" # Default: Birth name msgid "birth-name" msgstr "" # Default: Birth notes msgid "birth-notes" msgstr "" # Default: Body msgid "body" msgstr "Corps" # Default: Book msgid "book" msgstr "livre" # Default: Books msgid "books" msgstr "livres" # Default: Bottom 100 rank msgid "bottom-100-rank" msgstr "" # Default: Budget msgid "budget" msgstr "budget" # Default: Business msgid "business" msgstr "" # Default: By arrangement with msgid "by-arrangement-with" msgstr "" # Default: Camera msgid "camera" msgstr "camera" # Default: Camera and electrical department msgid "camera-and-electrical-department" msgstr "" # Default: Canonical episode title msgid "canonical-episode-title" msgstr "" # Default: Canonical name msgid "canonical-name" msgstr "" # Default: Canonical series title msgid "canonical-series-title" msgstr "" # Default: Canonical title msgid "canonical-title" msgstr "" # Default: Cast msgid "cast" msgstr "" # Default: Casting department msgid "casting-department" msgstr "" # Default: Casting director msgid "casting-director" msgstr "" # Default: Catalog number msgid "catalog-number" msgstr "" # Default: Category msgid "category" msgstr "catégorie" # Default: Certificate msgid "certificate" msgstr "certificat" # Default: Certificates msgid "certificates" msgstr "" # Default: Certification msgid "certification" msgstr "" # Default: Channel msgid "channel" msgstr "chaîne" # Default: Character msgid "character" msgstr "" # Default: Cinematographer msgid "cinematographer" msgstr "" # Default: Cinematographic process msgid "cinematographic-process" msgstr "" # Default: Close captions teletext ld g msgid "close-captions-teletext-ld-g" msgstr "" # Default: Color info msgid "color-info" msgstr "" # Default: Color information msgid "color-information" msgstr "" # Default: Color rendition msgid "color-rendition" msgstr "" # Default: Company msgid "company" msgstr "société" # Default: Complete cast msgid "complete-cast" msgstr "" # Default: Complete crew msgid "complete-crew" msgstr "" # Default: Composer msgid "composer" msgstr "" # Default: Connections msgid "connections" msgstr "" # Default: Contrast msgid "contrast" msgstr "" # Default: Copyright holder msgid "copyright-holder" msgstr "" # Default: Costume department msgid "costume-department" msgstr "" # Default: Costume designer msgid "costume-designer" msgstr "" # Default: Countries msgid "countries" msgstr "pays" # Default: Country msgid "country" msgstr "pays" # Default: Courtesy of msgid "courtesy-of" msgstr "" # Default: Cover msgid "cover" msgstr "couverture" # Default: Cover url msgid "cover-url" msgstr "" # Default: Crazy credits msgid "crazy-credits" msgstr "" # Default: Creator msgid "creator" msgstr "créateur" # Default: Current role msgid "current-role" msgstr "" # Default: Database msgid "database" msgstr "base de données" # Default: Date msgid "date" msgstr "date" # Default: Death date msgid "death-date" msgstr "" # Default: Death notes msgid "death-notes" msgstr "" # Default: Demographic msgid "demographic" msgstr "" # Default: Description msgid "description" msgstr "description" # Default: Dialogue intellegibility msgid "dialogue-intellegibility" msgstr "" # Default: Digital sound msgid "digital-sound" msgstr "" # Default: Director msgid "director" msgstr "directeur" # Default: Disc format msgid "disc-format" msgstr "" # Default: Disc size msgid "disc-size" msgstr "" # Default: Distributors msgid "distributors" msgstr "distributeurs" # Default: Dvd msgid "dvd" msgstr "dvd" # Default: Dvd features msgid "dvd-features" msgstr "" # Default: Dvd format msgid "dvd-format" msgstr "" # Default: Dvds msgid "dvds" msgstr "dvds" # Default: Dynamic range msgid "dynamic-range" msgstr "" # Default: Edited from msgid "edited-from" msgstr "" # Default: Edited into msgid "edited-into" msgstr "" # Default: Editor msgid "editor" msgstr "éditeur" # Default: Editorial department msgid "editorial-department" msgstr "" # Default: Episode msgid "episode" msgstr "épisode" # Default: Episode of msgid "episode-of" msgstr "" # Default: Episode title msgid "episode-title" msgstr "" # Default: Episodes msgid "episodes" msgstr "épisodes" # Default: Episodes rating msgid "episodes-rating" msgstr "" # Default: Essays msgid "essays" msgstr "" # Default: External reviews msgid "external-reviews" msgstr "" # Default: Faqs msgid "faqs" msgstr "faqs" # Default: Feature msgid "feature" msgstr "Caractéristique" # Default: Featured in msgid "featured-in" msgstr "" # Default: Features msgid "features" msgstr "caractéristiques" # Default: Film negative format msgid "film-negative-format" msgstr "" # Default: Filming dates msgid "filming-dates" msgstr "" # Default: Filmography msgid "filmography" msgstr "" # Default: Followed by msgid "followed-by" msgstr "" # Default: Follows msgid "follows" msgstr "" # Default: For msgid "for" msgstr "pour" # Default: Frequency response msgid "frequency-response" msgstr "" # Default: From msgid "from" msgstr "de" # Default: Full article link msgid "full-article-link" msgstr "" # Default: Full size cover url msgid "full-size-cover-url" msgstr "" # Default: Full size headshot msgid "full-size-headshot" msgstr "" # Default: Genres msgid "genres" msgstr "genres" # Default: Goofs msgid "goofs" msgstr "" # Default: Gross msgid "gross" msgstr "" # Default: Group genre msgid "group-genre" msgstr "" # Default: Headshot msgid "headshot" msgstr "" # Default: Height msgid "height" msgstr "hauteur" # Default: Imdbindex msgid "imdbindex" msgstr "" # Default: In development msgid "in-development" msgstr "" # Default: Interview msgid "interview" msgstr "interview" # Default: Interviews msgid "interviews" msgstr "" # Default: Introduction msgid "introduction" msgstr "introduction" # Default: Item msgid "item" msgstr "élément" # Default: Keywords msgid "keywords" msgstr "" # Default: Kind msgid "kind" msgstr "" # Default: Label msgid "label" msgstr "" # Default: Laboratory msgid "laboratory" msgstr "laboratoire" # Default: Language msgid "language" msgstr "langue" # Default: Languages msgid "languages" msgstr "langues" # Default: Laserdisc msgid "laserdisc" msgstr "" # Default: Laserdisc title msgid "laserdisc-title" msgstr "" # Default: Length msgid "length" msgstr "" # Default: Line msgid "line" msgstr "ligne" # Default: Link msgid "link" msgstr "lien" # Default: Link text msgid "link-text" msgstr "" # Default: Literature msgid "literature" msgstr "" # Default: Locations msgid "locations" msgstr "" # Default: Long imdb canonical name msgid "long-imdb-canonical-name" msgstr "" # Default: Long imdb canonical title msgid "long-imdb-canonical-title" msgstr "" # Default: Long imdb episode title msgid "long-imdb-episode-title" msgstr "" # Default: Long imdb name msgid "long-imdb-name" msgstr "" # Default: Long imdb title msgid "long-imdb-title" msgstr "" # Default: Magazine cover photo msgid "magazine-cover-photo" msgstr "" # Default: Make up msgid "make-up" msgstr "" # Default: Master format msgid "master-format" msgstr "" # Default: Median msgid "median" msgstr "" # Default: Merchandising links msgid "merchandising-links" msgstr "" # Default: Mini biography msgid "mini-biography" msgstr "" # Default: Misc links msgid "misc-links" msgstr "" # Default: Miscellaneous companies msgid "miscellaneous-companies" msgstr "" # Default: Miscellaneous crew msgid "miscellaneous-crew" msgstr "" # Default: Movie msgid "movie" msgstr "film" # Default: Mpaa msgid "mpaa" msgstr "mpaa" # Default: Music department msgid "music-department" msgstr "" # Default: Name msgid "name" msgstr "nom" # Default: News msgid "news" msgstr "actualisé" # Default: Newsgroup reviews msgid "newsgroup-reviews" msgstr "" # Default: Nick names msgid "nick-names" msgstr "" # Default: Notes msgid "notes" msgstr "notesnouvelle" # Default: Novel msgid "novel" msgstr "nouvelle" # Default: Number msgid "number" msgstr "numéro" # Default: Number of chapter stops msgid "number-of-chapter-stops" msgstr "" # Default: Number of episodes msgid "number-of-episodes" msgstr "" # Default: Number of seasons msgid "number-of-seasons" msgstr "" # Default: Number of sides msgid "number-of-sides" msgstr "" # Default: Number of votes msgid "number-of-votes" msgstr "" # Default: Official retail price msgid "official-retail-price" msgstr "" # Default: Official sites msgid "official-sites" msgstr "" # Default: Opening weekend msgid "opening-weekend" msgstr "" # Default: Original air date msgid "original-air-date" msgstr "" # Default: Original music msgid "original-music" msgstr "" # Default: Original title msgid "original-title" msgstr "" # Default: Other literature msgid "other-literature" msgstr "" # Default: Other works msgid "other-works" msgstr "" # Default: Parents guide msgid "parents-guide" msgstr "" # Default: Performed by msgid "performed-by" msgstr "" # Default: Person msgid "person" msgstr "" # Default: Photo sites msgid "photo-sites" msgstr "" # Default: Pictorial msgid "pictorial" msgstr "" # Default: Picture format msgid "picture-format" msgstr "" # Default: Plot msgid "plot" msgstr "" # Default: Plot outline msgid "plot-outline" msgstr "" # Default: Portrayed in msgid "portrayed-in" msgstr "" # Default: Pressing plant msgid "pressing-plant" msgstr "" # Default: Printed film format msgid "printed-film-format" msgstr "" # Default: Printed media reviews msgid "printed-media-reviews" msgstr "" # Default: Producer msgid "producer" msgstr "producteur" # Default: Production companies msgid "production-companies" msgstr "" # Default: Production country msgid "production-country" msgstr "" # Default: Production dates msgid "production-dates" msgstr "" # Default: Production design msgid "production-design" msgstr "" # Default: Production designer msgid "production-designer" msgstr "" # Default: Production manager msgid "production-manager" msgstr "" # Default: Production process protocol msgid "production-process-protocol" msgstr "" # Default: Quality of source msgid "quality-of-source" msgstr "" # Default: Quality program msgid "quality-program" msgstr "" # Default: Quote msgid "quote" msgstr "citation" # Default: Quotes msgid "quotes" msgstr "citations" # Default: Rating msgid "rating" msgstr "" # Default: Recommendations msgid "recommendations" msgstr "" # Default: Referenced in msgid "referenced-in" msgstr "" # Default: References msgid "references" msgstr "références" # Default: Region msgid "region" msgstr "" # Default: Release country msgid "release-country" msgstr "" # Default: Release date msgid "release-date" msgstr "" # Default: Release dates msgid "release-dates" msgstr "" # Default: Remade as msgid "remade-as" msgstr "" # Default: Remake of msgid "remake-of" msgstr "" # Default: Rentals msgid "rentals" msgstr "" # Default: Result msgid "result" msgstr "résultat" # Default: Review msgid "review" msgstr "revue" # Default: Review author msgid "review-author" msgstr "" # Default: Review kind msgid "review-kind" msgstr "" # Default: Runtime msgid "runtime" msgstr "" # Default: Runtimes msgid "runtimes" msgstr "" # Default: Salary history msgid "salary-history" msgstr "" # Default: Screenplay teleplay msgid "screenplay-teleplay" msgstr "" # Default: Season msgid "season" msgstr "saison" # Default: Second unit director or assistant director msgid "second-unit-director-or-assistant-director" msgstr "" # Default: Self msgid "self" msgstr "" # Default: Series animation department msgid "series-animation-department" msgstr "" # Default: Series art department msgid "series-art-department" msgstr "" # Default: Series assistant directors msgid "series-assistant-directors" msgstr "" # Default: Series camera department msgid "series-camera-department" msgstr "" # Default: Series casting department msgid "series-casting-department" msgstr "" # Default: Series cinematographers msgid "series-cinematographers" msgstr "" # Default: Series costume department msgid "series-costume-department" msgstr "" # Default: Series editorial department msgid "series-editorial-department" msgstr "" # Default: Series editors msgid "series-editors" msgstr "" # Default: Series make up department msgid "series-make-up-department" msgstr "" # Default: Series miscellaneous msgid "series-miscellaneous" msgstr "" # Default: Series music department msgid "series-music-department" msgstr "" # Default: Series producers msgid "series-producers" msgstr "" # Default: Series production designers msgid "series-production-designers" msgstr "" # Default: Series production managers msgid "series-production-managers" msgstr "" # Default: Series sound department msgid "series-sound-department" msgstr "" # Default: Series special effects department msgid "series-special-effects-department" msgstr "" # Default: Series stunts msgid "series-stunts" msgstr "" # Default: Series title msgid "series-title" msgstr "" # Default: Series transportation department msgid "series-transportation-department" msgstr "" # Default: Series visual effects department msgid "series-visual-effects-department" msgstr "" # Default: Series writers msgid "series-writers" msgstr "" # Default: Series years msgid "series-years" msgstr "" # Default: Set decoration msgid "set-decoration" msgstr "" # Default: Sharpness msgid "sharpness" msgstr "" # Default: Similar to msgid "similar-to" msgstr "" # Default: Smart canonical episode title msgid "smart-canonical-episode-title" msgstr "" # Default: Smart canonical series title msgid "smart-canonical-series-title" msgstr "" # Default: Smart canonical title msgid "smart-canonical-title" msgstr "" # Default: Smart long imdb canonical title msgid "smart-long-imdb-canonical-title" msgstr "" # Default: Sound clips msgid "sound-clips" msgstr "" # Default: Sound crew msgid "sound-crew" msgstr "" # Default: Sound encoding msgid "sound-encoding" msgstr "" # Default: Sound mix msgid "sound-mix" msgstr "" # Default: Soundtrack msgid "soundtrack" msgstr "" # Default: Spaciality msgid "spaciality" msgstr "" # Default: Special effects msgid "special-effects" msgstr "" # Default: Special effects companies msgid "special-effects-companies" msgstr "" # Default: Special effects department msgid "special-effects-department" msgstr "" # Default: Spin off msgid "spin-off" msgstr "" # Default: Spin off from msgid "spin-off-from" msgstr "" # Default: Spoofed in msgid "spoofed-in" msgstr "" # Default: Spoofs msgid "spoofs" msgstr "" # Default: Spouse msgid "spouse" msgstr "époux" # Default: Status of availablility msgid "status-of-availablility" msgstr "" # Default: Studio msgid "studio" msgstr "studio" # Default: Studios msgid "studios" msgstr "studios" # Default: Stunt performer msgid "stunt-performer" msgstr "" # Default: Stunts msgid "stunts" msgstr "" # Default: Subtitles msgid "subtitles" msgstr "sous-titres" # Default: Supplement msgid "supplement" msgstr "bonus" # Default: Supplements msgid "supplements" msgstr "bonus" # Default: Synopsis msgid "synopsis" msgstr "synopsis" # Default: Taglines msgid "taglines" msgstr "" # Default: Tech info msgid "tech-info" msgstr "" # Default: Thanks msgid "thanks" msgstr "" # Default: Time msgid "time" msgstr "temps" # Default: Title msgid "title" msgstr "titre" # Default: Titles in this product msgid "titles-in-this-product" msgstr "" # Default: To msgid "to" msgstr "" # Default: Top 250 rank msgid "top-250-rank" msgstr "" # Default: Trade mark msgid "trade-mark" msgstr "" # Default: Transportation department msgid "transportation-department" msgstr "" # Default: Trivia msgid "trivia" msgstr "" # Default: Tv msgid "tv" msgstr "tv" # Default: Under license from msgid "under-license-from" msgstr "" # Default: Unknown link msgid "unknown-link" msgstr "" # Default: Upc msgid "upc" msgstr "upc" # Default: Version of msgid "version-of" msgstr "" # Default: Vhs msgid "vhs" msgstr "" # Default: Video msgid "video" msgstr "video" # Default: Video artifacts msgid "video-artifacts" msgstr "" # Default: Video clips msgid "video-clips" msgstr "" # Default: Video noise msgid "video-noise" msgstr "" # Default: Video quality msgid "video-quality" msgstr "" # Default: Video standard msgid "video-standard" msgstr "" # Default: Visual effects msgid "visual-effects" msgstr "" # Default: Votes msgid "votes" msgstr "" # Default: Votes distribution msgid "votes-distribution" msgstr "" # Default: Weekend gross msgid "weekend-gross" msgstr "" # Default: Where now msgid "where-now" msgstr "" # Default: With msgid "with" msgstr "avec" # Default: Writer msgid "writer" msgstr "auteur" # Default: Written by msgid "written-by" msgstr "" # Default: Year msgid "year" msgstr "année" # Default: Zshops msgid "zshops" msgstr ""
19,684
Python
.py
984
18.653455
88
0.78638
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,210
__init__.py
cinemagoer_cinemagoer/imdb/parser/__init__.py
# Copyright 2004-2017 Davide Alberani <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This package provides various parsers to access IMDb data, such as a parser for the web/http interface, a parser for the SQL database interface, etc. So far, the http, s3 and sql parsers are implemented. """ from __future__ import absolute_import, division, print_function, unicode_literals __all__ = ['http', 'sql', 's3']
1,090
Python
.py
22
48.409091
82
0.771831
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,211
movieParser.py
cinemagoer_cinemagoer/imdb/parser/http/movieParser.py
# -*- coding: utf-8 -*- # Copyright 2004-2023 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the IMDb pages on the www.imdb.com server about a movie. For example, for Brian De Palma's "The Untouchables", the referred pages would be: combined details http://www.imdb.com/title/tt0094226/reference plot summary http://www.imdb.com/title/tt0094226/plotsummary ...and so on. """ from __future__ import absolute_import, division, print_function, unicode_literals import functools import re from imdb import PY2, imdbURL_base from imdb.Company import Company from imdb.Movie import Movie from imdb.Person import Person from imdb.utils import KIND_MAP, _Container from .piculet import Path, Rule, Rules, preprocessors, transformers from .utils import DOMParserBase, analyze_imdbid, build_movie, build_person if PY2: from urllib import unquote else: from urllib.parse import unquote # Dictionary used to convert some section's names. _SECT_CONV = { 'directed': 'director', 'directed by': 'director', 'directors': 'director', 'editors': 'editor', 'writing credits': 'writer', 'writers': 'writer', 'produced': 'producer', 'cinematography': 'cinematographer', 'film editing': 'editor', 'casting': 'casting director', 'costume design': 'costume designer', 'makeup department': 'make up', 'production management': 'production manager', 'second unit director or assistant director': 'assistant director', 'costume and wardrobe department': 'costume department', 'costume departmen': 'costume department', 'sound department': 'sound crew', 'stunts': 'stunt performer', 'other crew': 'miscellaneous crew', 'also known as': 'akas', 'country': 'countries', 'runtime': 'runtimes', 'language': 'languages', 'certification': 'certificates', 'genre': 'genres', 'created': 'creator', 'creators': 'creator', 'color': 'color info', 'plot': 'plot outline', 'art director': 'art direction', 'art directors': 'art direction', 'composers': 'composer', 'assistant directors': 'assistant director', 'set decorator': 'set decoration', 'set decorators': 'set decoration', 'visual effects department': 'visual effects', 'miscellaneous': 'miscellaneous crew', 'make up department': 'make up', 'plot summary': 'plot outline', 'cinematographers': 'cinematographer', 'camera department': 'camera and electrical department', 'costume designers': 'costume designer', 'production designer': 'production design', 'production designers': 'production design', 'production managers': 'production manager', 'music original': 'original music', 'casting directors': 'casting director', 'other companies': 'miscellaneous companies', 'producers': 'producer', 'special effects by': 'special effects department', } re_space = re.compile(r'\s+') def clean_section_name(section): """Clean and replace some section names.""" section = re_space.sub(' ', section.replace('_', ' ').strip().lower()) if section.endswith(' by'): section = section[:-3] return _SECT_CONV.get(section, section) def _manageRoles(mo): """Perform some transformation on the html, so that roleIDs can be easily retrieved.""" firstHalf = mo.group(1) secondHalf = mo.group(2) newRoles = [] roles = secondHalf.split(' / ') for role in roles: role = role.strip() if not role: continue roleID = analyze_imdbid(role) if roleID is None: roleID = '/' else: roleID += '/' newRoles.append('<div class="_imdbpyrole" roleid="%s">%s</div>' % ( roleID, role.strip() )) return firstHalf + ' / '.join(newRoles) + mo.group(3) _reRolesMovie = re.compile(r'(<td class="character">)(.*?)(</td>)', re.I | re.M | re.S) def makeSplitter(lstrip=None, sep='|', comments=True, origNotesSep=' (', newNotesSep='::(', strip=None): """Return a splitter function suitable for a given set of data.""" def splitter(x): if not x: return x x = x.strip() if not x: return x if lstrip is not None: x = x.lstrip(lstrip).lstrip() lx = x.split(sep) lx[:] = [_f for _f in [j.strip() for j in lx] if _f] if comments: lx[:] = [j.replace(origNotesSep, newNotesSep, 1) for j in lx] if strip: lx[:] = [j.strip(strip) for j in lx] return lx return splitter def _toInt(val, replace=()): """Return the value, converted to integer, or None; if present, 'replace' must be a list of tuples of values to replace.""" for before, after in replace: val = val.replace(before, after) try: return int(val) except (TypeError, ValueError): return None _re_og_title = re.compile( r'(.*) \((?:(?:(.+)(?= ))? ?(\d{4})(?:(–)(\d{4}| ))?|(.+))\)', re.UNICODE ) def special_kind(og_title): specialKind = re.compile(r"\n(.*)").findall(og_title) if len(specialKind): return specialKind[0].strip() return None def analyze_og_title(og_title): data = {} og_kind = special_kind(og_title) match = _re_og_title.match(og_title) if og_title and not match: # assume it's a title in production, missing release date information return {'title': og_title} data['title'] = match.group(1) if match.group(3): data['year'] = int(match.group(3)) kind = match.group(2) or match.group(6) if kind is None: if og_kind is None: kind = 'movie' else: kind = og_kind.lower() else: kind = kind.lower() kind = KIND_MAP.get(kind, kind) data['kind'] = kind year_separator = match.group(4) # There is a year separator so assume an ongoing or ended series if year_separator is not None: end_year = match.group(5) if end_year is not None: data['series years'] = '%(year)d-%(end_year)s' % { 'year': data['year'], 'end_year': end_year.strip(), } elif kind.endswith('series'): data['series years'] = '%(year)d-' % {'year': data['year']} # No year separator and series, so assume that it ended the same year elif kind.endswith('series') and 'year' in data: data['series years'] = '%(year)d-%(year)d' % {'year': data['year']} if data['kind'] == 'episode' and data['title'][0] == '"': quote_end = data['title'].find('"', 1) data['tv series title'] = data['title'][1:quote_end] data['title'] = data['title'][quote_end + 1:].strip() return data def analyze_certificates(certificates): def reducer(acc, el): cert_re = re.compile(r'^(.+):(.+)$', re.UNICODE) if cert_re.match(el): acc.append(el) elif acc: acc[-1] = u'{}::{}'.format( acc[-1], el, ) return acc certificates = [el.strip() for el in certificates.split('\n') if el.strip()] return functools.reduce(reducer, certificates, []) def clean_akas(aka): aka = re_space.sub(' ', aka).strip() if aka.lower().startswith('see more'): aka = '' return aka class DOMHTMLMovieParser(DOMParserBase): """Parser for the "reference" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: mparser = DOMHTMLMovieParser() result = mparser.parse(reference_html_string) """ _containsObjects = True rules = [ Rule( key='title', extractor=Path('//meta[@property="og:title"]/@content|//*[@id="main"]/section/div/div/ul[1]/li[5]/text()', transform=analyze_og_title) ), Rule( key='alternative kind', extractor=Path('//h3[@itemprop="name"]/following-sibling::ul/li[last()]/text()', transform=lambda x: KIND_MAP.get(x.strip().lower(), x.strip().lower())) ), Rule( key='original title', extractor=Path('//div[@class="titlereference-header"]//span[@class="titlereference-original-title-label"]/preceding-sibling::text()', # noqa: E501 transform=lambda x: re_space.sub(' ', x).strip()) ), Rule( key='original title title-year', extractor=Path('//div[@class="titlereference-header"]//span[@class="titlereference-title-year"]/preceding-sibling::text()', # noqa: E501 transform=lambda x: re_space.sub(' ', x).strip()) ), Rule( key='localized title', extractor=Path('//meta[@name="title"]/@content', transform=lambda x: analyze_og_title(x).get('title')) ), Rule( key="stars", extractor=Path( foreach='//div[@class="titlereference-overview-section" and ' 'contains(text(), "Stars:")]/ul/li[1]/a', path='./text()') ), # parser for misc sections like 'casting department', 'stunts', ... Rule( key='misc sections', extractor=Rules( foreach='//h4[contains(@class, "ipl-header__content")]', rules=[ Rule( key=Path('./@name', transform=clean_section_name), extractor=Rules( foreach='../../following-sibling::table[1]//tr', rules=[ Rule( key='person', extractor=Path('.//text()') ), Rule( key='link', extractor=Path('./td[1]/a[@href]/@href') ) ], transform=lambda x: build_person( x.get('person') or '', personID=analyze_imdbid(x.get('link')) ) ) ) ] ) ), Rule( key='cast', extractor=Rules( foreach='//table[@class="cast_list"]//tr', rules=[ Rule( key='person', extractor=Path('.//text()') ), Rule( key='link', extractor=Path('./td[2]/a/@href') ), Rule( key='roleID', extractor=Path('./td[4]//div[@class="_imdbpyrole"]/@roleid') ) ], transform=lambda x: build_person( x.get('person') or '', personID=analyze_imdbid(x.get('link')), roleID=(x.get('roleID') or '').split('/') ) ) ), Rule( key='recommendations', extractor=Rules( foreach='//div[contains(@class, "rec_item")]', rules=[ Rule( key='movieID', extractor=Path( './@data-tconst', transform=lambda x: (x or '').replace('tt', '') ) ), Rule( key='title', extractor=Path( './/a//img/@title', transform=lambda x: re_space.sub(' ', x or '').strip() ) ), ], transform=lambda x: build_movie(x.get('title', ''), movieID=x.get('movieID')) ) ), Rule( key='myrating', extractor=Path('//span[@id="voteuser"]//text()') ), Rule( key='plot summary', extractor=Path('//td[starts-with(text(), "Plot")]/..//p/text()', transform=lambda x: x.strip().rstrip('|').rstrip()) ), Rule( key='genres', extractor=Path( foreach='//td[starts-with(text(), "Genre")]/..//li/a', path='./text()' ) ), Rule( key='runtimes', extractor=Path( foreach='//td[starts-with(text(), "Runtime")]/..//li', path='./text()', transform=lambda x: x.strip().replace(' min', '') ) ), Rule( key='countries', extractor=Path( foreach='//td[starts-with(text(), "Countr")]/..//li/a', path='./text()' ) ), Rule( key='country codes', extractor=Path( foreach='//td[starts-with(text(), "Countr")]/..//li/a', path='./@href', transform=lambda x: x.split('/')[2].strip().lower() ) ), Rule( key='language', extractor=Path( foreach='//td[starts-with(text(), "Language")]/..//li/a', path='./text()' ) ), Rule( key='language codes', extractor=Path( foreach='//td[starts-with(text(), "Language")]/..//li/a', path='./@href', transform=lambda x: x.split('/')[2].strip() ) ), Rule( key='color info', extractor=Path( foreach='//td[starts-with(text(), "Color")]/..//li/a', path='./text()', transform=lambda x: x.replace(' (', '::(') ) ), Rule( key='aspect ratio', extractor=Path( '//td[starts-with(text(), "Aspect")]/..//li/text()', transform=transformers.strip ) ), Rule( key='sound mix', extractor=Path( foreach='//td[starts-with(text(), "Sound Mix")]/..//li/a', path='./text()', transform=lambda x: x.replace(' (', '::(') ) ), Rule( key='box office', extractor=Rules( foreach='//section[contains(@class, "titlereference-section-box-office")]' '//table[contains(@class, "titlereference-list")]//tr', rules=[ Rule( key='box_office_title', extractor=Path('./td[1]/text()') ), Rule( key='box_office_detail', extractor=Path('./td[2]/text()') ) ], transform=lambda x: (x['box_office_title'].strip(), x['box_office_detail'].strip()) ), ), Rule( key='certificates', extractor=Path( '//td[starts-with(text(), "Certificat")]/..//text()', transform=analyze_certificates ) ), # Collects akas not encosed in <i> tags. Rule( key='other akas', extractor=Path( foreach='//section[contains(@class, "listo")]//td[starts-with(text(), "Also Known As")]/..//ul/li', path='.//text()', transform=clean_akas ) ), Rule( key='creator', extractor=Rules( foreach='//div[starts-with(normalize-space(text()), "Creator")]/ul/li[1]/a', rules=[ Rule( key='name', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ) ], transform=lambda x: build_person( x.get('name') or '', personID=analyze_imdbid(x.get('link')) ) ) ), Rule( key='thin writer', extractor=Rules( foreach='//div[starts-with(normalize-space(text()), "Writer")]/ul/li[1]/a', rules=[ Rule( key='name', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ) ], transform=lambda x: build_person( x.get('name') or '', personID=analyze_imdbid(x.get('link')) ) ) ), Rule( key='thin director', extractor=Rules( foreach='//div[starts-with(normalize-space(text()), "Director")]/ul/li[1]/a', rules=[ Rule( key='name', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ) ], transform=lambda x: build_person( x.get('name') or '', personID=analyze_imdbid(x.get('link')) ) ) ), Rule( key='top/bottom rank', extractor=Path( '//li[@class="ipl-inline-list__item"]//a[starts-with(@href, "/chart/")]/text()' ) ), Rule( key='original air date', extractor=Path('//span[@imdbpy="airdate"]/text()') ), Rule( key='series years', extractor=Path( '//div[@id="tn15title"]//span[starts-with(text(), "TV series")]/text()', transform=lambda x: x.replace('TV series', '').strip() ) ), Rule( key='season/episode', extractor=Path( '//div[@class="titlereference-overview-season-episode-section"]/ul//text()', transform=transformers.strip ) ), Rule( key='number of episodes', extractor=Path( '//a[starts-with(text(), "All Episodes")]/text()', transform=lambda x: int(x.replace('All Episodes', '').strip()[1:-1]) ) ), Rule( key='episode number', extractor=Path( '//div[@id="tn15epnav"]/text()', transform=lambda x: int(re.sub(r'[^a-z0-9 ]', '', x.lower()).strip().split()[0])) ), Rule( key='previous episode', extractor=Path( '//span[@class="titlereference-overview-episodes-links"]' '//a[contains(text(), "Previous")]/@href', transform=analyze_imdbid ) ), Rule( key='next episode', extractor=Path( '//span[@class="titlereference-overview-episodes-links"]' '//a[contains(text(), "Next")]/@href', transform=analyze_imdbid ) ), Rule( key='number of seasons', extractor=Path( '//span[@class="titlereference-overview-years-links"]/../a[1]/text()', transform=int ) ), Rule( key='tv series link', extractor=Path('//a[starts-with(text(), "All Episodes")]/@href') ), Rule( key='akas', extractor=Path( foreach='//i[@class="transl"]', path='./text()', transform=lambda x: x.replace(' ', ' ') .rstrip('-') .replace('" - ', '"::', 1) .strip('"') .replace(' ', ' ') ) ), Rule( key='production status', extractor=Path( '//td[starts-with(text(), "Status:")]/../td[2]/text()', transform=lambda x: x.strip().split('|')[0].strip().lower() ) ), Rule( key='production status updated', extractor=Path( '//td[starts-with(text(), "Status Updated:")]/' '..//td[2]/text()', transform=transformers.strip ) ), Rule( key='production comments', extractor=Path( '//td[starts-with(text(), "Comments:")]/' '..//td[2]/text()', transform=transformers.strip ) ), Rule( key='production note', extractor=Path( '//td[starts-with(text(), "Note:")]/' '..//td[2]/text()', transform=transformers.strip ) ), Rule( key='companies', extractor=Rules( foreach="//ul[@class='simpleList']", rules=[ Rule( key=Path('preceding-sibling::header[1]/div/h4/text()', transform=transformers.lower), extractor=Rules( foreach='./li', rules=[ Rule( key='name', extractor=Path('./a//text()') ), Rule( key='comp-link', extractor=Path('./a/@href') ), Rule( key='notes', extractor=Path('./text()') ) ], transform=lambda x: Company( name=x.get('name') or '', accessSystem='http', companyID=analyze_imdbid(x.get('comp-link')), notes=(x.get('notes') or '').strip() ) ) ) ] ) ), Rule( key='rating', extractor=Path('(//span[@class="ipl-rating-star__rating"])[1]/text()') ), Rule( key='votes', extractor=Path('//span[@class="ipl-rating-star__total-votes"][1]/text()') ), Rule( key='cover url', extractor=Path('//img[@alt="Poster"]/@src') ), Rule( key='imdbID', extractor=Path('//meta[@property="pageId"]/@content', transform=lambda x: (x or '').replace('tt', '')) ), Rule( key='videos', extractor=Path(foreach='//div[@class="mediastrip_big"]//a', path='./@href', transform=lambda x: 'http://www.imdb.com' + x) ) ] preprocessors = [ ('/releaseinfo">', '"><span imdbpy="airdate">'), (re.compile(r'(<b class="blackcatheader">.+?</b>)', re.I), r'</div><div>\1'), ('<small>Full cast and crew for<br>', ''), ('<td> </td>', '<td>...</td>'), (re.compile(r'<span class="tv-extra">TV mini-series(\s+.*?)</span>', re.I), r'<span class="tv-extra">TV series\1</span> (mini)'), (_reRolesMovie, _manageRoles) ] def preprocess_dom(self, dom): # Handle series information. xpath = self.xpath(dom, "//b[text()='Series Crew']") if xpath: b = xpath[-1] # In doubt, take the last one. for a in self.xpath(b, "./following::h5/a[@class='glossary']"): name = a.get('name') if name: a.set('name', 'series %s' % name) # Remove links to IMDbPro. preprocessors.remove(dom, '//span[@class="pro-link"]') # Remove some 'more' links (keep others, like the one around # the number of votes). preprocessors.remove(dom, '//a[@class="tn15more"][starts-with(@href, "/title/")]') # Remove the "rest of list" in cast. preprocessors.remove(dom, '//td[@colspan="4"]/..') return dom re_space = re.compile(r'\s+') re_airdate = re.compile(r'(.*)\s*\(season (\d+), episode (\d+)\)', re.I) def postprocess_data(self, data): # Convert section names. for sect in list(data.keys()): if sect in _SECT_CONV: data[_SECT_CONV[sect]] = data[sect] del data[sect] # Filter out fake values. for key in data: value = data[key] if isinstance(value, list) and value: if isinstance(value[0], Person): data[key] = [x for x in value if x.personID is not None] if isinstance(value[0], _Container): for obj in data[key]: obj.accessSystem = self._as obj.modFunct = self._modFunct for key in ['title']: if (key in data) and isinstance(data[key], dict): subdata = data[key] del data[key] data.update(subdata) if not data.get('original title'): if 'original title title-year' in data: data['original title'] = data['original title title-year'] del data['original title title-year'] elif 'original title title-year' in data: del data['original title title-year'] misc_sections = data.get('misc sections') if misc_sections is not None: for section in misc_sections: # skip sections with their own parsers if 'cast' in section.keys(): continue data.update(section) del data['misc sections'] if 'akas' in data or 'other akas' in data: akas = data.get('akas') or [] other_akas = data.get('other akas') or [] akas += other_akas nakas = [] for aka in akas: aka = aka.strip() if not aka: continue if aka.endswith('" -'): aka = aka[:-3].rstrip() nakas.append(aka) if 'akas' in data: del data['akas'] if 'other akas' in data: del data['other akas'] if nakas: data['akas'] = nakas if 'runtimes' in data: data['runtimes'] = [x.replace(' min', '') for x in data['runtimes']] if 'number of seasons' in data: data['seasons'] = [str(i) for i in range(1, data['number of seasons'] + 1)] if 'season/episode' in data: tokens = data['season/episode'].split('Episode') try: data['season'] = int(tokens[0].split('Season')[1]) except: data['season'] = 'unknown' try: data['episode'] = int(tokens[1]) except: data['episode'] = 'unknown' del data['season/episode'] for k in ('writer', 'director'): t_k = 'thin %s' % k if t_k not in data: continue if k not in data: data[k] = data[t_k] del data[t_k] if 'top/bottom rank' in data: tbVal = data['top/bottom rank'].lower() if tbVal.startswith('top'): tbKey = 'top 250 rank' tbVal = _toInt(tbVal, [('top rated movies: #', '')]) else: tbKey = 'bottom 100 rank' tbVal = _toInt(tbVal, [('bottom rated movies: #', '')]) if tbVal: data[tbKey] = tbVal del data['top/bottom rank'] if 'year' in data and data['year'] == '????': del data['year'] if 'tv series link' in data: if 'tv series title' in data: data['episode of'] = Movie(title=data['tv series title'], movieID=analyze_imdbid(data['tv series link']), accessSystem=self._as, modFunct=self._modFunct) data['episode of']['kind'] = 'tv series' del data['tv series title'] del data['tv series link'] if 'rating' in data: try: data['rating'] = float(data['rating'].replace('/10', '').replace(',', '.')) except (TypeError, ValueError): pass if data['rating'] == 0: del data['rating'] if 'votes' in data: try: votes = data['votes'].replace('(', '').replace(')', '').replace(',', '').replace('votes', '') data['votes'] = int(votes) except (TypeError, ValueError): pass companies = data.get('companies') if companies: for section in companies: for key, value in section.items(): if key in data: key = '%s companies' % key data.update({key: value}) del data['companies'] if 'box office' in data: data['box office'] = dict(data['box office']) alt_kind = data.get('alternative kind') if alt_kind is not None: data['kind'] = alt_kind return data def _process_plotsummary(x): """Process a plot (contributed by Rdian06).""" xauthor = x.get('author') xplot = x.get('plot', '').strip() if xauthor: xplot += '::%s' % xauthor return xplot class DOMHTMLPlotParser(DOMParserBase): """Parser for the "plot summary" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a 'plot' key, containing a list of string with the structure: 'summary::summary_author <author@email>'. Example:: pparser = HTMLPlotParser() result = pparser.parse(plot_summary_html_string) """ _defGetRefs = True # Notice that recently IMDb started to put the email of the # author only in the link, that we're not collecting, here. rules = [ Rule( key='plot', extractor=Rules( foreach='//div[@data-testid="sub-section-summaries"]//li', rules=[ Rule( key='plot', extractor=Path('.//text()') ), ], transform=_process_plotsummary ) ), Rule( key='synopsis', extractor=Path( foreach='//div[@data-testid="sub-section-synopsis"]//li', path='.//text()' ) ) ] def preprocess_dom(self, dom): preprocessors.remove(dom, '//li[@id="no-summary-content"]') return dom def postprocess_data(self, data): if 'synopsis' in data and data['synopsis'][0] and 'a Synopsis for this title' in data['synopsis'][0]: del data['synopsis'] return data def _process_award(x): award = {} _award = x.get('award') if _award is not None: _award = _award.strip() award['award'] = _award if not award['award']: return {} award['year'] = x.get('year').strip() if award['year'] and award['year'].isdigit(): award['year'] = int(award['year']) award['result'] = x.get('result').strip() category = x.get('category').strip() if category: award['category'] = category received_with = x.get('with') if received_with is not None: award['with'] = received_with.strip() notes = x.get('notes') if notes is not None: notes = notes.strip().split('\n', 2)[0] notes = re_space.sub(' ', notes) if notes: award['notes'] = notes award['anchor'] = x.get('anchor') return award class DOMHTMLAwardsParser(DOMParserBase): """Parser for the "awards" page of a given person or movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: awparser = HTMLAwardsParser() result = awparser.parse(awards_html_string) """ subject = 'title' _containsObjects = True rules = [ Rule( key='awards', extractor=Rules( foreach='//*[@id="main"]/div[1]/div/table//tr', rules=[ Rule( key='year', extractor=Path('normalize-space(./ancestor::table/preceding-sibling::*[1]/a/text())') ), Rule( key='result', extractor=Path('./td[1]/b/text()') ), Rule( key='award', extractor=Path('./td[1]/span/text()') ), Rule( key='category', extractor=Path('normalize-space(./ancestor::table/preceding-sibling::*[1]/text())') ), Rule( key='notes', extractor=Path('./td[2]/text()') ), Rule( key='anchor', extractor=Path('.//text()') ) ], transform=_process_award ) ), Rule( key='recipients', extractor=Rules( foreach='//*[@id="main"]/div[1]/div/table//tr/td[2]/a', rules=[ Rule( key='name', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ), Rule( key='anchor', extractor=Path('./ancestor::tr//text()') ) ] ) ) ] preprocessors = [ (re.compile('(<tr><td[^>]*>.*?</td></tr>\n\n</table>)', re.I), r'\1</table>'), (re.compile('(<tr><td[^>]*>\n\n<big>.*?</big></td></tr>)', re.I), r'</table><table class="_imdbpy">\1'), (re.compile('(<table[^>]*>\n\n)</table>(<table)', re.I), r'\1\2'), (re.compile('(<small>.*?)<br>(.*?</small)', re.I), r'\1 \2'), (re.compile('(</tr>\n\n)(<td)', re.I), r'\1<tr>\2') ] def preprocess_dom(self, dom): """Repeat td elements according to their rowspan attributes in subsequent tr elements. """ cols = self.xpath(dom, "//td[@rowspan]") for col in cols: span = int(col.get('rowspan')) del col.attrib['rowspan'] position = len(self.xpath(col, "./preceding-sibling::td")) row = col.getparent() for tr in self.xpath(row, "./following-sibling::tr")[:span - 1]: # if not cloned, child will be moved to new parent clone = self.clone(col) tr.insert(position, clone) return dom def postprocess_data(self, data): if len(data) == 0: return {} nd = [] for award in data['awards']: matches = [p for p in data.get('recipients', []) if 'nm' in p.get('link') and award.get('anchor') == p.get('anchor')] if self.subject == 'title': recipients = [ Person(name=recipient['name'], personID=analyze_imdbid(recipient['link'])) for recipient in matches ] award['to'] = recipients elif self.subject == 'name': recipients = [ Movie(title=recipient['name'], movieID=analyze_imdbid(recipient['link'])) for recipient in matches ] award['for'] = recipients nd.append(award) if 'anchor' in award: del award['anchor'] return {'awards': nd} class DOMHTMLTaglinesParser(DOMParserBase): """Parser for the "taglines" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: tparser = DOMHTMLTaglinesParser() result = tparser.parse(taglines_html_string) """ rules = [ Rule( key='taglines', extractor=Path( foreach='//div[@class="ipc-html-content-inner-div"]', path='.//text()' ) ) ] def postprocess_data(self, data): if 'taglines' in data: data['taglines'] = [tagline.strip() for tagline in data['taglines']] return data class DOMHTMLKeywordsParser(DOMParserBase): """Parser for the "keywords" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: kwparser = DOMHTMLKeywordsParser() result = kwparser.parse(keywords_html_string) """ rules = [ Rule( key='keywords', extractor=Path( foreach='//td[@data-item-keyword]', path='./@data-item-keyword', transform=lambda x: x.lower().replace(' ', '-') ) ), Rule( key='relevant keywords', extractor=Rules( foreach='//td[@data-item-keyword]', rules=[ Rule( key='keyword', extractor=Path('./@data-item-keyword') ), Rule( key='ordering', extractor=Path('./@data-item-votes') ), Rule( key='vote_str', extractor=Path('./div[2]/div//text()') ) ], transform=lambda x: { 'keyword': x.get('keyword').lower(), 'keyword_dash': x.get('keyword').lower().replace(' ', '-'), 'ordering': x.get('ordering'), 'votes_str': x.get('vote_str').strip().lower() } ) ) ] def postprocess_data(self, data): if 'relevant keywords' in data: rk = [] for x in data['relevant keywords']: if 'votes_str' in x: if 'is this relevant?' in x['votes_str']: x['votes_for'] = 0 x['total_votes'] = 0 else: x['votes_for'] = x['votes_str'].split('of')[0].strip() x['total_votes'] = re.sub(r"\D", "", x['votes_str'].split('of')[1]).strip() rk.append(x) data['relevant keywords'] = rk return data class DOMHTMLAlternateVersionsParser(DOMParserBase): """Parser for the "alternate versions" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: avparser = DOMHTMLAlternateVersionsParser() result = avparser.parse(alternateversions_html_string) """ _defGetRefs = True rules = [ Rule( key='alternate versions', extractor=Path( foreach='//ul[@class="trivia"]/li', path='.//text()', transform=transformers.strip ) ) ] class DOMHTMLTriviaParser(DOMParserBase): """Parser for the "trivia" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: tparser = DOMHTMLTriviaParser() result = tparser.parse(trivia_html_string) """ _defGetRefs = True rules = [ Rule(key="trivia", extractor=Path(foreach='//div[@class="ipc-html-content-inner-div"]', path='.//text()')) ] class DOMHTMLSoundtrackParser(DOMParserBase): """Parser for the "soundtrack" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: stparser = DOMHTMLSoundtrackParser() result = stparser.parse(soundtrack_html_string) """ _defGetRefs = True preprocessors = [('<br />', '\n'), ('<br>', '\n')] rules = [ Rule( key='soundtrack', extractor=Path( foreach='//div[@class="list"]//div', path='.//text()', transform=transformers.strip ) ) ] def postprocess_data(self, data): if 'soundtrack' in data: nd = [] for x in data['soundtrack']: ds = x.split('\n') title = ds[0] if title[0] == '"' and title[-1] == '"': title = title[1:-1] nds = [] newData = {} for l in ds[1:]: if ' with ' in l or ' by ' in l or ' from ' in l \ or ' of ' in l or l.startswith('From '): nds.append(l) else: if nds: nds[-1] += l else: nds.append(l) newData[title] = {} for l in nds: skip = False for sep in ('From ',): if l.startswith(sep): fdix = len(sep) kind = l[:fdix].rstrip().lower() info = l[fdix:].lstrip() newData[title][kind] = info skip = True if not skip: for sep in ' with ', ' by ', ' from ', ' of ': fdix = l.find(sep) if fdix != -1: fdix = fdix + len(sep) kind = l[:fdix].rstrip().lower() info = l[fdix:].lstrip() newData[title][kind] = info break nd.append(newData) data['soundtrack'] = nd return data class DOMHTMLCrazyCreditsParser(DOMParserBase): """Parser for the "crazy credits" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: ccparser = DOMHTMLCrazyCreditsParser() result = ccparser.parse(crazycredits_html_string) """ _defGetRefs = True rules = [ Rule( key='crazy credits', extractor=Path( foreach='//ul/li/tt', path='.//text()', transform=lambda x: x.replace('\n', ' ').replace(' ', ' ') ) ) ] def _process_goof(x): text = (x.get('text') or '').strip() category = (x.get('category') or 'Goof').strip() return {"category": category, "text": text} class DOMHTMLGoofsParser(DOMParserBase): """Parser for the "goofs" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: gparser = DOMHTMLGoofsParser() result = gparser.parse(goofs_html_string) """ _defGetRefs = True rules = [ Rule( key='goofs', extractor=Rules( foreach='//div[contains(@class, "soda sodavote")]', rules=[ Rule( key='text', extractor=Path('./div[@class="sodatext"]/text()') ), Rule( key='category', extractor=Path('./preceding-sibling::h4[1]/text()') ) ], transform=_process_goof ) ) ] class DOMHTMLQuotesParser(DOMParserBase): """Parser for the "memorable quotes" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: qparser = DOMHTMLQuotesParser() result = qparser.parse(quotes_html_string) """ _defGetRefs = True rules = [ Rule( key='quotes', extractor=Path( foreach='//div[@class="sodatext"]', path='.//text()', transform=lambda x: x.strip() .replace(' \n', '::') .replace('::\n', '::') .replace('\n', ' ') ) ) ] def preprocess_dom(self, dom): preprocessors.remove(dom, '//div[@class="did-you-know-actions"]') return dom def postprocess_data(self, data): quotes = data.get('quotes', []) if not quotes: return {} quotes = [q.split('::') for q in quotes] return {'quotes': quotes} class DOMHTMLReleaseinfoParser(DOMParserBase): """Parser for the "release dates" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: rdparser = DOMHTMLReleaseinfoParser() result = rdparser.parse(releaseinfo_html_string) """ rules = [ Rule( key='release dates', extractor=Rules( foreach='//table[contains(@class, "release-dates-table-test-only")]//tr', rules=[ Rule( key='country', extractor=Path('.//td[1]//text()') ), Rule( key='country_code', extractor=Path('.//td[1]/a/@href') ), Rule( key='date', extractor=Path('.//td[2]//text()') ), Rule( key='notes', extractor=Path('.//td[3]//text()') ) ] ) ), Rule( key='akas', extractor=Rules( foreach='//table[contains(@class, "akas-table-test-only")]//tr', rules=[ Rule( key='countries', extractor=Path('./td[1]/text()') ), Rule( key='title', extractor=Path('./td[2]/text()') ) ] ) ) ] preprocessors = [ (re.compile('(<h5><a name="?akas"?.*</table>)', re.I | re.M | re.S), r'<div class="_imdbpy_akas">\1</div>') ] def postprocess_data(self, data): if not ('release dates' in data or 'akas' in data): return data releases = data.get('release dates') or [] rl = [] for i in releases: country = i.get('country') date = i.get('date') if not (country and date): continue country = country.strip() date = date.strip() if not (country and date): continue notes = i.get('notes') info = '%s::%s' % (country, date) if notes: notes = notes.replace('\n', '') i['notes'] = notes info += notes rl.append(info) if releases: for rd in data['release dates']: rd['country_code'] = rd['country_code'].split('region=')[1].split('&')[0].strip().upper() data['raw release dates'] = data['release dates'] del data['release dates'] if rl: data['release dates'] = rl akas = data.get('akas') or [] nakas = [] for aka in akas: title = (aka.get('title') or '').strip() if not title: continue countries = (aka.get('countries') or '').split(',') if not countries: nakas.append(title) else: for country in countries: nakas.append('%s %s' % (title, country.strip())) if akas: if releases: for rd in data['raw release dates']: for a in data['akas']: if 'countries' in a: if rd['country'].strip() in a['countries'].strip(): a['country_code'] = rd['country_code'] data['raw akas'] = data['akas'] del data['akas'] if nakas: data['akas'] = data['akas from release info'] = nakas return data class DOMHTMLRatingsParser(DOMParserBase): """Parser for the "user ratings" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: rparser = DOMHTMLRatingsParser() result = rparser.parse(userratings_html_string) """ re_means = re.compile(r'mean\s*=\s*([0-9]\.[0-9])\s*median\s*=\s*([0-9])', re.I) rules = [ Rule( key='votes', extractor=Rules( foreach='//th[@class="firstTableCoulmn"]/../../tr', rules=[ Rule( key='ordinal', extractor=Path('./td[1]/div//text()') ), Rule( key='votes', extractor=Path('./td[3]/div/div//text()') ) ] ) ), Rule( key='mean and median', extractor=Path( '//div[starts-with(normalize-space(text()), "Arithmetic mean")]/text()' ) ), Rule( key='demographics', extractor=Rules( foreach='//div[@class="smallcell"]', rules=[ Rule( key='link', extractor=Path('./a/@href') ), Rule( key='rating', extractor=Path('..//div[@class="bigcell"]//text()') ), Rule( key='votes', extractor=Path('./a/text()') ) ] ) ) ] def postprocess_data(self, data): nd = {} demographics = data.get('demographics') if demographics: dem = {} for dem_data in demographics: link = (dem_data.get('link') or '').strip() votes = (dem_data.get('votes') or '').strip() rating = (dem_data.get('rating') or '').strip() if not (link and votes and rating): continue eq_idx = link.rfind('=') if eq_idx == -1: continue info = link[eq_idx + 1:].replace('_', ' ') try: votes = int(votes.replace(',', '')) except Exception: continue try: rating = float(rating) except Exception: continue dem[info] = {'votes': votes, 'rating': rating} nd['demographics'] = dem votes = data.get('votes', []) if votes: nd['number of votes'] = {} for v_info in votes: ordinal = v_info.get('ordinal') nr_votes = v_info.get('votes') if not (ordinal and nr_votes): continue try: ordinal = int(ordinal) except Exception: continue try: nr_votes = int(nr_votes.replace(',', '')) except Exception: continue nd['number of votes'][ordinal] = nr_votes mean = data.get('mean and median', '') if mean: means = self.re_means.findall(mean) if means and len(means[0]) == 2: am, med = means[0] try: am = float(am) except (ValueError, OverflowError): pass if isinstance(am, float): nd['arithmetic mean'] = am try: med = int(med) except (ValueError, OverflowError): pass if isinstance(med, int): nd['median'] = med return nd def _normalize_href(href): if (href is not None) and (not href.lower().startswith('http://')): if href.startswith('/'): href = href[1:] # TODO: imdbURL_base may be set by the user! href = '%s%s' % (imdbURL_base, href) return href class DOMHTMLCriticReviewsParser(DOMParserBase): """Parser for the "critic reviews" pages of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: crparser = DOMHTMLCriticReviewsParser() result = crparser.parse(criticreviews_html_string) """ kind = 'critic reviews' rules = [ Rule( key='metascore', extractor=Path('//*[@data-testid="critic-reviews-title"]/div/text()', transform=lambda x: int(x.strip())) ), Rule( key='metacritic url', extractor=Path('//*[@data-testid="critic-reviews-title"]/div[2]/div[2]/a/@href') ) ] class DOMHTMLReviewsParser(DOMParserBase): """Parser for the "reviews" pages of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: rparser = DOMHTMLReviewsParser() result = rparser.parse(reviews_html_string) """ rules = [ Rule( key='reviews', extractor=Rules( foreach='//div[@class="review-container"]', rules=[ Rule( key='text', extractor=Path('.//div[@class="text show-more__control"]//text()') ), Rule( key='helpful', extractor=Path('.//div[@class="actions text-muted"]//text()[1]') ), Rule( key='title', extractor=Path('.//a[@class="title"]//text()') ), Rule( key='author', extractor=Path('.//span[@class="display-name-link"]/a/@href') ), Rule( key='date', extractor=Path('.//span[@class="review-date"]//text()') ), Rule( key='rating', extractor=Path('.//span[@class="point-scale"]/preceding-sibling::span[1]/text()') ) ], transform=lambda x: ({ 'content': x.get('text', '').replace('\n', ' ').replace(' ', ' ').strip(), 'helpful': [int(s) for s in x.get('helpful', '').split() if s.isdigit()], 'title': x.get('title', '').strip(), 'author': analyze_imdbid(x.get('author')), 'date': x.get('date', '').strip(), 'rating': x.get('rating', '').strip() }) ) ) ] preprocessors = [('<br>', '<br>\n')] def postprocess_data(self, data): for review in data.get('reviews', []): if review.get('rating'): if isinstance(review['rating'], str): review['rating'] = int(review['rating']) elif len(review['rating']) == 2: # May be legacy code. review['rating'] = int(review['rating'][0]) else: review['rating'] = None else: review['rating'] = None if review.get('helpful') and len(review['helpful']) == 2: review['not_helpful'] = review['helpful'][1] - review['helpful'][0] review['helpful'] = review['helpful'][0] else: review['helpful'] = 0 review['not_helpful'] = 0 review['author'] = "ur%s" % review['author'] return data class DOMHTMLFullCreditsParser(DOMParserBase): """Parser for the "full credits" (series cast section) page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: fcparser = DOMHTMLFullCreditsParser() result = fcparser.parse(fullcredits_html_string) """ kind = 'full credits' rules = [ Rule( key='cast', extractor=Rules( foreach='//table[@class="cast_list"]//tr[@class="odd" or @class="even"]', rules=[ Rule( key='person', extractor=Path('.//text()') ), Rule( key='link', extractor=Path('./td[2]/a/@href') ), Rule( key='roleID', extractor=Path('./td[4]//div[@class="_imdbpyrole"]/@roleid') ), Rule( key='headshot', extractor=Path('./td[@class="primary_photo"]/a/img/@loadlate') ) ], transform=lambda x: build_person( x.get('person', ''), personID=analyze_imdbid(x.get('link')), roleID=(x.get('roleID', '')).split('/'), headshot=(x.get('headshot', '')) ) ) ), # parser for misc sections like 'casting department', 'stunts', ... Rule( key='misc sections', extractor=Rules( foreach='//h4[contains(@class, "dataHeaderWithBorder")]', rules=[ Rule( key=Path('./@name', transform=clean_section_name), extractor=Rules( foreach='./following-sibling::table[1]//tr', rules=[ Rule( key='person', extractor=Path('.//text()') ), Rule( key='link', extractor=Path('./td[1]/a[@href]/@href') ) ], transform=lambda x: build_person( x.get('person') or '', personID=analyze_imdbid(x.get('link')) ) ) ) ] ) ), ] preprocessors = [ (_reRolesMovie, _manageRoles) ] def postprocess_data(self, data): # Convert section names. clean_cast = [] for person in data.get('cast', []): if person.personID and person.get('name'): clean_cast.append(person) if clean_cast: data['cast'] = clean_cast misc_sections = data.get('misc sections') if misc_sections is not None: for section in misc_sections: for sectName, sectData in section.items(): # skip sections with their own parsers if sectName in ('cast',): continue newName = _SECT_CONV.get(sectName, sectName) if sectData: data[newName] = sectData del data['misc sections'] return data class DOMHTMLOfficialsitesParser(DOMParserBase): """Parser for the "official sites", "external reviews" "miscellaneous links", "sound clips", "video clips" and "photographs" pages of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: osparser = DOMHTMLOfficialsitesParser() result = osparser.parse(officialsites_html_string) """ rules = [ Rule( foreach='//div[contains(@class, "ipc-page-grid__item")]/section[contains(@class, "ipc-page-section--base")]', # noqa: E501 key=Path( './/h3//text()', transform=lambda x: x.strip().lower() ), extractor=Rules( foreach='.//ul[1]//li//a[1]', rules=[ Rule( key='link', extractor=Path('./@href') ), Rule( key='info', extractor=Path('.//text()') ) ], transform=lambda x: ( x.get('info', '').strip(), unquote(x.get('link')) ) ) ) ] class DOMHTMLConnectionsParser(DOMParserBase): """Parser for the "connections" pages of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: osparser = DOMHTMLOfficialsitesParser() result = osparser.parse(officialsites_html_string) """ rules = [ Rule( foreach='//div[contains(@class, "ipc-page-grid__item")]/section[contains(@class, "ipc-page-section--base")]', # noqa: E501 key=Path( './div[1]//h3//text()', transform=lambda x: (x or '').strip().lower() ), extractor=Rules( foreach='./div[2]//ul[1]//li', rules=[ Rule( key='link', extractor=Path('./div[1]//p//a/@href') ), Rule( key='info', extractor=Path('./div[1]//p//text()') ) ], transform=lambda x: ( x.get('info', '').strip(), unquote(_normalize_href(x.get('link', ''))) ) ) ) ] def postprocess_data(self, data): connections = {} for k, v in data.items(): k = k.strip() if not (k and v): continue movies = [] for title, link in v: title = title.strip().replace('\n', '') movieID = analyze_imdbid(link) if not (title and movieID): continue movie = Movie(title=title, movieID=movieID, accessSystem=self._as, modFunct=self._modFunct) movies.append(movie) if movies: connections[k] = movies return {'connections': connections} class DOMHTMLLocationsParser(DOMParserBase): """Parser for the "locations" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: lparser = DOMHTMLLocationsParser() result = lparser.parse(locations_html_string) """ rules = [ Rule( key='locations', extractor=Rules( foreach='//dt', rules=[ Rule( key='place', extractor=Path('.//text()') ), Rule( key='note', extractor=Path('./following-sibling::dd[1]//text()') ) ], transform=lambda x: ('%s::%s' % (x['place'].strip(), (x['note'] or '').strip())).strip(':') ) ) ] class DOMHTMLTechParser(DOMParserBase): """Parser for the "technical", "publicity" (for people) and "contacts" (for people) pages of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: tparser = DOMHTMLTechParser() result = tparser.parse(technical_html_string) """ kind = 'tech' re_space = re.compile(r'\s+') rules = [ Rule( key='tech', extractor=Rules( foreach='//table//tr/td[@class="label"]', rules=[ Rule( key=Path( './text()', transform=lambda x: x.lower().strip()), extractor=Path( '..//td[2]//text()', transform=lambda x: [t.strip() for t in x.split(':::') if t.strip()] ) ) ] ) ) ] preprocessors = [ (re.compile('(<h5>.*?</h5>)', re.I), r'</div>\1<div class="_imdbpy">'), (re.compile('((<br/>|</p>|</table>))\n?<br/>(?!<a)', re.I), r'\1</div>'), # the ones below are for the publicity parser (re.compile('<p>(.*?)</p>', re.I), r'\1<br/>'), (re.compile('(</td><td valign="top">)', re.I), r'\1::'), (re.compile('(</tr><tr>)', re.I), r'\n\1'), (re.compile(r'<span class="ghost">\|</span>', re.I), r':::'), (re.compile('<br/?>', re.I), r':::') # this is for splitting individual entries ] def postprocess_data(self, data): info = {} for section in data.get('tech', []): info.update(section) for key, value in info.items(): if isinstance(value, list): info[key] = [self.re_space.sub(' ', x).strip() for x in value] else: info[key] = self.re_space.sub(' ', value).strip() return {self.kind: info} class DOMHTMLNewsParser(DOMParserBase): """Parser for the "news" page of a given movie or person. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: nwparser = DOMHTMLNewsParser() result = nwparser.parse(news_html_string) """ _defGetRefs = True rules = [ Rule( key='news', extractor=Rules( foreach='//h2', rules=[ Rule( key='title', extractor=Path('./text()') ), Rule( key='fromdate', extractor=Path('./following-sibling::p[1]/small//text()') ), Rule( key='body', extractor=Path('../following-sibling::p[2]//text()') ), Rule( key='link', extractor=Path('../..//a[text()="Permalink"]/@href') ), Rule( key='fulllink', extractor=Path('../..//a[starts-with(text(), "See full article at")]/@href') ) ], transform=lambda x: { 'title': x.get('title').strip(), 'date': x.get('fromdate').split('|')[0].strip(), 'from': x.get('fromdate').split('|')[1].replace('From ', '').strip(), 'body': (x.get('body') or '').strip(), 'link': _normalize_href(x.get('link')), 'full article link': _normalize_href(x.get('fulllink')) } ) ) ] preprocessors = [ (re.compile('(<a name=[^>]+><h2>)', re.I), r'<div class="_imdbpy">\1'), (re.compile('(<hr/>)', re.I), r'</div>\1'), (re.compile('<p></p>', re.I), r'') ] def postprocess_data(self, data): if 'news' not in data: return {} for news in data['news']: if 'full article link' in news: if news['full article link'] is None: del news['full article link'] return data def _parse_review(x): result = {} title = x.get('title').strip() if title[-1] == ':': title = title[:-1] result['title'] = title result['link'] = _normalize_href(x.get('link')) kind = x.get('kind').strip() if kind[-1] == ':': kind = kind[:-1] result['review kind'] = kind text = x.get('review').replace('\n\n', '||').replace('\n', ' ').split('||') review = '\n'.join(text) if x.get('author') is not None: author = x.get('author').strip() review = review.split(author)[0].strip() result['review author'] = author[2:] if x.get('item') is not None: item = x.get('item').strip() review = review[len(item):].strip() review = "%s: %s" % (item, review) result['review'] = review return result MONTH_NUMS = {m: "%02d" % (n + 1) for n, m in enumerate(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])} class DOMHTMLSeasonEpisodesParser(DOMParserBase): """Parser for the "episode list" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: sparser = DOMHTMLSeasonEpisodesParser() result = sparser.parse(episodes_html_string) """ rules = [ Rule( key='series link', extractor=Path('.//div[@data-testid="poster"]//a/@href') ), Rule( key='series title', extractor=Path('//h2[@data-testid="subtitle"]/text()') ), Rule( key='_seasons', extractor=Path( foreach='//li[@data-testid="tab-season-entry"]', path='./text()' ) ), Rule( key='_current_season', extractor=Path('//li[@data-testid="tab-season-entry"][@aria-selected="true"]/text()') ), Rule( key='episodes', extractor=Rules( foreach='//h4', rules=[ Rule( key=Path('.//a//text()'), extractor=Rules( rules=[ Rule( key='link', extractor=Path('.//a/@href') ), Rule( key='original air date', extractor=Path('following-sibling::span/text()') ), Rule( key='rating', extractor=Path('../..//span[contains(@class, "ratingGroup--imdb-rating")]/text()') ), Rule( key='votes', extractor=Path('../..//span[contains(@class, "ipc-rating-star--voteCount")]/text()') ), Rule( key='plot', extractor=Path('../..//div[@role="presentation"]//text()') ) ] ) ) ] ) ) ] def postprocess_data(self, data): series_id = analyze_imdbid(data.get('series link')) series_title = data.get('series title', '').strip() selected_season = data.get('_current_season', 'unknown season').strip() if not (series_id and series_title): return {} series = Movie(title=series_title, movieID=str(series_id), accessSystem=self._as, modFunct=self._modFunct) if series.get('kind') == 'movie': series['kind'] = 'tv series' try: selected_season = int(selected_season) except ValueError: pass nd = {selected_season: {}} if 'episode -1' in data: counter = 1 for episode in data['episode -1']: while 'episode %d' % counter in data: counter += 1 k = 'episode %d' % counter data[k] = [episode] del data['episode -1'] episodes = data.get('episodes', []) for seq, ep in enumerate(episodes): if not ep: continue episode_nr_title, episode = list(ep.items())[0] nr_title_tokens = episode_nr_title.split(" ∙ ") if len(nr_title_tokens) == 2: episode_seq, episode_title = nr_title_tokens episode_nr = episode_seq.split(".")[1][1:] else: episode_nr, episode_title = seq + 1, nr_title_tokens[0] try: episode_nr = int(episode_nr) except ValueError: pass episode_id = analyze_imdbid(episode.get('link', '')) episode_air_date = episode.get('original air date', '').strip() episode_plot = episode.get('plot', '') episode_rating = episode.get('rating', '') episode_votes = episode.get('votes', '')[2:-1] # remove () if not (episode_nr is not None and episode_id and episode_title): continue ep_obj = Movie(movieID=episode_id, title=episode_title, accessSystem=self._as, modFunct=self._modFunct) ep_obj['kind'] = 'episode' ep_obj['episode of'] = series ep_obj['season'] = selected_season ep_obj['episode'] = episode_nr if episode_rating: try: ep_obj['rating'] = float(episode_rating) except: pass if episode_votes: try: if episode_votes[-1] == "K": ep_votes = int(float(episode_votes[:-1]) * 1000) elif episode_votes[-1] == "M": ep_votes = int(float(episode_votes[:-1]) * 1000000) else: ep_votes = int(episode_votes) ep_obj['votes'] = ep_votes except: pass if episode_air_date: if episode_air_date[-4:].isdigit(): year = episode_air_date[-4:] if episode_air_date.startswith(("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")): ep_month, ep_day = episode_air_date[5:].split(",")[0].split(" ") episode_air_date = year + "-" + MONTH_NUMS[ep_month] + "-" + "%02d" % int(ep_day) ep_obj['original air date'] = episode_air_date ep_obj['year'] = int(year) if episode_plot: ep_obj['plot'] = episode_plot nd[selected_season][episode_nr] = ep_obj _seasons = data.get('_seasons') or [] for idx, season in enumerate(_seasons): try: _seasons[idx] = int(season) except ValueError: pass return {'episodes': nd, '_seasons': _seasons, '_current_season': selected_season} def _build_episode(x): """Create a Movie object for a given series' episode.""" episode_id = analyze_imdbid(x.get('link')) episode_title = x.get('title') e = Movie(movieID=episode_id, title=episode_title) e['kind'] = 'episode' oad = x.get('oad') if oad: e['original air date'] = oad.strip() year = x.get('year') if year is not None: year = year[5:] if year == 'unknown': year = '????' if year and year.isdigit(): year = int(year) e['year'] = year else: if oad and oad[-4:].isdigit(): e['year'] = int(oad[-4:]) epinfo = x.get('episode') if epinfo is not None: season, episode = epinfo.split(':')[0].split(',') e['season'] = int(season[7:]) e['episode'] = int(episode[8:]) else: e['season'] = 'unknown' e['episode'] = 'unknown' plot = x.get('plot') if plot: e['plot'] = plot.strip() return e class DOMHTMLEpisodesParser(DOMParserBase): """Parser for the "episode list" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: eparser = DOMHTMLEpisodesParser() result = eparser.parse(episodes_html_string) """ kind = 'episodes list' _episodes_path = "..//h4" _oad_path = "./following-sibling::span/strong[1]/text()" def _init(self): self.rules = [ Rule( key='series title', extractor=Path('//title/text()') ), Rule( key='series movieID', extractor=Path( './/h1/a[@class="main"]/@href', transform=analyze_imdbid ) ), Rule( key='episodes', extractor=Rules( foreach='//div[@class="_imdbpy"]/h3', rules=[ Rule( key='./a/@name', extractor=Rules( foreach=self._episodes_path, rules=[ Rule( key='link', extractor=Path('./a/@href') ), Rule( key='title', extractor=Path('./a/text()') ), Rule( key='year', extractor=Path('./preceding-sibling::a[1]/@name') ), Rule( key='episode', extractor=Path('./text()[1]') ), Rule( key='oad', extractor=Path(self._oad_path) ), Rule( key='plot', extractor=Path('./following-sibling::text()[1]') ) ], transform=_build_episode ) ) ] ) ) ] preprocessors = [ (re.compile('(<hr/>\n)(<h3>)', re.I), r'</div>\1<div class="_imdbpy">\2'), (re.compile('(</p>\n\n)</div>', re.I), r'\1'), (re.compile('<h3>(.*?)</h3>', re.I), r'<h4>\1</h4>'), (_reRolesMovie, _manageRoles), (re.compile('(<br/> <br/>\n)(<hr/>)', re.I), r'\1</div>\2') ] def postprocess_data(self, data): # A bit extreme? if 'series title' not in data: return {} if 'series movieID' not in data: return {} stitle = data['series title'].replace('- Episode list', '') stitle = stitle.replace('- Episodes list', '') stitle = stitle.replace('- Episode cast', '') stitle = stitle.replace('- Episodes cast', '') stitle = stitle.strip() if not stitle: return {} seriesID = data['series movieID'] if seriesID is None: return {} series = Movie(title=stitle, movieID=str(seriesID), accessSystem=self._as, modFunct=self._modFunct) nd = {} for key in list(data.keys()): if key.startswith('filter-season-') or key.startswith('season-'): season_key = key.replace('filter-season-', '').replace('season-', '') try: season_key = int(season_key) except ValueError: pass nd[season_key] = {} ep_counter = 1 for episode in data[key]: if not episode: continue episode_key = episode.get('episode') if episode_key is None: continue if not isinstance(episode_key, int): episode_key = ep_counter ep_counter += 1 cast_key = 'Season %s, Episode %s:' % (season_key, episode_key) if cast_key in data: cast = data[cast_key] for i in range(len(cast)): cast[i].billingPos = i + 1 episode['cast'] = cast episode['episode of'] = series nd[season_key][episode_key] = episode if len(nd) == 0: return {} return {'episodes': nd} class DOMHTMLFaqsParser(DOMParserBase): """Parser for the "FAQ" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: fparser = DOMHTMLFaqsParser() result = fparser.parse(faqs_html_string) """ _defGetRefs = True rules = [ Rule( key='faqs', extractor=Rules( foreach='//div[@class="section"]', rules=[ Rule( key='question', extractor=Path('./h3/a/span/text()') ), Rule( key='answer', extractor=Path('../following-sibling::div[1]//text()') ) ], transform=lambda x: '%s::%s' % ( x.get('question').strip(), '\n\n'.join(x.get('answer').replace('\n\n', '\n').strip().split('||')) ) ) ) ] preprocessors = [ (re.compile('<br/><br/>', re.I), r'||'), (re.compile('<h4>(.*?)</h4>\n', re.I), r'||\1--'), (re.compile('<span class="spoiler"><span>(.*?)</span></span>', re.I), r'[spoiler]\1[/spoiler]') ] class DOMHTMLAiringParser(DOMParserBase): """Parser for the "airing" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: aparser = DOMHTMLAiringParser() result = aparser.parse(airing_html_string) """ _containsObjects = True rules = [ Rule( key='series title', extractor=Path( '//title/text()', transform=lambda x: x.replace(' - TV schedule', '') ) ), Rule( key='series id', extractor=Path('//h1/a[@href]/@href') ), Rule( key='tv airings', extractor=Rules( foreach='//tr[@class]', rules=[ Rule( key='date', extractor=Path('./td[1]//text()') ), Rule( key='time', extractor=Path('./td[2]//text()') ), Rule( key='channel', extractor=Path('./td[3]//text()') ), Rule( key='link', extractor=Path('./td[4]/a[1]/@href') ), Rule( key='title', extractor=Path('./td[4]//text()') ), Rule( key='season', extractor=Path('./td[5]//text()') ) ], transform=lambda x: { 'date': x.get('date'), 'time': x.get('time'), 'channel': x.get('channel').strip(), 'link': x.get('link'), 'title': x.get('title'), 'season': (x.get('season') or '').strip() } ) ) ] def postprocess_data(self, data): if len(data) == 0: return {} seriesTitle = data.get('series title') or '' seriesID = analyze_imdbid(data.get('series id')) if seriesID and 'airing' in data: for airing in data['airing']: title = airing.get('title', '').strip() if not title: epsTitle = seriesTitle if seriesID is None: continue epsID = seriesID else: epsTitle = '%s {%s}' % (data['series title'], airing['title']) epsID = analyze_imdbid(airing['link']) e = Movie(title=epsTitle, movieID=epsID) airing['episode'] = e del airing['link'] del airing['title'] if not airing['season']: del airing['season'] if 'series title' in data: del data['series title'] if 'series id' in data: del data['series id'] if 'airing' in data: data['airing'] = [_f for _f in data['airing'] if _f] if 'airing' not in data or not data['airing']: return {} return data class DOMHTMLParentsGuideParser(DOMParserBase): """Parser for the "parents guide" page of a given movie. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: pgparser = HTMLParentsGuideParser() result = pgparser.parse(parentsguide_html_string) """ rules = [ Rule( key='mpaa', extractor=Path( '//tr[@id="mpaa-rating"]/td[2]//text()' ) ), Rule( key='certificates', extractor=Rules( foreach='//tr[@id="certifications-list"]//li', rules=[ Rule( key='full', extractor=Path('./a//text()') ), Rule( key='country_code', extractor=Path('./a/@href') ), Rule( key='note', extractor=Path('./text()') ), ], transform=lambda x: { 'country_code': x.get('country_code').split('certificates=')[1].split(':')[0].strip(), 'country': x.get('full').split(':')[0].strip(), 'certificate': x.get('full').split(':')[1].strip(), 'note': x.get('note').strip(), 'full': x.get('full').strip(), } ) ), Rule( key='advisories', extractor=Rules( foreach='//section[starts-with(@id, "advisory-")]', rules=[ Rule( key='section', extractor=Path('./@id') ), Rule( key='items', extractor=Rules( foreach='.//li', rules=[ Rule( key='item', extractor=Path('./text()') ) ], transform=lambda x: x.get('item').strip() ) ) ] ) ), Rule( key='advisory votes', extractor=Rules( foreach='//section[starts-with(@id, "advisory-")][not(contains(@id, "advisory-spoiler"))]', rules=[ Rule(key='section', extractor=Path('./@id'), ), Rule(key='status', extractor=Path('.//li[1]//div[contains(@class, "ipl-swapper__content-primary")]//span/text()') ), Rule(key='votes', extractor=Path( foreach='.//li[1]//span[contains(@class, "ipl-vote-button__details")]', path='./text()', transform=lambda x: int(x.replace(',', '')) ) ) ] ) ) ] def postprocess_data(self, data): if 'advisories' in data: for advisory in data['advisories']: sect = advisory.get('section', '').replace('-', ' ') items = [x for x in advisory.get('items', []) if x] if sect and items: data[sect] = items del data['advisories'] if 'advisory votes' in data: advisory_votes = {} for vote in data['advisory votes']: if 'status' not in vote or 'votes' not in vote: continue advisory_votes[vote['section'][9:]] = { 'votes': { 'None': vote['votes'][0], 'Mild': vote['votes'][1], 'Moderate': vote['votes'][2], 'Severe': vote['votes'][3], }, 'status': vote['status'], } data['advisory votes'] = advisory_votes return data _OBJECTS = { 'movie_parser': ((DOMHTMLMovieParser,), None), 'full_credits_parser': ((DOMHTMLFullCreditsParser,), None), 'plot_parser': ((DOMHTMLPlotParser,), None), 'movie_awards_parser': ((DOMHTMLAwardsParser,), None), 'taglines_parser': ((DOMHTMLTaglinesParser,), None), 'keywords_parser': ((DOMHTMLKeywordsParser,), None), 'crazycredits_parser': ((DOMHTMLCrazyCreditsParser,), None), 'goofs_parser': ((DOMHTMLGoofsParser,), None), 'alternateversions_parser': ((DOMHTMLAlternateVersionsParser,), None), 'trivia_parser': ((DOMHTMLTriviaParser,), None), 'soundtrack_parser': ((DOMHTMLSoundtrackParser,), None), 'quotes_parser': ((DOMHTMLQuotesParser,), None), 'releasedates_parser': ((DOMHTMLReleaseinfoParser,), None), 'ratings_parser': ((DOMHTMLRatingsParser,), None), 'criticrev_parser': ((DOMHTMLCriticReviewsParser,), {'kind': 'critic reviews'}), 'reviews_parser': ((DOMHTMLReviewsParser,), {'kind': 'reviews'}), 'externalsites_parser': ((DOMHTMLOfficialsitesParser,), None), 'officialsites_parser': ((DOMHTMLOfficialsitesParser,), None), 'externalrev_parser': ((DOMHTMLOfficialsitesParser,), None), 'misclinks_parser': ((DOMHTMLOfficialsitesParser,), None), 'soundclips_parser': ((DOMHTMLOfficialsitesParser,), None), 'videoclips_parser': ((DOMHTMLOfficialsitesParser,), None), 'photosites_parser': ((DOMHTMLOfficialsitesParser,), None), 'connections_parser': ((DOMHTMLConnectionsParser,), None), 'tech_parser': ((DOMHTMLTechParser,), None), 'locations_parser': ((DOMHTMLLocationsParser,), None), 'news_parser': ((DOMHTMLNewsParser,), None), 'episodes_parser': ((DOMHTMLEpisodesParser,), None), 'season_episodes_parser': ((DOMHTMLSeasonEpisodesParser,), None), 'movie_faqs_parser': ((DOMHTMLFaqsParser,), None), 'airing_parser': ((DOMHTMLAiringParser,), None), 'parentsguide_parser': ((DOMHTMLParentsGuideParser,), None) }
97,928
Python
.py
2,536
24.250789
159
0.451871
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,212
searchPersonParser.py
cinemagoer_cinemagoer/imdb/parser/http/searchPersonParser.py
# Copyright 2004-2022 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the results of a search for a given person. For example, when searching for the name "Mel Gibson", the parsed page would be: http://www.imdb.com/find?q=Mel+Gibson&s=nm """ from __future__ import absolute_import, division, print_function, unicode_literals from imdb.utils import analyze_name from .piculet import Path, Rule, Rules, reducers from .searchMovieParser import DOMHTMLSearchMovieParser from .utils import analyze_imdbid class DOMHTMLSearchPersonParser(DOMHTMLSearchMovieParser): """A parser for the name search page.""" rules = [ Rule( key='data', extractor=Rules( foreach='//li[contains(@class, "find-name-result")]', rules=[ Rule( key='link', extractor=Path('.//a[@class="ipc-metadata-list-summary-item__t"]/@href', reduce=reducers.first) ), Rule( key='name', extractor=Path('.//a[@class="ipc-metadata-list-summary-item__t"]/text()') ), Rule( key='headshot', extractor=Path('.//img[@class="ipc-image"]/@src') ) ], transform=lambda x: ( analyze_imdbid(x.get('link')), analyze_name(x.get('name', '') + x.get('index', ''), canonical=1), x.get('akas'), x.get('headshot') ) ) ) ] def _init(self): super(DOMHTMLSearchPersonParser, self)._init() self.img_type = 'headshot' _OBJECTS = { 'search_person_parser': ((DOMHTMLSearchPersonParser,), {'kind': 'person'}) }
2,686
Python
.py
64
32.78125
119
0.604598
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,213
searchMovieParser.py
cinemagoer_cinemagoer/imdb/parser/http/searchMovieParser.py
# Copyright 2004-2022 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the results of a search for a given title. For example, when searching for the title "the passion", the parsed page would be: http://www.imdb.com/find?q=the+passion&s=tt """ from __future__ import absolute_import, division, print_function, unicode_literals from imdb.utils import analyze_title, re_m_kind from .piculet import Path, Rule, Rules, reducers from .utils import DOMParserBase, analyze_imdbid def process_title(tdict): """Process parsed data and build a tuple that can be used to create a list of results.""" imdbid = analyze_imdbid(tdict.get('link')) title = tdict.get('title', '').strip() kind = (tdict.get('kind') or '').strip() if not re_m_kind.match('(%s)' % kind): kind = '' year = (tdict.get('year') or '').strip() if year: title += ' (%s)' % year if kind: title += ' (%s)' % kind if title: analized_title = analyze_title(title) else: analized_title = {} akas = tdict.get('akas') cover = tdict.get('cover url') return imdbid, analized_title, akas, cover class DOMHTMLSearchMovieParser(DOMParserBase): """A parser for the title search page.""" rules = [ Rule( key='data', extractor=Rules( foreach='//li[contains(@class, "find-title-result")]', rules=[ Rule( key='link', extractor=Path('.//a[@class="ipc-metadata-list-summary-item__t"]/@href', reduce=reducers.first) ), Rule( key='title', extractor=Path('.//a[@class="ipc-metadata-list-summary-item__t"]/text()') ), Rule( key='year', extractor=Path('.//span[@class="ipc-metadata-list-summary-item__li"]/text()', reduce=reducers.first) ), Rule( key='kind', extractor=Path('(.//span[@class="ipc-metadata-list-summary-item__li"])[2]/text()') ), Rule( key='cover url', extractor=Path('.//img[@class="ipc-image"]/@src') ) ], transform=process_title ) ) ] def _init(self): self.url = '' self.img_type = 'cover url' def _reset(self): self.url = '' def postprocess_data(self, data): if 'data' not in data: return {'data': []} results = getattr(self, 'results', None) if results is not None: data['data'][:] = data['data'][:results] # Horrible hack to support AKAs. data['data'] = [x for x in data['data'] if x[0] and x[1]] if data and data['data'] and len(data['data'][0]) == 4 and isinstance(data['data'][0], tuple): for idx, datum in enumerate(data['data']): if not isinstance(datum, tuple): continue if not datum[0] and datum[1]: continue if datum[2] is not None: akas = [aka[1:-1] for aka in datum[2]] # remove the quotes datum[1]['akas'] = akas if datum[3] is not None: datum[1][self.img_type] = datum[3] data['data'][idx] = (datum[0], datum[1]) return data def add_refs(self, data): return data _OBJECTS = { 'search_movie_parser': ((DOMHTMLSearchMovieParser,), None) }
4,614
Python
.py
113
30.212389
106
0.549732
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,214
piculet.py
cinemagoer_cinemagoer/imdb/parser/http/piculet.py
# Copyright (C) 2014-2022 H. Turgut Uyar <[email protected]> # # Piculet is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Piculet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Piculet. If not, see <http://www.gnu.org/licenses/>. """Piculet is a module for scraping XML and HTML documents using XPath queries. It consists of this single source file with no dependencies other than the standard library, which makes it very easy to integrate into applications. It has been tested with Python 2.7, Python 3.4+, PyPy2 5.7+, and PyPy3 5.7+. For more information, please refer to the documentation: https://piculet.readthedocs.io/ """ from __future__ import absolute_import, division, print_function, unicode_literals import json import re import sys from argparse import ArgumentParser from collections import deque from functools import partial from operator import itemgetter from pkgutil import find_loader __version__ = '1.2b1' PY2 = sys.version_info < (3, 0) if PY2: str, bytes = unicode, str if PY2: from cgi import escape as html_escape from htmlentitydefs import name2codepoint # noqa: I003 from HTMLParser import HTMLParser from StringIO import StringIO else: from html import escape as html_escape from html.parser import HTMLParser from io import StringIO from types import MappingProxyType if PY2: from contextlib import contextmanager @contextmanager def redirect_stdout(new_stdout): """Context manager for temporarily redirecting stdout.""" old_stdout, sys.stdout = sys.stdout, new_stdout try: yield new_stdout finally: sys.stdout = old_stdout else: from contextlib import redirect_stdout ########################################################### # HTML OPERATIONS ########################################################### class HTMLNormalizer(HTMLParser): """HTML cleaner and XHTML convertor. DOCTYPE declarations and comments are removed. """ SELF_CLOSING_TAGS = {'br', 'hr', 'img', 'input', 'link', 'meta'} """Tags to handle as self-closing.""" def __init__(self, omit_tags=None, omit_attrs=None): """Initialize this normalizer. :sig: (Optional[Iterable[str]], Optional[Iterable[str]]) -> None :param omit_tags: Tags to remove, along with all their content. :param omit_attrs: Attributes to remove. """ if PY2: HTMLParser.__init__(self) else: super().__init__(convert_charrefs=True) self.omit_tags = set(omit_tags) if omit_tags is not None else set() # sig: Set[str] self.omit_attrs = set(omit_attrs) if omit_attrs is not None else set() # sig: Set[str] # stacks used during normalization self._open_tags = deque() self._open_omitted_tags = deque() def handle_starttag(self, tag, attrs): if tag in self.omit_tags: self._open_omitted_tags.append(tag) if not self._open_omitted_tags: # stack empty -> not in omit mode if '@' in tag: # email address in angular brackets print('&lt;%s&gt;' % tag, end='') return if (tag == 'li') and (self._open_tags[-1] == 'li'): self.handle_endtag('li') attributes = [] for attr_name, attr_value in attrs: if attr_name in self.omit_attrs: continue if attr_value is None: attr_value = '' markup = '%(name)s="%(value)s"' % { 'name': attr_name, 'value': html_escape(attr_value, quote=True) } attributes.append(markup) line = '<%(tag)s%(attrs)s%(slash)s>' % { 'tag': tag, 'attrs': (' ' + ' '.join(attributes)) if len(attributes) > 0 else '', 'slash': ' /' if tag in self.SELF_CLOSING_TAGS else '' } print(line, end='') if tag not in self.SELF_CLOSING_TAGS: self._open_tags.append(tag) def handle_endtag(self, tag): if not self._open_omitted_tags: # stack empty -> not in omit mode if tag not in self.SELF_CLOSING_TAGS: last = self._open_tags[-1] if (tag == 'ul') and (last == 'li'): self.handle_endtag('li') if tag == last: # expected end tag print('</%(tag)s>' % {'tag': tag}, end='') self._open_tags.pop() elif tag not in self._open_tags: # XXX: for <a><b></a></b>, this case gets invoked after the case below pass elif tag == self._open_tags[-2]: print('</%(tag)s>' % {'tag': last}, end='') print('</%(tag)s>' % {'tag': tag}, end='') self._open_tags.pop() self._open_tags.pop() elif (tag in self.omit_tags) and (tag == self._open_omitted_tags[-1]): # end of expected omitted tag self._open_omitted_tags.pop() def handle_data(self, data): if not self._open_omitted_tags: # stack empty -> not in omit mode line = html_escape(data) print(line.decode('utf-8') if PY2 and isinstance(line, bytes) else line, end='') def handle_entityref(self, name): # XXX: doesn't get called if convert_charrefs=True num = name2codepoint.get(name) # we are sure we're on PY2 here if num is not None: print('&#%(ref)d;' % {'ref': num}, end='') def handle_charref(self, name): # XXX: doesn't get called if convert_charrefs=True print('&#%(ref)s;' % {'ref': name}, end='') # def feed(self, data): # super().feed(data) # # close all remaining open tags # for tag in reversed(self._open_tags): # print('</%(tag)s>' % {'tag': tag}, end='') def html_to_xhtml(document, omit_tags=None, omit_attrs=None): """Clean HTML and convert to XHTML. :sig: (str, Optional[Iterable[str]], Optional[Iterable[str]]) -> str :param document: HTML document to clean and convert. :param omit_tags: Tags to exclude from the output. :param omit_attrs: Attributes to exclude from the output. :return: Normalized XHTML content. """ out = StringIO() normalizer = HTMLNormalizer(omit_tags=omit_tags, omit_attrs=omit_attrs) with redirect_stdout(out): normalizer.feed(document) return out.getvalue() ########################################################### # DATA EXTRACTION OPERATIONS ########################################################### # sigalias: XPathResult = Union[Sequence[str], Sequence[Element]] _USE_LXML = find_loader('lxml') is not None if _USE_LXML: from lxml import etree as ElementTree from lxml.etree import Element XPath = ElementTree.XPath xpath = ElementTree._Element.xpath else: from xml.etree import ElementTree from xml.etree.ElementTree import Element class XPath: """An XPath expression evaluator. This class is mainly needed to compensate for the lack of ``text()`` and ``@attr`` axis queries in ElementTree XPath support. """ def __init__(self, path): """Initialize this evaluator. :sig: (str) -> None :param path: XPath expression to evaluate. """ def descendant(element): # strip trailing '//text()' return [t for e in element.findall(path[:-8]) for t in e.itertext() if t] def child(element): # strip trailing '/text()' return [t for e in element.findall(path[:-7]) for t in ([e.text] + [c.tail if c.tail else '' for c in e]) if t] def attribute(element, subpath, attr): result = [e.attrib.get(attr) for e in element.findall(subpath)] return [r for r in result if r is not None] if path[0] == '/': # ElementTree doesn't support absolute paths # TODO: handle this properly, find root of tree path = '.' + path if path.endswith('//text()'): _apply = descendant elif path.endswith('/text()'): _apply = child else: steps = path.split('/') front, last = steps[:-1], steps[-1] # after dropping PY2: *front, last = path.split('/') if last.startswith('@'): _apply = partial(attribute, subpath='/'.join(front), attr=last[1:]) else: _apply = partial(Element.findall, path=path) self._apply = _apply # sig: Callable[[Element], XPathResult] def __call__(self, element): """Apply this evaluator to an element. :sig: (Element) -> XPathResult :param element: Element to apply this expression to. :return: Elements or strings resulting from the query. """ return self._apply(element) xpath = lambda e, p: XPath(p)(e) _EMPTY = {} if PY2 else MappingProxyType({}) # empty result singleton # sigalias: Reducer = Callable[[Sequence[str]], str] # sigalias: PathTransformer = Callable[[str], Any] # sigalias: MapTransformer = Callable[[Mapping[str, Any]], Any] # sigalias: Transformer = Union[PathTransformer, MapTransformer] # sigalias: ExtractedItem = Union[str, Mapping[str, Any]] class Extractor: """Abstract base extractor for getting data out of an XML element.""" def __init__(self, transform=None, foreach=None): """Initialize this extractor. :sig: (Optional[Transformer], Optional[str]) -> None :param transform: Function to transform the extracted value. :param foreach: Path to apply for generating a collection of values. """ self.transform = transform # sig: Optional[Transformer] """Function to transform the extracted value.""" self.foreach = XPath(foreach) if foreach is not None else None # sig: Optional[XPath] """Path to apply for generating a collection of values.""" def apply(self, element): """Get the raw data from an element using this extractor. :sig: (Element) -> ExtractedItem :param element: Element to apply this extractor to. :return: Extracted raw data. """ raise NotImplementedError('Concrete extractors must implement this method') def extract(self, element, transform=True): """Get the processed data from an element using this extractor. :sig: (Element, Optional[bool]) -> Any :param element: Element to extract the data from. :param transform: Whether the transformation will be applied or not. :return: Extracted and optionally transformed data. """ value = self.apply(element) if (value is None) or (value is _EMPTY) or (not transform): return value return value if self.transform is None else self.transform(value) @staticmethod def from_map(item): """Generate an extractor from a description map. :sig: (Mapping[str, Any]) -> Extractor :param item: Extractor description. :return: Extractor object. :raise ValueError: When reducer or transformer names are unknown. """ transformer = item.get('transform') if transformer is None: transform = None else: transform = transformers.get(transformer) if transform is None: raise ValueError('Unknown transformer') foreach = item.get('foreach') path = item.get('path') if path is not None: reducer = item.get('reduce') if reducer is None: reduce = None else: reduce = reducers.get(reducer) if reduce is None: raise ValueError('Unknown reducer') extractor = Path(path, reduce, transform=transform, foreach=foreach) else: items = item.get('items') # TODO: check for None rules = [Rule.from_map(i) for i in items] extractor = Rules(rules, section=item.get('section'), transform=transform, foreach=foreach) return extractor class Path(Extractor): """An extractor for getting text out of an XML element.""" def __init__(self, path, reduce=None, transform=None, foreach=None): """Initialize this extractor. :sig: ( str, Optional[Reducer], Optional[PathTransformer], Optional[str] ) -> None :param path: Path to apply to get the data. :param reduce: Function to reduce selected texts into a single string. :param transform: Function to transform extracted value. :param foreach: Path to apply for generating a collection of data. """ if PY2: Extractor.__init__(self, transform=transform, foreach=foreach) else: super().__init__(transform=transform, foreach=foreach) self.path = XPath(path) # sig: XPath """XPath evaluator to apply to get the data.""" if reduce is None: reduce = reducers.concat self.reduce = reduce # sig: Reducer """Function to reduce selected texts into a single string.""" def apply(self, element): """Apply this extractor to an element. :sig: (Element) -> str :param element: Element to apply this extractor to. :return: Extracted text. """ selected = self.path(element) if len(selected) == 0: value = None else: value = self.reduce(selected) return value class Rules(Extractor): """An extractor for getting data items out of an XML element.""" def __init__(self, rules, section=None, transform=None, foreach=None): """Initialize this extractor. :sig: ( Sequence[Rule], str, Optional[MapTransformer], Optional[str] ) -> None :param rules: Rules for generating the data items. :param section: Path for setting the root of this section. :param transform: Function to transform extracted value. :param foreach: Path for generating multiple items. """ if PY2: Extractor.__init__(self, transform=transform, foreach=foreach) else: super().__init__(transform=transform, foreach=foreach) self.rules = rules # sig: Sequence[Rule] """Rules for generating the data items.""" self.section = XPath(section) if section is not None else None # sig: Optional[XPath] """XPath expression for selecting a subroot for this section.""" def apply(self, element): """Apply this extractor to an element. :sig: (Element) -> Mapping[str, Any] :param element: Element to apply the extractor to. :return: Extracted mapping. """ if self.section is None: subroot = element else: subroots = self.section(element) if len(subroots) == 0: return _EMPTY if len(subroots) > 1: raise ValueError('Section path should select exactly one element') subroot = subroots[0] data = {} for rule in self.rules: extracted = rule.extract(subroot) data.update(extracted) return data if len(data) > 0 else _EMPTY class Rule: """A rule describing how to get a data item out of an XML element.""" def __init__(self, key, extractor, foreach=None): """Initialize this rule. :sig: (Union[str, Extractor], Extractor, Optional[str]) -> None :param key: Name to distinguish this data item. :param extractor: Extractor that will generate this data item. :param foreach: Path for generating multiple items. """ self.key = key # sig: Union[str, Extractor] """Name to distinguish this data item.""" self.extractor = extractor # sig: Extractor """Extractor that will generate this data item.""" self.foreach = XPath(foreach) if foreach is not None else None # sig: Optional[XPath] """XPath evaluator for generating multiple items.""" @staticmethod def from_map(item): """Generate a rule from a description map. :sig: (Mapping[str, Any]) -> Rule :param item: Item description. :return: Rule object. """ item_key = item['key'] key = item_key if isinstance(item_key, str) else Extractor.from_map(item_key) value = Extractor.from_map(item['value']) return Rule(key=key, extractor=value, foreach=item.get('foreach')) def extract(self, element): """Extract data out of an element using this rule. :sig: (Element) -> Mapping[str, Any] :param element: Element to extract the data from. :return: Extracted data. """ data = {} subroots = [element] if self.foreach is None else self.foreach(element) for subroot in subroots: key = self.key if isinstance(self.key, str) else self.key.extract(subroot) if key is None: continue if self.extractor.foreach is None: value = self.extractor.extract(subroot) if (value is None) or (value is _EMPTY): continue data[key] = value else: # don't try to transform list items by default, it might waste a lot of time raw_values = [self.extractor.extract(r, transform=False) for r in self.extractor.foreach(subroot)] values = [v for v in raw_values if (v is not None) and (v is not _EMPTY)] if len(values) == 0: continue data[key] = values if self.extractor.transform is None else \ list(map(self.extractor.transform, values)) return data def remove_elements(root, path): """Remove selected elements from the tree. :sig: (Element, str) -> None :param root: Root element of the tree. :param path: XPath to select the elements to remove. """ if _USE_LXML: get_parent = ElementTree._Element.getparent else: # ElementTree doesn't support parent queries, so we'll build a map for it get_parent = root.attrib.get('_get_parent') if get_parent is None: get_parent = {e: p for p in root.iter() for e in p}.get root.attrib['_get_parent'] = get_parent elements = XPath(path)(root) if len(elements) > 0: for element in elements: # XXX: could this be hazardous? parent removed in earlier iteration? get_parent(element).remove(element) def set_element_attr(root, path, name, value): """Set an attribute for selected elements. :sig: ( Element, str, Union[str, Mapping[str, Any]], Union[str, Mapping[str, Any]] ) -> None :param root: Root element of the tree. :param path: XPath to select the elements to set attributes for. :param name: Description for name generation. :param value: Description for value generation. """ elements = XPath(path)(root) for element in elements: attr_name = name if isinstance(name, str) else \ Extractor.from_map(name).extract(element) if attr_name is None: continue attr_value = value if isinstance(value, str) else \ Extractor.from_map(value).extract(element) if attr_value is None: continue element.attrib[attr_name] = attr_value def set_element_text(root, path, text): """Set the text for selected elements. :sig: (Element, str, Union[str, Mapping[str, Any]]) -> None :param root: Root element of the tree. :param path: XPath to select the elements to set attributes for. :param text: Description for text generation. """ elements = XPath(path)(root) for element in elements: element_text = text if isinstance(text, str) else \ Extractor.from_map(text).extract(element) # note that the text can be None in which case the existing text will be cleared element.text = element_text def build_tree(document, force_html=False): """Build a tree from an XML document. :sig: (str, Optional[bool]) -> Element :param document: XML document to build the tree from. :param force_html: Force to parse from HTML without converting. :return: Root element of the XML tree. """ content = document.encode('utf-8') if PY2 else document if _USE_LXML and force_html: import lxml.html return lxml.html.fromstring(content) return ElementTree.fromstring(content) class Registry: """A simple, attribute-based namespace.""" def __init__(self, entries): """Initialize this registry. :sig: (Mapping[str, Any]) -> None :param entries: Entries to add to this registry. """ self.__dict__.update(entries) def get(self, item): """Get the value of an entry from this registry. :sig: (str) -> Any :param item: Entry to get the value for. :return: Value of entry. """ return self.__dict__.get(item) def register(self, key, value): """Register a new entry in this registry. :sig: (str, Any) -> None :param key: Key to search the entry in this registry. :param value: Value to store for the entry. """ self.__dict__[key] = value _PREPROCESSORS = { 'remove': remove_elements, 'set_attr': set_element_attr, 'set_text': set_element_text } preprocessors = Registry(_PREPROCESSORS) # sig: Registry """Predefined preprocessors.""" _REDUCERS = { 'first': itemgetter(0), 'concat': partial(str.join, ''), 'clean': lambda xs: re.sub(r'\s+', ' ', ''.join(xs).replace('\xa0', ' ')).strip(), 'normalize': lambda xs: re.sub('[^a-z0-9_]', '', ''.join(xs).lower().replace(' ', '_')) } reducers = Registry(_REDUCERS) # sig: Registry """Predefined reducers.""" _TRANSFORMERS = { 'int': int, 'float': float, 'bool': bool, 'len': len, 'lower': str.lower, 'upper': str.upper, 'capitalize': str.capitalize, 'lstrip': str.lstrip, 'rstrip': str.rstrip, 'strip': str.strip } transformers = Registry(_TRANSFORMERS) # sig: Registry """Predefined transformers.""" def preprocess(root, pre): """Process a tree before starting extraction. :sig: (Element, Sequence[Mapping[str, Any]]) -> None :param root: Root of tree to process. :param pre: Descriptions for processing operations. """ for step in pre: op = step['op'] if op == 'remove': remove_elements(root, step['path']) elif op == 'set_attr': set_element_attr(root, step['path'], name=step['name'], value=step['value']) elif op == 'set_text': set_element_text(root, step['path'], text=step['text']) else: raise ValueError('Unknown preprocessing operation') def extract(element, items, section=None): """Extract data from an XML element. :sig: ( Element, Sequence[Mapping[str, Any]], Optional[str] ) -> Mapping[str, Any] :param element: Element to extract the data from. :param items: Descriptions for extracting items. :param section: Path to select the root element for these items. :return: Extracted data. """ rules = Rules([Rule.from_map(item) for item in items], section=section) return rules.extract(element) def scrape(document, spec): """Extract data from a document after optionally preprocessing it. :sig: (str, Mapping[str, Any]) -> Mapping[str, Any] :param document: Document to scrape. :param spec: Extraction specification. :return: Extracted data. """ root = build_tree(document) pre = spec.get('pre') if pre is not None: preprocess(root, pre) data = extract(root, spec.get('items'), section=spec.get('section')) return data ########################################################### # COMMAND-LINE INTERFACE ########################################################### def main(): parser = ArgumentParser(description="extract data from XML/HTML") parser.add_argument('--version', action='version', version=__version__) parser.add_argument('--html', action='store_true', help='document is in HTML format') parser.add_argument('-s', '--spec', required=True, help='spec file') arguments = parser.parse_args() content = sys.stdin.read() if arguments.html: content = html_to_xhtml(content) with open(arguments.spec) as f: spec_content = f.read() spec = json.loads(spec_content) data = scrape(content, spec) print(json.dumps(data, indent=2, sort_keys=True)) if __name__ == '__main__': main()
26,143
Python
.py
607
34.100494
95
0.596904
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,215
companyParser.py
cinemagoer_cinemagoer/imdb/parser/http/companyParser.py
# Copyright 2008-2019 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the IMDb pages on the www.imdb.com server about a company. For example, for "Columbia Pictures [us]" the referred page would be: main details http://www.imdb.com/company/co0071509/ """ from __future__ import absolute_import, division, print_function, unicode_literals import re from .piculet import Path, Rule, Rules from .utils import DOMParserBase, analyze_imdbid, build_movie _re_company_name = re.compile(r'With\s+(.+)\s+\(Sorted by.*', re.I | re.M) def clean_company_title(title): """Extract company name""" name = _re_company_name.findall(title or '') if name and name[0]: return name[0] class DOMCompanyParser(DOMParserBase): """Parser for the main page of a given company. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: cparser = DOMCompanyParser() result = cparser.parse(company_html_string) """ _containsObjects = True rules = [ Rule( key='name', extractor=Path( '//h1[@class="header"]/text()', transform=lambda x: clean_company_title(x) ) ), Rule( key='filmography', extractor=Rules( foreach='//b/a[@name]', rules=[ Rule( key=Path('./text()', transform=str.lower), extractor=Rules( foreach='../following-sibling::ol[1]/li', rules=[ Rule( key='link', extractor=Path('./a[1]/@href') ), Rule( key='title', extractor=Path('./a[1]/text()') ), Rule( key='year', extractor=Path('./text()[1]') ) ], transform=lambda x: build_movie( '%s %s' % (x.get('title'), x.get('year').strip()), movieID=analyze_imdbid(x.get('link') or ''), _parsingCompany=True ) ) ) ] ) ) ] preprocessors = [ (re.compile('(<b><a name=)', re.I), r'</p>\1') ] def postprocess_data(self, data): for key in ['name']: if (key in data) and isinstance(data[key], dict): subdata = data[key] del data[key] data.update(subdata) for key in list(data.keys()): new_key = key.replace('company', 'companies') new_key = new_key.replace('other', 'miscellaneous') new_key = new_key.replace('distributor', 'distributors') if new_key != key: data[new_key] = data[key] del data[key] return data _OBJECTS = { 'company_main_parser': ((DOMCompanyParser,), None) }
4,253
Python
.py
105
27.866667
82
0.522276
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,216
showtimesParser.py
cinemagoer_cinemagoer/imdb/parser/http/showtimesParser.py
# Copyright 2009-2022 Davide Alberani <[email protected]> # 2018 H. Turgut Uyar <[email protected]> # 2022 Kostya Farber # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the pages for the showtimes of movies near you. Pages: https://www.imdb.com/showtimes/ """ from __future__ import absolute_import, division, print_function, unicode_literals import re from .piculet import Path, Rule, Rules from .utils import DOMParserBase, analyze_imdbid, build_movie re_space = re.compile(r'\s+') class DOMHTMLMoviesNearYou(DOMParserBase): rules = [ Rule( key='showtimes', extractor=Rules( foreach='//div[@itemtype="http://schema.org/MovieTheater"]', rules=[ Rule( key='cinema', extractor=Path('.//h3/a/text()') ), Rule( key='address and contacts', extractor=Path( './/div[@itemtype="http://schema.org/PostalAddress"]//text()', transform=lambda x: re_space.sub(' ', x).strip() ) ), Rule( key='movies', extractor=Rules( foreach='.//div[@class="info"]', rules=[ Rule( key='movie', extractor=Rules( rules=[ Rule( key='link', extractor=Path(".//h4//a/@href") ), Rule( key='title', extractor=Path(".//h4//a/text()") ), ], transform=lambda x: build_movie(x.get('title'), analyze_imdbid(x.get('link'))) ) ), Rule( key='showtimes', extractor=Path( './/div[@class="showtimes"]//text()', transform=lambda x: re_space.sub(' ', x).strip() ) ) ]) ) ] ) ) ] def postprocess_data(self, data): return data.get('showtimes', []) _OBJECTS = { 'showtime_parser': ((DOMHTMLMoviesNearYou,), None), }
3,702
Python
.py
85
25.188235
118
0.434951
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,217
utils.py
cinemagoer_cinemagoer/imdb/parser/http/utils.py
# Copyright 2004-2022 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides miscellaneous utilities used by the components in the :mod:`imdb.parser.http` package. """ from __future__ import absolute_import, division, print_function, unicode_literals import re from imdb import PY2 from imdb.Character import Character from imdb.Movie import Movie from imdb.parser.http.logging import logger from imdb.Person import Person from imdb.utils import _Container, flatten from .piculet import _USE_LXML, ElementTree, Path, Rule, Rules, build_tree, html_to_xhtml from .piculet import xpath as piculet_xpath if PY2: from collections import Callable else: from collections.abc import Callable # Year, imdbIndex and kind. re_yearKind_index = re.compile( r'(\([0-9\?]{4}(?:/[IVXLCDM]+)?\)(?: \(mini\)| \(TV\)| \(V\)| \(VG\))?)' ) # Match imdb ids in href tags re_imdbid = re.compile(r'(title/tt|name/nm|company/co|companies=co|user/ur)([0-9]+)') def analyze_imdbid(href): """Return an imdbID from an URL.""" if not href: return None match = re_imdbid.search(href) if not match: return None return str(match.group(2)) _modify_keys = list(Movie.keys_tomodify_list) + list(Person.keys_tomodify_list) def _putRefs(d, re_titles, re_names, lastKey=None): """Iterate over the strings inside list items or dictionary values, substitutes movie titles and person names with the (qv) references.""" if isinstance(d, list): for i in range(len(d)): if isinstance(d[i], str): if lastKey in _modify_keys: if re_names: d[i] = re_names.sub(r"'\1' (qv)", d[i]) if re_titles: d[i] = re_titles.sub(r'_\1_ (qv)', d[i]) elif isinstance(d[i], (list, dict)): _putRefs(d[i], re_titles, re_names, lastKey=lastKey) elif isinstance(d, dict): for k, v in list(d.items()): lastKey = k if isinstance(v, str): if lastKey in _modify_keys: if re_names: d[k] = re_names.sub(r"'\1' (qv)", v) if re_titles: d[k] = re_titles.sub(r'_\1_ (qv)', v) elif isinstance(v, (list, dict)): _putRefs(d[k], re_titles, re_names, lastKey=lastKey) _b_p_logger = logger.getChild('build_person') def build_person(txt, personID=None, billingPos=None, roleID=None, accessSystem='http', modFunct=None, headshot=None): """Return a Person instance from the tipical <tr>...</tr> strings found in the IMDb's web site.""" # if personID is None # _b_p_logger.debug('empty name or personID for "%s"', txt) notes = '' role = '' # Search the (optional) separator between name and role/notes. if txt.find('....') != -1: sep = '....' elif txt.find('...') != -1: sep = '...' else: sep = '...' # Replace the first parenthesis, assuming there are only notes, after. # Rationale: no imdbIndex is (ever?) showed on the web site. txt = txt.replace('(', '...(', 1) txt_split = txt.split(sep, 1) if isinstance(roleID, list): roleID = [r for r in roleID if r] if not roleID: roleID = [''] name = txt_split[0].strip() if len(txt_split) == 2: role_comment = re_spaces.sub(' ', txt_split[1]).strip() re_episodes = re.compile(r'(\d+ episodes.*)', re.I | re.M | re.S) ep_match = re_episodes.search(role_comment) if ep_match and (not ep_match.start() or role_comment[ep_match.start() - 1] != '('): role_comment = re_episodes.sub(r'(\1)', role_comment) # Strip common endings. if role_comment[-4:] == ' and': role_comment = role_comment[:-4].rstrip() elif role_comment[-2:] == ' &': role_comment = role_comment[:-2].rstrip() elif role_comment[-6:] == '& ....': role_comment = role_comment[:-6].rstrip() # Get the notes. if roleID is not None: if not isinstance(roleID, list): cmt_idx = role_comment.find('(') if cmt_idx != -1: role = role_comment[:cmt_idx].rstrip() notes = role_comment[cmt_idx:] else: # Just a role, without notes. role = role_comment else: role = role_comment else: # We're managing something that doesn't have a 'role', so # everything are notes. notes = role_comment if role == '....': role = '' roleNotes = [] # Manages multiple roleIDs. if isinstance(roleID, list): rolesplit = role.split('/') role = [] for r in rolesplit: nidx = r.find('(') if nidx != -1: role.append(r[:nidx].rstrip()) roleNotes.append(r[nidx:]) else: role.append(r) roleNotes.append(None) lr = len(role) lrid = len(roleID) if lr > lrid: roleID += [None] * (lrid - lr) elif lr < lrid: roleID = roleID[:lr] for i, rid in enumerate(roleID): if rid is not None: roleID[i] = str(rid) if lr == 1: role = role[0] roleID = roleID[0] notes = roleNotes[0] or '' elif roleID is not None: roleID = str(roleID) if personID is not None: personID = str(personID) if (not name) or (personID is None): # Set to 'debug', since build_person is expected to receive some crap. _b_p_logger.debug('empty name or personID for "%s"', txt) if role: if isinstance(role, list): role = [r.strip() for r in role] else: role = role.strip() if notes: if isinstance(notes, list): notes = [n.strip() for n in notes] else: notes = notes.strip() # XXX: return None if something strange is detected? data = {} if headshot: data['headshot'] = headshot person = Person(name=name, personID=personID, currentRole=role, roleID=roleID, notes=notes, billingPos=billingPos, modFunct=modFunct, accessSystem=accessSystem, data=data) if roleNotes and len(roleNotes) == len(roleID): for idx, role in enumerate(person.currentRole): if roleNotes[idx]: role.notes = roleNotes[idx] elif person.currentRole and isinstance(person.currentRole, Character) and \ not person.currentRole.notes and notes: person.currentRole.notes = notes return person _re_chrIDs = re.compile('[0-9]{7}') _b_m_logger = logger.getChild('build_movie') # To shrink spaces. re_spaces = re.compile(r'\s+') def build_movie(txt, movieID=None, roleID=None, status=None, accessSystem='http', modFunct=None, _parsingCharacter=False, _parsingCompany=False, year=None, chrRoles=None, rolesNoChar=None, additionalNotes=None): """Given a string as normally seen on the "categorized" page of a person on the IMDb's web site, returns a Movie instance.""" # FIXME: Oook, lets face it: build_movie and build_person are now # two horrible sets of patches to support the new IMDb design. They # must be rewritten from scratch. if _parsingCompany: _defSep = ' ... ' else: _defSep = ' .... ' title = re_spaces.sub(' ', txt).strip() # Split the role/notes from the movie title. tsplit = title.split(_defSep, 1) role = '' notes = '' roleNotes = [] if len(tsplit) == 2: title = tsplit[0].rstrip() role = tsplit[1].lstrip() if title[-9:] == 'TV Series': title = title[:-9].rstrip() # elif title[-7:] == '(short)': # title = title[:-7].rstrip() # elif title[-11:] == '(TV series)': # title = title[:-11].rstrip() # elif title[-10:] == '(TV movie)': # title = title[:-10].rstrip() elif title[-14:] == 'TV mini-series': title = title[:-14] + ' (mini)' if title and title.endswith(_defSep.rstrip()): title = title[:-len(_defSep) + 1] # Try to understand where the movie title ends. while True: if year: break if title[-1:] != ')': # Ignore the silly "TV Series" notice. if title[-9:] == 'TV Series': title = title[:-9].rstrip() continue else: # Just a title: stop here. break # Try to match paired parentheses; yes: sometimes there are # parentheses inside comments... nidx = title.rfind('(') while nidx != -1 and title[nidx:].count('(') != title[nidx:].count(')'): nidx = title[:nidx].rfind('(') # Unbalanced parentheses: stop here. if nidx == -1: break # The last item in parentheses seems to be a year: stop here. first4 = title[nidx + 1:nidx + 5] if (first4.isdigit() or first4 == '????') and title[nidx + 5:nidx + 6] in (')', '/'): break # The last item in parentheses is a known kind: stop here. if title[nidx + 1:-1] in ('TV', 'V', 'mini', 'VG', 'TV movie', 'TV series', 'short'): break # Else, in parentheses there are some notes. # XXX: should the notes in the role half be kept separated # from the notes in the movie title half? if notes: notes = '%s %s' % (title[nidx:], notes) else: notes = title[nidx:] title = title[:nidx].rstrip() if year: year = year.strip() if title[-1:] == ')': fpIdx = title.rfind('(') if fpIdx != -1: if notes: notes = '%s %s' % (title[fpIdx:], notes) else: notes = title[fpIdx:] title = title[:fpIdx].rstrip() title = '%s (%s)' % (title, year) if not roleID: roleID = None elif len(roleID) == 1: roleID = roleID[0] if not role and chrRoles and isinstance(roleID, str): roleID = _re_chrIDs.findall(roleID) role = ' / '.join([_f for _f in chrRoles.split('@@') if _f]) # Manages multiple roleIDs. if isinstance(roleID, list): tmprole = role.split('/') role = [] for r in tmprole: nidx = r.find('(') if nidx != -1: role.append(r[:nidx].rstrip()) roleNotes.append(r[nidx:]) else: role.append(r) roleNotes.append(None) lr = len(role) lrid = len(roleID) if lr > lrid: roleID += [None] * (lrid - lr) elif lr < lrid: roleID = roleID[:lr] for i, rid in enumerate(roleID): if rid is not None: roleID[i] = str(rid) if lr == 1: role = role[0] roleID = roleID[0] elif roleID is not None: roleID = str(roleID) if movieID is not None: movieID = str(movieID) if (not title) or (movieID is None): _b_m_logger.error('empty title or movieID for "%s"', txt) if rolesNoChar: rolesNoChar = [_f for _f in [x.strip() for x in rolesNoChar.split('/')] if _f] if not role: role = [] elif not isinstance(role, list): role = [role] role += rolesNoChar notes = notes.strip() if additionalNotes: additionalNotes = re_spaces.sub(' ', additionalNotes).strip() if notes: notes += ' ' notes += additionalNotes m = Movie(title=title, movieID=movieID, notes=notes, currentRole=role, roleID=roleID, roleIsPerson=_parsingCharacter, modFunct=modFunct, accessSystem=accessSystem) if additionalNotes: if 'TV Series' in additionalNotes: m['kind'] = 'tv series' elif 'Video Game' in additionalNotes: m['kind'] = 'video game' elif 'TV Movie' in additionalNotes: m['kind'] = 'tv movie' elif 'TV Short' in additionalNotes: m['kind'] = 'tv short' if roleNotes and len(roleNotes) == len(roleID): for idx, role in enumerate(m.currentRole): try: if roleNotes[idx]: role.notes = roleNotes[idx] except IndexError: break # Status can't be checked here, and must be detected by the parser. if status: m['status'] = status return m class DOMParserBase(object): """Base parser to handle HTML data from the IMDb's web server.""" _defGetRefs = False _containsObjects = False preprocessors = [] rules = [] _logger = logger.getChild('domparser') def __init__(self): """Initialize the parser.""" self._modFunct = None self._as = 'http' self._cname = self.__class__.__name__ self._init() self.reset() def reset(self): """Reset the parser.""" # Names and titles references. self._namesRefs = {} self._titlesRefs = {} self._reset() def _init(self): """Subclasses can override this method, if needed.""" pass def _reset(self): """Subclasses can override this method, if needed.""" pass def parse(self, html_string, getRefs=None, **kwds): """Return the dictionary generated from the given html string; getRefs can be used to force the gathering of movies/persons references.""" self.reset() if getRefs is not None: self.getRefs = getRefs else: self.getRefs = self._defGetRefs if PY2 and isinstance(html_string, str): html_string = html_string.decode('utf-8') # Temporary fix: self.parse_dom must work even for empty strings. html_string = self.preprocess_string(html_string) if html_string: html_string = html_string.replace('&nbsp;', ' ') dom = self.get_dom(html_string) try: dom = self.preprocess_dom(dom) except Exception: self._logger.error('%s: caught exception preprocessing DOM', self._cname, exc_info=True) if self.getRefs: try: self.gather_refs(dom) except Exception: self._logger.warn('%s: unable to gather refs', self._cname, exc_info=True) data = self.parse_dom(dom) else: data = {} try: data = self.postprocess_data(data) except Exception: self._logger.error('%s: caught exception postprocessing data', self._cname, exc_info=True) if self._containsObjects: self.set_objects_params(data) data = self.add_refs(data) return data def get_dom(self, html_string): """Return a dom object, from the given string.""" try: if not _USE_LXML: html_string = html_to_xhtml(html_string, omit_tags={"script"}) dom = build_tree(html_string, force_html=True) if dom is None: dom = build_tree('') self._logger.error('%s: using a fake empty DOM', self._cname) return dom except Exception: self._logger.error('%s: caught exception parsing DOM', self._cname, exc_info=True) return build_tree('') def xpath(self, element, path): """Return elements matching the given XPath.""" try: return piculet_xpath(element, path) except Exception: self._logger.error('%s: caught exception extracting XPath "%s"', self._cname, path, exc_info=True) return [] def tostring(self, element): """Convert the element to a string.""" if isinstance(element, str): return str(element) else: try: return ElementTree.tostring(element, encoding='utf8') except Exception: self._logger.error('%s: unable to convert to string', self._cname, exc_info=True) return '' def clone(self, element): """Clone an element.""" return build_tree(self.tostring(element)) def preprocess_string(self, html_string): """Here we can modify the text, before it's parsed.""" if not html_string: return html_string try: preprocessors = self.preprocessors except AttributeError: return html_string for src, sub in preprocessors: # re._pattern_type is present only since Python 2.5. if isinstance(getattr(src, 'sub', None), Callable): html_string = src.sub(sub, html_string) elif isinstance(src, str) or isinstance(src, unicode): html_string = html_string.replace(src, sub) elif isinstance(src, Callable): try: html_string = src(html_string) except Exception: _msg = '%s: caught exception preprocessing html' self._logger.error(_msg, self._cname, exc_info=True) continue return html_string def gather_refs(self, dom): """Collect references.""" grParser = GatherRefs() grParser._as = self._as grParser._modFunct = self._modFunct refs = grParser.parse_dom(dom) refs = grParser.postprocess_data(refs) self._namesRefs = refs['names refs'] self._titlesRefs = refs['titles refs'] def preprocess_dom(self, dom): """Last chance to modify the dom, before the rules are applied.""" return dom def parse_dom(self, dom): """Parse the given dom according to the rules specified in self.rules.""" return Rules(self.rules).extract(dom) def postprocess_data(self, data): """Here we can modify the data.""" return data def set_objects_params(self, data): """Set parameters of Movie/Person/... instances, since they are not always set in the parser's code.""" for obj in flatten(data, yieldDictKeys=True, scalar=_Container): obj.accessSystem = self._as obj.modFunct = self._modFunct def add_refs(self, data): """Modify data according to the expected output.""" if self.getRefs: titl_re = r'(%s)' % '|'.join( [re.escape(x) for x in list(self._titlesRefs.keys())] ) if titl_re != r'()': re_titles = re.compile(titl_re, re.U) else: re_titles = None nam_re = r'(%s)' % '|'.join( [re.escape(x) for x in list(self._namesRefs.keys())] ) if nam_re != r'()': re_names = re.compile(nam_re, re.U) else: re_names = None _putRefs(data, re_titles, re_names) return {'data': data, 'titlesRefs': self._titlesRefs, 'namesRefs': self._namesRefs } def _parse_ref(text, link, info): """Manage links to references.""" if link.find('/title/tt') != -1: yearK = re_yearKind_index.match(info) if yearK and yearK.start() == 0: text += ' %s' % info[:yearK.end()] return text.replace('\n', ' '), link class GatherRefs(DOMParserBase): """Parser used to gather references to movies, persons.""" _common_rules = [ Rule( key='text', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ), Rule( key='info', extractor=Path('./following::text()[1]') ) ] _common_transform = lambda x: _parse_ref( x.get('text') or '', x.get('link') or '', (x.get('info') or '').strip() ) rules = [ Rule( key='names refs', extractor=Rules( foreach='//a[starts-with(@href, "/name/nm")]', rules=_common_rules, transform=_common_transform ) ), Rule( key='titles refs', extractor=Rules( foreach='//a[starts-with(@href, "/title/tt")]', rules=_common_rules, transform=_common_transform ) ) ] def postprocess_data(self, data): result = {} for item in ('names refs', 'titles refs'): result[item] = {} for k, v in data.get(item, []): k = k.strip() v = v.strip() if not (k and v): continue imdbID = analyze_imdbid(v) if item == 'names refs': obj = Person(personID=imdbID, name=k, accessSystem=self._as, modFunct=self._modFunct) elif item == 'titles refs': obj = Movie(movieID=imdbID, title=k, accessSystem=self._as, modFunct=self._modFunct) result[item][k] = obj return result def add_refs(self, data): return data
22,603
Python
.py
579
28.773748
93
0.545719
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,218
__init__.py
cinemagoer_cinemagoer/imdb/parser/http/__init__.py
# Copyright 2004-2022 Davide Alberani <[email protected]> # 2008 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This package provides the IMDbHTTPAccessSystem class used to access IMDb's data through the web interface. The :func:`imdb.IMDb` function will return an instance of this class when called with the ``accessSystem`` argument is set to "http" or "web" or "html" (this is the default). """ from __future__ import absolute_import, division, print_function, unicode_literals import socket import ssl import warnings from codecs import lookup from imdb import PY2, IMDbBase from imdb._exceptions import IMDbDataAccessError, IMDbParserError from imdb.parser.http.logging import logger from imdb.utils import analyze_title from . import ( companyParser, listParser, movieParser, personParser, searchCompanyParser, searchKeywordParser, searchMovieAdvancedParser, searchMovieParser, searchPersonParser, showtimesParser, topBottomParser ) if PY2: from urllib import quote_plus from urllib2 import HTTPRedirectHandler, HTTPSHandler, ProxyHandler, build_opener # noqa: I003 else: from urllib.parse import quote_plus from urllib.request import HTTPRedirectHandler, HTTPSHandler, ProxyHandler, build_opener # Logger for miscellaneous functions. _aux_logger = logger.getChild('aux') class _ModuleProxy: """A proxy to instantiate and access parsers.""" def __init__(self, module, defaultKeys=None): """Initialize a proxy for the given module; defaultKeys, if set, muste be a dictionary of values to set for instanced objects.""" if defaultKeys is None: defaultKeys = {} self._defaultKeys = defaultKeys self._module = module def __getattr__(self, name): """Called only when no look-up is found.""" _sm = self._module # Read the _OBJECTS dictionary to build the asked parser. if name in _sm._OBJECTS: _entry = _sm._OBJECTS[name] # Initialize the parser. kwds = {} parserClass = _entry[0][0] obj = parserClass(**kwds) attrsToSet = self._defaultKeys.copy() attrsToSet.update(_entry[1] or {}) # Set attribute to the object. for key in attrsToSet: setattr(obj, key, attrsToSet[key]) setattr(self, name, obj) return obj return getattr(_sm, name) class _FakeURLOpener(object): """Fake URLOpener object, used to return empty strings instead of errors. """ def __init__(self, url, headers): self.url = url self.headers = headers def read(self, *args, **kwds): return '' def close(self, *args, **kwds): pass def info(self, *args, **kwds): return self.headers class IMDbHTTPSHandler(HTTPSHandler, object): """HTTPSHandler that ignores the SSL certificate.""" def __init__(self, logger=None, *args, **kwds): self._logger = logger context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE super(IMDbHTTPSHandler, self).__init__(context=context) def http_error_default(self, url, fp, errcode, errmsg, headers): if errcode == 404: if self._logger: self._logger.warn('404 code returned for %s: %s (headers: %s)', url, errmsg, headers) return _FakeURLOpener(url, headers) raise IMDbDataAccessError( {'url': 'http:%s' % url, 'errcode': errcode, 'errmsg': errmsg, 'headers': headers, 'error type': 'http_error_default', 'proxy': self.get_proxy()} ) def open_unknown(self, fullurl, data=None): raise IMDbDataAccessError( {'fullurl': fullurl, 'data': str(data), 'error type': 'open_unknown', 'proxy': self.get_proxy()} ) def open_unknown_proxy(self, proxy, fullurl, data=None): raise IMDbDataAccessError( {'proxy': str(proxy), 'fullurl': fullurl, 'error type': 'open_unknown_proxy', 'data': str(data)} ) class IMDbHTTPRedirectHandler(HTTPRedirectHandler): """Custom handler to support redirect 308.""" def http_error_308(self, req, fp, code, msg, headers): # force handling of redirect 308 req.code = 302 code = 302 return super(IMDbHTTPRedirectHandler, self).http_error_302(req, fp, code, msg, headers) class IMDbURLopener: """Fetch web pages and handle errors.""" _logger = logger.getChild('urlopener') def __init__(self, *args, **kwargs): self._last_url = '' self.https_handler = IMDbHTTPSHandler(logger=self._logger) self.redirect_handler = IMDbHTTPRedirectHandler() self.proxies = {} self.addheaders = [] for header in ('User-Agent', 'User-agent', 'user-agent'): self.del_header(header) self.set_header('User-Agent', 'Mozilla/5.0 (X11; CrOS armv6l 13597.84.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.56') # noqa: E501 lang = kwargs.get('languages', 'en-us,en;q=0.5') self.set_header('Accept-Language', lang) def get_proxy(self): """Return the used proxy, or an empty string.""" return self.proxies.get('http', '') def set_proxy(self, proxy): """Set the proxy.""" if not proxy: if 'http' in self.proxies: del self.proxies['http'] else: if not proxy.lower().startswith('http://'): proxy = 'http://%s' % proxy self.proxies['http'] = proxy def set_header(self, header, value, _overwrite=True): """Set a default header.""" if _overwrite: self.del_header(header) self.addheaders.append((header, value)) def get_header(self, header): """Return the first value of a header, or None if not present.""" for index in range(len(self.addheaders)): if self.addheaders[index][0] == header: return self.addheaders[index][1] return None def del_header(self, header): """Remove a default header.""" for index in range(len(self.addheaders)): if self.addheaders[index][0] == header: del self.addheaders[index] break def retrieve_unicode(self, url, size=-1): """Retrieves the given URL, and returns a unicode string, trying to guess the encoding of the data (assuming utf8 by default)""" encode = None try: if size != -1: self.set_header('Range', 'bytes=0-%d' % size) handlers = [] if 'http' in self.proxies: proxy_handler = ProxyHandler({ 'http': self.proxies['http'], 'https': self.proxies['http'] }) handlers.append(proxy_handler) handlers.append(self.redirect_handler) handlers.append(self.https_handler) uopener = build_opener(*handlers) uopener.addheaders = list(self.addheaders) response = uopener.open(url) content = response.read() self._last_url = response.url # Maybe the server is so nice to tell us the charset... if PY2: server_encode = response.headers.getparam('charset') or None else: server_encode = response.headers.get_content_charset(None) # Otherwise, look at the content-type HTML meta tag. if server_encode is None and content: begin_h = content.find(b'text/html; charset=') if begin_h != -1: end_h = content[19 + begin_h:].find('"') if end_h != -1: server_encode = content[19 + begin_h:19 + begin_h + end_h] if server_encode: try: if lookup(server_encode): encode = server_encode except (LookupError, ValueError, TypeError): pass if size != -1: self.del_header('Range') response.close() except IOError as e: if size != -1: # Ensure that the Range header is removed. self.del_header('Range') raise IMDbDataAccessError( {'errcode': e.errno, 'errmsg': str(e.strerror), 'url': url, 'proxy': self.get_proxy(), 'exception type': 'IOError', 'original exception': e} ) if encode is None: encode = 'utf8' # The detection of the encoding is error prone... self._logger.warn('Unable to detect the encoding of the retrieved page [%s];' ' falling back to default utf8.', encode) if isinstance(content, str): return content return str(content, encode, 'replace') class IMDbHTTPAccessSystem(IMDbBase): """The class used to access IMDb's data through the web.""" accessSystem = 'http' _http_logger = logger def __init__(self, adultSearch=True, proxy=-1, cookie_id=-1, timeout=30, cookie_uu=None, *arguments, **keywords): """Initialize the access system.""" IMDbBase.__init__(self, *arguments, **keywords) self.urlOpener = IMDbURLopener(*arguments, **keywords) self._getRefs = True self._mdparse = False self.set_timeout(timeout) if proxy != -1: self.set_proxy(proxy) _def = {'_modFunct': self._defModFunct, '_as': self.accessSystem} # Proxy objects. self.smProxy = _ModuleProxy(searchMovieParser, defaultKeys=_def) self.smaProxy = _ModuleProxy(searchMovieAdvancedParser, defaultKeys=_def) self.spProxy = _ModuleProxy(searchPersonParser, defaultKeys=_def) self.scompProxy = _ModuleProxy(searchCompanyParser, defaultKeys=_def) self.skProxy = _ModuleProxy(searchKeywordParser, defaultKeys=_def) self.mProxy = _ModuleProxy(movieParser, defaultKeys=_def) self.pProxy = _ModuleProxy(personParser, defaultKeys=_def) self.compProxy = _ModuleProxy(companyParser, defaultKeys=_def) self.topBottomProxy = _ModuleProxy(topBottomParser, defaultKeys=_def) self.listProxy = _ModuleProxy(listParser, defaultKeys=_def) self.stimesProxy = _ModuleProxy(showtimesParser, defaultKeys=_def) def _normalize_movieID(self, movieID): """Normalize the given movieID.""" try: return '%07d' % int(movieID) except ValueError as e: raise IMDbParserError('invalid movieID "%s": %s' % (movieID, e)) def _normalize_personID(self, personID): """Normalize the given personID.""" try: return '%07d' % int(personID) except ValueError as e: raise IMDbParserError('invalid personID "%s": %s' % (personID, e)) def _normalize_companyID(self, companyID): """Normalize the given companyID.""" try: return '%07d' % int(companyID) except ValueError as e: raise IMDbParserError('invalid companyID "%s": %s' % (companyID, e)) def get_imdbMovieID(self, movieID): """Translate a movieID in an imdbID; in this implementation the movieID _is_ the imdbID. """ return movieID def get_imdbPersonID(self, personID): """Translate a personID in an imdbID; in this implementation the personID _is_ the imdbID. """ return personID def get_imdbCompanyID(self, companyID): """Translate a companyID in an imdbID; in this implementation the companyID _is_ the imdbID. """ return companyID def get_proxy(self): """Return the used proxy or an empty string.""" return self.urlOpener.get_proxy() def set_proxy(self, proxy): """Set the web proxy to use. It should be a string like 'http://localhost:8080/'; if the string is empty, no proxy will be used. If set, the value of the environment variable HTTP_PROXY is automatically used. """ self.urlOpener.set_proxy(proxy) def set_timeout(self, timeout): """Set the default timeout, in seconds, of the connection.""" try: timeout = int(timeout) except Exception: timeout = 0 if timeout <= 0: timeout = None socket.setdefaulttimeout(timeout) def set_cookies(self, cookie_id, cookie_uu): """Set a cookie to access an IMDb's account.""" warnings.warn("set_cookies has been deprecated") def del_cookies(self): """Remove the used cookie.""" warnings.warn("del_cookies has been deprecated") def do_adult_search(self, doAdult, cookie_id=None, cookie_uu=None): """If doAdult is true, 'adult' movies are included in the search results; cookie_id and cookie_uu are optional parameters to select a specific account (see your cookie or cookies.txt file.""" return def _retrieve(self, url, size=-1, _noCookies=False): """Retrieve the given URL.""" self._http_logger.debug('fetching url %s (size: %d)', url, size) ret = self.urlOpener.retrieve_unicode(url, size=size) if PY2 and isinstance(ret, str): ret = ret.decode('utf-8') return ret def _get_search_content(self, kind, ton, results): """Retrieve the web page for a given search. kind can be 'tt' (for titles), 'nm' (for names), or 'co' (for companies). ton is the title or the name to search. results is the maximum number of results to be retrieved.""" if PY2: params = 'q=%s&s=%s' % (quote_plus(ton, safe=''.encode('utf8')), kind.encode('utf8')) else: params = 'q=%s&s=%s' % (quote_plus(ton, safe=''), kind) if kind == 'ep': params = params.replace('s=ep&', 's=tt&ttype=ep&', 1) cont = self._retrieve(self.urls['find'] % params) # print 'URL:', imdbURL_find % params if cont.find('Your search returned more than') == -1 or \ cont.find("displayed the exact matches") == -1: return cont # The retrieved page contains no results, because too many # titles or names contain the string we're looking for. params = 'q=%s&ls=%s&lm=0' % (quote_plus(ton, safe=''), kind) size = 131072 + results * 512 return self._retrieve(self.urls['find'] % params, size=size) def _search_movie(self, title, results): cont = self._get_search_content('tt', title, results) return self.smProxy.search_movie_parser.parse(cont, results=results)['data'] def _get_list_content(self, list_, page): """Retrieve a list by it's id""" if list_.startswith('ls'): imdbUrl = self.urls['movie_list'] + list_ + '?page=' + str(page) else: warnings.warn("list type not recognized make sure it starts with 'ls'") return return self._retrieve(url=imdbUrl) def _get_movie_list(self, list_, results): page = 1 result_list = [] while True: cont = self._get_list_content(list_, page=page) result_part = self.listProxy.list_parser.parse(cont, results=results)['data'] if result_part: page += 1 result_list.extend(result_part) else: break return result_list def _get_search_movie_advanced_content(self, title=None, adult=None, results=None, sort=None, sort_dir=None): """Retrieve the web page for a given search. results is the maximum number of results to be retrieved.""" criteria = {} if title is not None: criteria['title'] = quote_plus(title, safe='') if adult: criteria['adult'] = 'include' if results is not None: criteria['count'] = str(results) if sort is not None: criteria['sort'] = sort if sort_dir is not None: criteria['sort'] = sort + ',' + sort_dir params = '&'.join(['%s=%s' % (k, v) for k, v in criteria.items()]) return self._retrieve(self.urls['search_movie_advanced'] % params) def _search_movie_advanced(self, title=None, adult=None, results=None, sort=None, sort_dir=None): cont = self._get_search_movie_advanced_content(title=title, adult=adult, results=results, sort=sort, sort_dir=sort_dir) return self.smaProxy.search_movie_advanced_parser.parse(cont, results=results)['data'] def _get_top_movies_or_tv_by_genres(self, genres, filter_content): cont = self._retrieve(self.urls['search_movie_advanced'] % 'genres=' + genres + filter_content) return self.smaProxy.search_movie_advanced_parser.parse(cont)['data'] def _search_episode(self, title, results): t_dict = analyze_title(title) if t_dict['kind'] == 'episode': title = t_dict['title'] cont = self._get_search_content('ep', title, results) return self.smProxy.search_movie_parser.parse(cont, results=results)['data'] def get_movie_main(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'reference') return self.mProxy.movie_parser.parse(cont, mdparse=self._mdparse) def get_movie_recommendations(self, movieID): # for some reason /tt0133093 is okay, but /tt0133093/ is not cont = self._retrieve((self.urls['movie_main'] % movieID).strip('/')) r = {'info sets': ('recommendations',), 'data': {}} ret = self.mProxy.movie_parser.parse(cont, mdparse=self._mdparse) if 'data' in ret and 'recommendations' in ret['data'] and ret['data']['recommendations']: r['data']['recommendations'] = ret['data']['recommendations'] return r def get_movie_full_credits(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'fullcredits') return self.mProxy.full_credits_parser.parse(cont) def get_movie_plot(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'plotsummary') ret = self.mProxy.plot_parser.parse(cont, getRefs=self._getRefs) ret['info sets'] = ('plot', 'synopsis') return ret def get_movie_awards(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'awards') return self.mProxy.movie_awards_parser.parse(cont) def get_movie_taglines(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'taglines') return self.mProxy.taglines_parser.parse(cont) def get_movie_keywords(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'keywords') return self.mProxy.keywords_parser.parse(cont) def get_movie_alternate_versions(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'alternateversions') return self.mProxy.alternateversions_parser.parse(cont, getRefs=self._getRefs) def get_movie_crazy_credits(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'crazycredits') return self.mProxy.crazycredits_parser.parse(cont, getRefs=self._getRefs) def get_movie_goofs(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'goofs') return self.mProxy.goofs_parser.parse(cont, getRefs=self._getRefs) def get_movie_quotes(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'quotes') return self.mProxy.quotes_parser.parse(cont, getRefs=self._getRefs) def get_movie_release_dates(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'releaseinfo') ret = self.mProxy.releasedates_parser.parse(cont) ret['info sets'] = ('release dates', 'akas') return ret get_movie_akas = get_movie_release_dates get_movie_release_info = get_movie_release_dates def get_movie_vote_details(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'ratings') return self.mProxy.ratings_parser.parse(cont) def get_movie_trivia(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'trivia') return self.mProxy.trivia_parser.parse(cont, getRefs=self._getRefs) def get_movie_connections(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'movieconnections') return self.mProxy.connections_parser.parse(cont) def get_movie_technical(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'technical') return self.mProxy.tech_parser.parse(cont) def get_movie_locations(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'locations') return self.mProxy.locations_parser.parse(cont) def get_movie_soundtrack(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'soundtrack') return self.mProxy.soundtrack_parser.parse(cont) def get_movie_reviews(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'reviews?count=9999999&start=0') return self.mProxy.reviews_parser.parse(cont) def get_movie_critic_reviews(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'criticreviews') return self.mProxy.criticrev_parser.parse(cont) def get_movie_external_reviews(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'externalreviews') return self.mProxy.externalrev_parser.parse(cont) def get_movie_external_sites(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'externalsites') ret = self.mProxy.externalsites_parser.parse(cont) ret['info sets'] = ('external sites', 'misc sites', 'sound clips', 'video sites', 'photo sites', 'official sites') return ret def get_movie_official_sites(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'officialsites') ret = self.mProxy.officialsites_parser.parse(cont) ret['info sets'] = ('external sites', 'misc sites', 'sound clips', 'video sites', 'photo sites', 'official sites') return ret def get_movie_misc_sites(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'miscsites') ret = self.mProxy.misclinks_parser.parse(cont) ret['info sets'] = ('external sites', 'misc sites', 'sound clips', 'video sites', 'photo sites', 'official sites') return ret def get_movie_sound_clips(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'soundsites') ret = self.mProxy.soundclips_parser.parse(cont) ret['info sets'] = ('external sites', 'misc sites', 'sound clips', 'video sites', 'photo sites', 'official sites') return ret def get_movie_video_clips(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'videosites') ret = self.mProxy.videoclips_parser.parse(cont) ret['info sets'] = ('external sites', 'misc sites', 'sound clips', 'video sites', 'photo sites', 'official sites') return ret def get_movie_photo_sites(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'photosites') ret = self.mProxy.photosites_parser.parse(cont) ret['info sets'] = ('external sites', 'misc sites', 'sound clips', 'video sites', 'photo sites', 'official sites') return ret def get_movie_news(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'news') return self.mProxy.news_parser.parse(cont, getRefs=self._getRefs) def _purge_seasons_data(self, data_d): if '_current_season' in data_d['data']: del data_d['data']['_current_season'] if '_seasons' in data_d['data']: del data_d['data']['_seasons'] return data_d def get_movie_episodes(self, movieID, season_nums='all'): cont = self._retrieve(self.urls['movie_main'] % movieID + 'episodes') temp_d = self.mProxy.season_episodes_parser.parse(cont) if isinstance(season_nums, int): season_nums = {season_nums} elif (isinstance(season_nums, (list, tuple)) or not hasattr(season_nums, '__contains__')): season_nums = set(season_nums) if not temp_d and 'data' in temp_d: return {} _seasons = temp_d['data'].get('_seasons') or [] nr_eps = 0 data_d = dict() for season in _seasons: if season_nums != 'all' and season not in season_nums: continue # Prevent Critical error if season is not found #330 try: cont = self._retrieve( self.urls['movie_main'] % movieID + 'episodes?season=' + str(season) ) except: pass other_d = self.mProxy.season_episodes_parser.parse(cont) other_d = self._purge_seasons_data(other_d) other_d['data'].setdefault('episodes', {}) # Prevent Critical error if season is not found #330 try: if not (other_d and other_d['data'] and other_d['data']['episodes'][season]): continue except: pass nr_eps += len(other_d['data']['episodes'].get(season) or []) if data_d: data_d['data']['episodes'][season] = other_d['data']['episodes'][season] else: data_d = other_d if not data_d: data_d['data'] = dict() data_d['data']['number of episodes'] = nr_eps return data_d def get_movie_faqs(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'faq') return self.mProxy.movie_faqs_parser.parse(cont, getRefs=self._getRefs) def get_movie_airing(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'tvschedule') return self.mProxy.airing_parser.parse(cont) get_movie_tv_schedule = get_movie_airing def get_movie_synopsis(self, movieID): return self.get_movie_plot(movieID) def get_movie_parents_guide(self, movieID): cont = self._retrieve(self.urls['movie_main'] % movieID + 'parentalguide') return self.mProxy.parentsguide_parser.parse(cont) def _search_person(self, name, results): cont = self._get_search_content('nm', name, results) return self.spProxy.search_person_parser.parse(cont, results=results)['data'] def get_person_main(self, personID): cont = self._retrieve(self.urls['person_main'] % personID) ret = self.pProxy.maindetails_parser.parse(cont) return ret def get_person_filmography(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'fullcredits') return self.pProxy.filmo_parser.parse(cont, getRefs=self._getRefs) def get_person_biography(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'bio') return self.pProxy.bio_parser.parse(cont, getRefs=self._getRefs) def get_person_awards(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'awards') return self.pProxy.person_awards_parser.parse(cont) def get_person_other_works(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'otherworks') return self.pProxy.otherworks_parser.parse(cont, getRefs=self._getRefs) def get_person_publicity(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'publicity') return self.pProxy.publicity_parser.parse(cont) def get_person_official_sites(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'officialsites') return self.pProxy.person_officialsites_parser.parse(cont) def get_person_news(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'news') return self.pProxy.news_parser.parse(cont) def get_person_genres_links(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'filmogenre') return self.pProxy.person_genres_parser.parse(cont) def get_person_keywords_links(self, personID): cont = self._retrieve(self.urls['person_main'] % personID + 'filmokey') return self.pProxy.person_keywords_parser.parse(cont) def _search_company(self, name, results): cont = self._get_search_content('co', name, results) url = self.urlOpener._last_url return self.scompProxy.search_company_parser.parse(cont, url=url, results=results)['data'] def get_company_main(self, companyID): cont = self._retrieve(self.urls['company_main'] % companyID) ret = self.compProxy.company_main_parser.parse(cont) return ret def _search_keyword(self, keyword, results): # XXX: the IMDb web server seems to have some serious problem with # non-ascii keyword. # E.g.: http://www.imdb.com/keyword/fianc%E9/ # will return a 500 Internal Server Error: Redirect Recursion. try: cont = self._get_search_content('kw', keyword, results) except IMDbDataAccessError: self._http_logger.warn('unable to search for keyword %s', keyword, exc_info=True) return [] return self.skProxy.search_keyword_parser.parse(cont, results=results)['data'] def _get_keyword(self, keyword, results, page=None): try: url = self.urls['keyword_main'] % keyword if page is not None: url = url + "&page=" + str(page) cont = self._retrieve(url) except IMDbDataAccessError: self._http_logger.warn('unable to get keyword %s', keyword, exc_info=True) return [] return self.skProxy.search_moviekeyword_parser.parse(cont, results=results)['data'] def _get_top_bottom_movies(self, kind): if kind == 'top': parser = self.topBottomProxy.top250_parser url = self.urls['top250'] elif kind == 'bottom': parser = self.topBottomProxy.bottom100_parser url = self.urls['bottom100'] elif kind == 'moviemeter': parser = self.topBottomProxy.moviemeter100_parser url = self.urls['moviemeter100'] elif kind == 'toptv': parser = self.topBottomProxy.toptv250_parser url = self.urls['toptv250'] elif kind == 'tvmeter': parser = self.topBottomProxy.tvmeter100_parser url = self.urls['tvmeter100'] elif kind == 'topindian250': parser = self.topBottomProxy.topindian250_parser url = self.urls['topindian250'] elif kind == 'boxoffice': parser = self.topBottomProxy.boxoffice_parser url = self.urls['boxoffice'] else: return [] cont = self._retrieve(url) return parser.parse(cont)['data'] def _get_showtimes(self): cont = self._retrieve(self.urls['showtimes']) return self.stimesProxy.showtime_parser.parse(cont)['data']
33,163
Python
.py
686
38.360058
170
0.612713
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,219
topBottomParser.py
cinemagoer_cinemagoer/imdb/parser/http/topBottomParser.py
# Copyright 2009-2023 Davide Alberani <[email protected]> # 2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the pages for the lists of top 250 and bottom 100 movies. Pages: http://www.imdb.com/chart/top http://www.imdb.com/chart/bottom """ from __future__ import absolute_import, division, print_function, unicode_literals import re from imdb.utils import analyze_title from .piculet import Path, Rule, Rules, reducers from .utils import DOMParserBase, analyze_imdbid class DOMHTMLTop250Parser(DOMParserBase): """A parser for the "top 250 movies" page.""" ranktext = 'top 250 rank' rules = [ Rule( key='chart', extractor=Rules( foreach='//ul[contains(@class, "ipc-metadata-list")]/li', rules=[ Rule( key='movieID', extractor=Path('.//a[contains(@class, "ipc-title-link-wrapper")]/@href', reduce=reducers.first) ), Rule( key='title', extractor=Path('.//h3[contains(@class, "ipc-title__text")]//text()') ), Rule( key='rating', extractor=Path('.//span[contains(@class, "ipc-rating-star")]//text()', reduce=reducers.first, transform=lambda x: round(float(x), 1)) ), Rule( key='year', extractor=Path('.//div[contains(@class, "cli-title-metadata")]/span/text()', reduce=reducers.first) ), Rule( key='votes', extractor=Path('.//span[contains(@class, "ipc-rating-star--voteCount")]//text()') ) ] ) ) ] def postprocess_data(self, data): if (not data) or ('chart' not in data): return [] _re_rank = re.compile('(\d+)\.(.+)') _re_votes = re.compile('([0-9\.]+)([kmb])', re.I) movies = [] for count, entry in enumerate(data['chart']): if ('movieID' not in entry) or ('title' not in entry): continue entry['rank'] = count + 1 rank_match = _re_rank.match(entry['title']) if rank_match and len(rank_match.groups()) == 2: try: entry['rank'] = int(rank_match.group(1)) except Exception: pass entry['title'] = rank_match.group(2).strip() movie_id = analyze_imdbid(entry['movieID']) if movie_id is None: continue del entry['movieID'] entry[self.ranktext] = entry['rank'] del entry['rank'] title = entry['title'] if 'year' in entry: title = entry['title'] + ' (%s)' % entry['year'] del entry['year'] title = analyze_title(title) entry.update(title) if 'votes' in entry: votes = entry['votes'].replace('(', '').replace(')', '').replace('\xa0', '') multiplier = 1 votes_match = _re_votes.match(votes) if votes_match and len(votes_match.groups()) == 2: votes = votes_match.group(1) str_multiplier = votes_match.group(2).lower() if str_multiplier == 'k': multiplier = 1000 elif str_multiplier == 'm': multiplier = 1000 * 1000 elif str_multiplier == 'b': multiplier = 1000 * 1000 * 1000 try: entry['votes'] = int(float(votes) * multiplier) except Exception: pass movies.append((movie_id, entry)) return movies class DOMHTMLBottom100Parser(DOMHTMLTop250Parser): """A parser for the "bottom 100 movies" page.""" ranktext = 'bottom 100 rank' class DOMHTMLMoviemeter100Parser(DOMHTMLTop250Parser): """A parser for the "Most Popular Movies" page.""" ranktext = 'popular movies 100 rank' class DOMHTMLTVmeter100Parser(DOMHTMLTop250Parser): """A parser for the "Most Popular TV Shows" page.""" ranktext = 'popular tv 100 rank' class DOMHTMLTVTop250Parser(DOMHTMLTop250Parser): """A parser for the "Top Rated TV Shows" page.""" ranktext = 'top tv 250 rank' class DOMHTMLTopIndian250Parser(DOMHTMLTop250Parser): """A parser for the "Top Rated Indian Movies" page.""" ranktext = 'top indian 250 rank' class DOMHTMLBoxOfficeParser(DOMParserBase): """A parser for the "top boxoffice movies" page.""" ranktext = 'top box office rank' rules = [ Rule( key='chart', extractor=Rules( foreach='//tbody/tr', rules=[ Rule( key='movieID', extractor=Path('./td[@class="titleColumn"]/a/@href', reduce=reducers.first) ), Rule( key='title', extractor=Path('./td[@class="titleColumn"]/a/text()') ), Rule( key='weekend', extractor=Path('./td[@class="ratingColumn"]/text()') ), Rule( key='gross', extractor=Path('./td[@class="ratingColumn"]/span[@class="secondaryInfo"]/text()') ), Rule( key='weeks', extractor=Path('./td[@class="weeksColumn"]/text()') ), ] ) ) ] def postprocess_data(self, data): if (not data) or ('chart' not in data): return [] movies = [] for entry in data['chart']: if ('movieID' not in entry) or ('title' not in entry): continue movie_id = analyze_imdbid(entry['movieID']) if movie_id is None: continue del entry['movieID'] title = analyze_title(entry['title']) entry.update(title) weekend = entry['weekend'].lstrip().rstrip() entry.update({'weekend': weekend}) movies.append((movie_id, entry)) return movies _OBJECTS = { 'top250_parser': ((DOMHTMLTop250Parser,), None), 'bottom100_parser': ((DOMHTMLBottom100Parser,), None), 'moviemeter100_parser': ((DOMHTMLMoviemeter100Parser,), None), 'toptv250_parser': ((DOMHTMLTVTop250Parser,), None), 'tvmeter100_parser': ((DOMHTMLTVmeter100Parser,), None), 'topindian250_parser': ((DOMHTMLTopIndian250Parser,), None), 'boxoffice_parser': ((DOMHTMLBoxOfficeParser,), None) }
7,892
Python
.py
186
29.494624
119
0.5243
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,220
personParser.py
cinemagoer_cinemagoer/imdb/parser/http/personParser.py
# Copyright 2004-2022 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the IMDb pages on the www.imdb.com server about a person. For example, for "Mel Gibson" the referred pages would be: categorized http://www.imdb.com/name/nm0000154/maindetails biography http://www.imdb.com/name/nm0000154/bio ...and so on. """ from __future__ import absolute_import, division, print_function, unicode_literals import re from imdb.utils import analyze_name from .movieParser import DOMHTMLNewsParser, DOMHTMLOfficialsitesParser, DOMHTMLTechParser from .piculet import Path, Rule, Rules, transformers from .utils import DOMParserBase, analyze_imdbid, build_movie, build_person _re_spaces = re.compile(r'\s+') _reRoles = re.compile(r'(<li>.*? \.\.\.\. )(.*?)(</li>|<br>)', re.I | re.M | re.S) class DOMHTMLMaindetailsParser(DOMParserBase): """Parser for the "maindetails" page of a given person. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: cparser = DOMHTMLMaindetailsParser() result = cparser.parse(categorized_html_string) """ _containsObjects = True _name_imdb_index = re.compile(r'\([IVXLCDM]+\)') _birth_rules = [ Rule( key='birth date', extractor=Path('.//time[@itemprop="birthDate"]/@datetime') ), Rule( key='birth place', extractor=Path('.//a[starts-with(@href, "/search/name?birth_place=")]/text()') ) ] _death_rules = [ Rule( key='death date', extractor=Path('.//time[@itemprop="deathDate"]/@datetime') ), Rule( key='death place', extractor=Path('.//a[starts-with(@href, "/search/name?death_place=")]/text()') ) ] rules = [ Rule( key='name', extractor=Path( '//h1[@data-testid="hero__pageTitle"]//text()', transform=lambda x: analyze_name(x) ) ), Rule( key='birth info', extractor=Rules( section='//div[h4="Born:"]', rules=_birth_rules ) ), Rule( key='death info', extractor=Rules( section='//div[h4="Died:"]', rules=_death_rules, ) ), Rule( key='headshot', extractor=Path('(//section[contains(@class, "ipc-page-section")])[1]//div[contains(@class, "ipc-poster")]/img[@class="ipc-image"]/@src') # noqa: E501 ), Rule( key='akas', extractor=Path( '//div[h4="Alternate Names:"]/text()', transform=lambda x: x.strip().split(' ') ) ), Rule( key='in development', extractor=Rules( foreach='//div[starts-with(@class,"devitem")]', rules=[ Rule( key='link', extractor=Path('./a/@href') ), Rule( key='title', extractor=Path('./a/text()') ) ], transform=lambda x: build_movie( x.get('title') or '', movieID=analyze_imdbid(x.get('link') or ''), roleID=(x.get('roleID') or '').split('/'), status=x.get('status') or None ) ) ), Rule( key='imdbID', extractor=Path('//meta[@property="og:url"]/@content', transform=analyze_imdbid) ) ] preprocessors = [ ('<div class="clear"/> </div>', ''), ('<br/>', '<br />') ] def postprocess_data(self, data): for key in ['name']: if (key in data) and isinstance(data[key], dict): subdata = data[key] del data[key] data.update(subdata) for what in 'birth date', 'death date': if what in data and not data[what]: del data[what] # XXX: the code below is for backwards compatibility # probably could be removed for key in list(data.keys()): if key == 'birth place': data['birth notes'] = data[key] del data[key] if key == 'death place': data['death notes'] = data[key] del data[key] return data class DOMHTMLFilmographyParser(DOMParserBase): """Parser for the "full credits" page of a given person. The page should be provided as a string, as taken from the www.imdb.com server. Example:: filmo_parser = DOMHTMLFilmographyParser() result = filmo_parser.parse(fullcredits_html_string) """ _defGetRefs = True _film_rules = [ Rule( key='link', extractor=Path('.//b/a/@href') ), Rule( key='title', extractor=Path('.//b/a/text()') ), # TODO: Notes not migrated yet Rule( key='notes', extractor=Path('.//div[@class="ipc-metadata-list-summary-item__c"]//ul[contains(@class, "ipc-metadata-list-summary-item__stl")]//label/text()') # noqa: E501 ), Rule( key='year', extractor=Path( './/span[@class="year_column"]//text()', transform=lambda x: x.strip(), ), ), Rule( key='status', extractor=Path('./a[@class="in_production"]/text()') ), Rule( key='rolesNoChar', extractor=Path( './/br/following-sibling::text()', transform=lambda x: x.strip(), ), ) ] rules = [ Rule( key='filmography', extractor=Rules( foreach='//div[contains(@id, "filmo-head-")]', rules=[ Rule( key=Path( './/a/text()', transform=lambda x: x.lower() ), extractor=Rules( foreach='./following-sibling::div[1]/div[contains(@class, "filmo-row")]', rules=_film_rules, transform=lambda x: build_movie( x.get('title') or '', year=x.get('year'), movieID=analyze_imdbid(x.get('link') or ''), rolesNoChar=(x.get('rolesNoChar') or '').strip(), additionalNotes=x.get('notes'), status=x.get('status') or None ) ) ) ] ) ) ] def postprocess_data(self, data): filmo = {} for job in (data.get('filmography') or []): if not isinstance(job, dict) or not job: continue filmo.update(job) if filmo: data['filmography'] = filmo return data class DOMHTMLBioParser(DOMParserBase): """Parser for the "biography" page of a given person. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: bioparser = DOMHTMLBioParser() result = bioparser.parse(biography_html_string) """ _defGetRefs = True _birth_rules = [ Rule( key='birth date', extractor=Path( './time/@datetime', transform=lambda s: '%4d-%02d-%02d' % tuple(map(int, s.split('-'))) ) ), Rule( key='birth notes', extractor=Path('./a[starts-with(@href, "/search/name?birth_place=")]/text()') ) ] _death_rules = [ Rule( key='death date', extractor=Path( './time/@datetime', transform=lambda s: '%4d-%02d-%02d' % tuple(map(int, s.split('-'))) ) ), Rule( key='death cause', extractor=Path( './text()', transform=lambda x: ''.join(x).strip()[2:].lstrip() ) ), Rule( key='death notes', extractor=Path( '..//text()', transform=lambda x: _re_spaces.sub(' ', (x or '').strip().split('\n')[-1]) ) ) ] rules = [ Rule( key='headshot', extractor=Path('//img[@class="poster"]/@src') ), Rule( key='birth info', extractor=Rules( section='//table[@id="overviewTable"]' '//td[text()="Born"]/following-sibling::td[1]', rules=_birth_rules ) ), Rule( key='death info', extractor=Rules( section='//table[@id="overviewTable"]' '//td[text()="Died"]/following-sibling::td[1]', rules=_death_rules ) ), Rule( key='nick names', extractor=Path( '//table[@id="overviewTable"]' '//td[starts-with(text(), "Nickname")]/following-sibling::td[1]/text()', reduce=lambda xs: '|'.join(xs), transform=lambda x: [ n.strip().replace(' (', '::(', 1) for n in x.split('|') if n.strip() ] ) ), Rule( key='birth name', extractor=Path( '//table[@id="overviewTable"]' '//td[text()="Birth Name"]/following-sibling::td[1]/text()', transform=lambda x: x.strip() ) ), Rule( key='height', extractor=Path( '//table[@id="overviewTable"]' '//td[text()="Height"]/following-sibling::td[1]/text()', transform=transformers.strip ) ), Rule( key='mini biography', extractor=Rules( foreach='//div[@data-testid="sub-section-mini_bio"]', rules=[ Rule( key='bio', extractor=Path('.//text()') ), Rule( key='by', extractor=Path('.//a[@name="ba"]//text()') ) ], transform=lambda x: "%s::%s" % ( (x.get('bio') or '').split('- IMDb Mini Biography By:')[0].strip(), (x.get('by') or '').strip() or 'Anonymous' ) ) ), Rule( key='spouse', extractor=Rules( foreach='//a[@name="spouse"]/following::table[1]//tr', rules=[ Rule( key='name', extractor=Path('./td[1]//text()') ), Rule( key='info', extractor=Path('./td[2]//text()') ) ], transform=lambda x: ("%s::%s" % ( x.get('name').strip(), (_re_spaces.sub(' ', x.get('info') or '')).strip())).strip(':') ) ), Rule( key='trade mark', extractor=Path( foreach='//div[@class="_imdbpyh4"]/h4[starts-with(text(), "Trade Mark")]' '/.././div[contains(@class, "soda")]', path='.//text()', transform=transformers.strip ) ), Rule( key='trivia', extractor=Path( foreach='//div[@class="_imdbpyh4"]/h4[starts-with(text(), "Trivia")]' '/.././div[contains(@class, "soda")]', path='.//text()', transform=transformers.strip ) ), Rule( key='quotes', extractor=Path( foreach='//div[@class="_imdbpyh4"]/h4[starts-with(text(), "Personal Quotes")]' '/.././div[contains(@class, "soda")]', path='.//text()', transform=transformers.strip ) ), Rule( key='salary history', extractor=Rules( foreach='//a[@name="salary"]/following::table[1]//tr', rules=[ Rule( key='title', extractor=Path('./td[1]//text()') ), Rule( key='info', extractor=Path('./td[2]//text()') ) ], transform=lambda x: "%s::%s" % ( x.get('title').strip(), _re_spaces.sub(' ', (x.get('info') or '')).strip()) ) ) ] preprocessors = [ (re.compile('(<h5>)', re.I), r'</div><div class="_imdbpy">\1'), (re.compile('(<h4)', re.I), r'</div><div class="_imdbpyh4">\1'), (re.compile('(</table>\n</div>\\s+)</div>', re.I + re.DOTALL), r'\1'), (re.compile('(<div id="tn15bot">)'), r'</div>\1'), (re.compile(r'\.<br><br>([^\s])', re.I), r'. \1') ] def postprocess_data(self, data): for key in ['birth info', 'death info']: if key in data and isinstance(data[key], dict): subdata = data[key] del data[key] data.update(subdata) for what in 'birth date', 'death date', 'death cause': if what in data and not data[what]: del data[what] return data class DOMHTMLOtherWorksParser(DOMParserBase): """Parser for the "other works" page of a given person. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: owparser = DOMHTMLOtherWorksParser() result = owparser.parse(otherworks_html_string) """ _defGetRefs = True rules = [ Rule( key='other works', extractor=Path( foreach='//li[@class="ipl-zebra-list__item"]', path='.//text()', transform=transformers.strip ) ) ] class DOMHTMLPersonGenresParser(DOMParserBase): """Parser for the "by genre" and "by keywords" pages of a given person. The page should be provided as a string, as taken from the www.imdb.com server. The final result will be a dictionary, with a key for every relevant section. Example:: gparser = DOMHTMLPersonGenresParser() result = gparser.parse(bygenre_html_string) """ kind = 'genres' _containsObjects = True rules = [ Rule( key='genres', extractor=Rules( foreach='//b/a[@name]/following-sibling::a[1]', rules=[ Rule( key=Path('./text()', transform=str.lower), extractor=Rules( foreach='../../following-sibling::ol[1]/li//a[1]', rules=[ Rule( key='link', extractor=Path('./@href') ), Rule( key='title', extractor=Path('./text()') ), Rule( key='info', extractor=Path('./following-sibling::text()') ) ], transform=lambda x: build_movie( x.get('title') + x.get('info').split('[')[0], analyze_imdbid(x.get('link'))) ) ) ] ) ) ] def postprocess_data(self, data): if len(data) == 0: return {} return {self.kind: data} def _process_person_award(x): awards = {} movies = x.get('movies') year = x.get('year') result = x.get('result') prize = x.get('prize') category = x.get('category') award = x.get('award') sharedWith = x.get('shared with') if year: awards['year'] = int(year.strip()) if result: awards['result'] = result.strip() if prize: awards['prize'] = prize.strip() if category: awards['category'] = category.strip() if movies: awards['movies'] = movies if award: awards['award'] = award.strip() if sharedWith: awards['shared with'] = sharedWith return awards class DOMHTMLPersonAwardsParser(DOMParserBase): _defGetRefs = True rules = [ Rule( key='awards', extractor=Rules( foreach='//table[@class="awards"]/tr', rules=[ Rule( key='year', extractor=Path('./td[@class="award_year"]/a/text()') ), Rule( key='result', extractor=Path('./td[@class="award_outcome"]/b/text()') ), Rule( key='prize', extractor=Path('.//span[@class="award_category"]/text()') ), Rule( key='movies', foreach='./td[@class="award_description"]/a', extractor=Rules( [ Rule( key='title', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ), Rule( key='year', extractor=Path('./following-sibling::span[@class="title_year"][1]/text()') ) ], transform=lambda x: build_movie( x.get('title') or '', movieID=analyze_imdbid(x.get('link')), year=x.get('year') ) ) ), Rule( key='shared with', foreach='./td[@class="award_description"]/div[@class="shared_with"]/following-sibling::ul//a', extractor=Rules( [ Rule( key='name', extractor=Path('./text()') ), Rule( key='link', extractor=Path('./@href') ) ], transform=lambda x: build_person( x.get('name') or '', personID=analyze_imdbid(x.get('link')) ) ) ), Rule( key='category', extractor=Path('./td[@class="award_description"]/text()') ), Rule( key='award', extractor=Path('../preceding-sibling::h3[1]/text()') ), ], transform=_process_person_award ) ) ] _OBJECTS = { 'maindetails_parser': ((DOMHTMLMaindetailsParser,), None), 'bio_parser': ((DOMHTMLBioParser,), None), 'filmo_parser': ((DOMHTMLFilmographyParser,), None), 'otherworks_parser': ((DOMHTMLOtherWorksParser,), None), 'person_officialsites_parser': ((DOMHTMLOfficialsitesParser,), None), 'person_awards_parser': ((DOMHTMLPersonAwardsParser,), None), 'publicity_parser': ((DOMHTMLTechParser,), {'kind': 'publicity'}), 'person_contacts_parser': ((DOMHTMLTechParser,), {'kind': 'contacts'}), 'person_genres_parser': ((DOMHTMLPersonGenresParser,), None), 'person_keywords_parser': ((DOMHTMLPersonGenresParser,), {'kind': 'keywords'}), 'news_parser': ((DOMHTMLNewsParser,), None), }
22,385
Python
.py
608
22.381579
169
0.440501
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,221
searchKeywordParser.py
cinemagoer_cinemagoer/imdb/parser/http/searchKeywordParser.py
# Copyright 2009-2022 Davide Alberani <[email protected]> # 2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the results of a search for a given keyword. For example, when searching for the keyword "alabama", the parsed page would be: http://www.imdb.com/find?q=alabama&s=kw """ from __future__ import absolute_import, division, print_function, unicode_literals from imdb.utils import analyze_title from .piculet import Path, Rule, Rules, reducers from .searchMovieParser import DOMHTMLSearchMovieParser from .utils import analyze_imdbid class DOMHTMLSearchKeywordParser(DOMHTMLSearchMovieParser): """A parser for the keyword search page.""" rules = [ Rule( key='data', extractor=Path( foreach='//li[contains(@class, "find-keyword-result")]', path='.//a[@class="ipc-metadata-list-summary-item__t"]/text()' ) ) ] def custom_analyze_title4kwd(title, yearNote, outline): """Return a dictionary with the needed info.""" title = title.strip() if not title: return {} if yearNote: yearNote = '%s)' % yearNote.split(' ')[0] title = title + ' ' + yearNote retDict = analyze_title(title) if outline: retDict['plot outline'] = outline return retDict class DOMHTMLSearchMovieKeywordParser(DOMHTMLSearchMovieParser): """A parser for the movie search by keyword page.""" rules = [ Rule( key='data', extractor=Rules( foreach='//h3[@class="lister-item-header"]', rules=[ Rule( key='link', extractor=Path('./a/@href', reduce=reducers.first) ), Rule( key='info', extractor=Path('./a//text()') ), Rule( key='ynote', extractor=Path('./span[@class="lister-item-year text-muted unbold"]/text()') ), Rule( key='outline', extractor=Path('./span[@class="outline"]//text()') ) ], transform=lambda x: ( analyze_imdbid(x.get('link')), custom_analyze_title4kwd( x.get('info', ''), x.get('ynote', ''), x.get('outline', '') ) ) ) ) ] def preprocess_string(self, html_string): return html_string.replace(' + >', '>') _OBJECTS = { 'search_keyword_parser': ((DOMHTMLSearchKeywordParser,), {'kind': 'keyword'}), 'search_moviekeyword_parser': ((DOMHTMLSearchMovieKeywordParser,), None) }
3,659
Python
.py
93
29.516129
100
0.579318
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,222
searchMovieAdvancedParser.py
cinemagoer_cinemagoer/imdb/parser/http/searchMovieAdvancedParser.py
# -*- coding: utf-8 -*- # Copyright 2019 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the results of an advanced search for a given title. For example, when searching for the title "the passion", the parsed page would be: http://www.imdb.com/search/title/?title=the+passion """ from __future__ import absolute_import, division, print_function, unicode_literals import re from .piculet import Path, Rule, Rules, preprocessors, reducers from .utils import DOMParserBase, analyze_imdbid, build_movie, build_person _re_secondary_info = re.compile( r'''(\(([IVXLCM]+)\)\s+)?\((\d{4})(–(\s|(\d{4})))?(\s+(.*))?\)|(\(([IVXLCM]+)\))''' ) _KIND_MAP = { 'tv short': 'tv short movie', 'video': 'video movie' } def _parse_secondary_info(info): parsed = {} match = _re_secondary_info.match(info) kind = None if match.group(2): parsed['imdbIndex'] = match.group(2) if match.group(3): parsed['year'] = int(match.group(3)) if match.group(4): kind = 'tv series' if match.group(6): parsed['series years'] = match.group(3) + "-" + match.group(6) if match.group(8): kind = match.group(8).lower() if match.group(10): # Added to support case of imdbIndex but no year parsed['imdbIndex'] = match.group(10) if kind is None: kind = 'movie' parsed['kind'] = _KIND_MAP.get(kind, kind) return parsed class DOMHTMLSearchMovieAdvancedParser(DOMParserBase): """A parser for the title search page.""" person_rules = [ Rule(key='name', extractor=Path('./text()', reduce=reducers.first)), Rule(key='link', extractor=Path('./@href', reduce=reducers.first)) ] rules = [ Rule( key='data', extractor=Rules( foreach='//div[contains(@class, "ipc-title-")]//a', rules=[ Rule( key='link', extractor=Path('./@href', reduce=reducers.first) ), Rule( key='title', extractor=Path('./h3/text()', reduce=reducers.first) ), Rule( key='secondary_info', extractor=Path('./h3/span[@class="lister-item-year text-muted unbold"]/text()', reduce=reducers.first) ), Rule( key='state', extractor=Path('.//b/text()', reduce=reducers.first) ), Rule( key='certificates', extractor=Path('.//span[@class="certificate"]/text()', reduce=reducers.first, transform=lambda s: [s]) ), Rule( key='runtimes', extractor=Path('.//span[@class="runtime"]/text()', reduce=reducers.first, transform=lambda s: [[w for w in s.split() if w.isdigit()][0]]) ), Rule( key='genres', extractor=Path('.//span[@class="genre"]/text()', reduce=reducers.first, transform=lambda s: [w.strip() for w in s.split(',')]) ), Rule( key='rating', extractor=Path('.//div[@name="ir"]/@data-value', reduce=reducers.first, transform=float) ), Rule( key='votes', extractor=Path('.//span[@name="nv"]/@data-value', reduce=reducers.first, transform=int) ), Rule( key='metascore', extractor=Path('.//span[@class="metascore favorable"]/text()', reduce=reducers.first, transform=int) ), Rule( key='gross', extractor=Path('.//span[@name="GROSS"]/@data-value', reduce=reducers.normalize, transform=int) ), Rule( key='plot', extractor=Path('./p[@class="text-muted"]//text()', reduce=reducers.clean) ), Rule( key='directors', extractor=Rules( foreach='.//div[@class="DIRECTORS"]/a', rules=person_rules, transform=lambda x: build_person(x['name'], personID=analyze_imdbid(x['link'])) ) ), Rule( key='cast', extractor=Rules( foreach='.//div[@class="STARS"]/a', rules=person_rules, transform=lambda x: build_person(x['name'], personID=analyze_imdbid(x['link'])) ) ), Rule( key='cover url', extractor=Path('..//a/img/@loadlate') ), Rule( key='episode', extractor=Rules( rules=[ Rule(key='link', extractor=Path('./h3/small/a/@href', reduce=reducers.first)), Rule(key='title', extractor=Path('./h3/small/a/text()', reduce=reducers.first)), Rule(key='secondary_info', extractor=Path('./h3/small/span[@class="lister-item-year text-muted unbold"]/text()', # noqa: E501 reduce=reducers.first)), ] ) ) ] ) ) ] def _init(self): self.url = '' def _reset(self): self.url = '' preprocessors = [ (re.compile(r'Directors?:(.*?)(<span|</p>)', re.DOTALL), r'<div class="DIRECTORS">\1</div>\2'), (re.compile(r'Stars?:(.*?)(<span|</p>)', re.DOTALL), r'<div class="STARS">\1</div>\2'), (re.compile(r'(Gross:.*?<span name=)"nv"', re.DOTALL), r'\1"GROSS"'), ('Add a Plot', '<br class="ADD_A_PLOT"/>'), (re.compile(r'(Episode:)(</small>)(.*?)(</h3>)', re.DOTALL), r'\1\3\2\4') ] def preprocess_dom(self, dom): preprocessors.remove(dom, '//br[@class="ADD_A_PLOT"]/../..') return dom def postprocess_data(self, data): if 'data' not in data: data = {'data': []} results = getattr(self, 'results', None) if results is not None: data['data'][:] = data['data'][:results] result = [] idx = 1 for movie in data['data']: if not movie["title"].startswith(str(idx) + ". "): continue movie["title"] = movie["title"][len(str(idx)) + 2:] episode = movie.pop('episode', None) if episode is not None: series = build_movie(movie.get('title'), movieID=analyze_imdbid(movie['link'])) series['kind'] = 'tv series' series_secondary = movie.get('secondary_info') if series_secondary: series.update(_parse_secondary_info(series_secondary)) movie['episode of'] = series movie['link'] = episode['link'] movie['title'] = episode['title'] ep_secondary = episode.get('secondary_info') if ep_secondary is not None: movie['secondary_info'] = ep_secondary secondary_info = movie.pop('secondary_info', None) if secondary_info is not None: secondary = _parse_secondary_info(secondary_info) movie.update(secondary) if episode is not None: movie['kind'] = 'episode' result.append((analyze_imdbid(movie.pop('link')), movie)) idx += 1 data['data'] = result return data def add_refs(self, data): return data _OBJECTS = { 'search_movie_advanced_parser': ((DOMHTMLSearchMovieAdvancedParser,), None) }
9,949
Python
.py
224
27.553571
136
0.453645
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,223
searchCompanyParser.py
cinemagoer_cinemagoer/imdb/parser/http/searchCompanyParser.py
# Copyright 2008-2022 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the results of a search for a given company. For example, when searching for the name "Columbia Pictures", the parsed page would be: http://www.imdb.com/find?q=Columbia+Pictures&s=co """ from __future__ import absolute_import, division, print_function, unicode_literals from imdb.utils import analyze_company_name from .piculet import Path, Rule, Rules, reducers from .searchMovieParser import DOMHTMLSearchMovieParser from .utils import analyze_imdbid class DOMHTMLSearchCompanyParser(DOMHTMLSearchMovieParser): """A parser for the company search page.""" rules = [ Rule( key='data', extractor=Rules( foreach='//li[contains(@class, "find-company-result")]', rules=[ Rule( key='link', extractor=Path('.//a[@class="ipc-metadata-list-summary-item__t"]/@href', reduce=reducers.first) ), Rule( key='name', extractor=Path('.//a[@class="ipc-metadata-list-summary-item__t"]/text()') ), Rule( key='country', extractor=Path('.//label[@class="ipc-metadata-list-summary-item__li"]/text()', reduce=reducers.first) ), ], transform=lambda x: ( analyze_imdbid(x.get('link')), analyze_company_name(x.get('name') + (' [%s]' % x.get('country') if x.get('country') else '')) ) ) ) ] _OBJECTS = { 'search_company_parser': ((DOMHTMLSearchCompanyParser,), {'kind': 'company'}) }
2,653
Python
.py
60
34.85
119
0.611929
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,224
listParser.py
cinemagoer_cinemagoer/imdb/parser/http/listParser.py
# Copyright 2004-2018 Davide Alberani <[email protected]> # 2008-2018 H. Turgut Uyar <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the classes (and the instances) that are used to parse the the contents of a list. For example, when you want to parse the list "Golden Globes 2020: Trending Titles" the corresponding url would be: https://www.imdb.com/list/ls091843609/ """ from __future__ import absolute_import, division, print_function, unicode_literals import string from imdb.utils import analyze_title from .piculet import Path, Rule, Rules, reducers from .utils import DOMParserBase, analyze_imdbid non_numeric_chars = ''.join(set(string.printable) - set(string.digits)) class DOMHTMLListParser(DOMParserBase): """A parser for the title search page.""" rules = [ Rule( key='chart', extractor=Rules( foreach='//div[@class="lister-item mode-detail"]', rules=[ Rule( key='link', extractor=Path('.//h3[@class="lister-item-header"]/a/@href') ), Rule( key='rank', extractor=Path('.//span[@class="lister-item-index unbold text-primary"]/text()', reduce=reducers.first, transform=lambda x: int(''.join(i for i in x if i.isdigit()))) ), Rule( key='rating', extractor=Path('.//span[@class="ipl-rating-star__rating"]/text()', reduce=reducers.first, transform=lambda x: round(float(x), 1)) ), Rule( key='movieID', extractor=Path('.//h3[@class="lister-item-header"]/a/@href') ), Rule( key='title', extractor=Path('.//h3[@class="lister-item-header"]/a/text()') ), Rule( key='year', extractor=Path('.//span[@class="lister-item-year text-muted unbold"]/text()', transform=lambda x: int(''.join(i for i in x if i.isdigit())[:4])) ), Rule( key='votes', extractor=Path('.//span[@name="nv"]/@data-value', reduce=reducers.first, transform=int) ) ] ) ) ] def postprocess_data(self, data): if (not data) or ('chart' not in data): return [] movies = [] for entry in data['chart']: if ('movieID' not in entry) or ('rank' not in entry) or ('title' not in entry): continue movie_id = analyze_imdbid(entry['movieID']) # actually url parser to filter out id if movie_id is None: continue del entry['movieID'] title = analyze_title(entry['title']) entry.update(title) movies.append((movie_id, entry)) return movies _OBJECTS = { 'list_parser': ((DOMHTMLListParser,), None) }
4,107
Python
.py
93
30.806452
105
0.532416
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,225
__init__.py
cinemagoer_cinemagoer/imdb/parser/sql/__init__.py
# Copyright 2005-2019 Davide Alberani <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This package provides the IMDbSqlAccessSystem class used to access IMDb's data through a SQL database. Every database supported by the SQLAlchemy object relational mapper is available. The :func:`imdb.IMDb` function will return an instance of this class when called with the ``accessSystem`` parameter is set to "sql", "database" or "db". """ from __future__ import absolute_import, division, print_function, unicode_literals import re from difflib import SequenceMatcher from codecs import lookup from imdb import IMDbBase from imdb.utils import normalizeName, normalizeTitle, build_title, \ build_name, analyze_name, analyze_title, \ canonicalTitle, canonicalName, re_titleRef, \ build_company_name, re_episodes, _unicodeArticles, \ analyze_company_name, re_year_index, re_nameRef from imdb.Person import Person from imdb.Movie import Movie from imdb.Company import Company from imdb.parser.sql.logging import logger from imdb._exceptions import IMDbDataAccessError, IMDbError # Logger for miscellaneous functions. _aux_logger = logger.getChild('aux') # ============================= # Things that once upon a time were in imdb.parser.common.locsql. def titleVariations(title, fromPtdf=False): """Build title variations useful for searches; if fromPtdf is true, the input is assumed to be in the plain text data files format.""" if fromPtdf: title1 = '' else: title1 = title title2 = title3 = '' if fromPtdf or re_year_index.search(title): # If it appears to have a (year[/imdbIndex]) indication, # assume that a long imdb canonical name was provided. titldict = analyze_title(title, canonical=1) # title1: the canonical name. title1 = titldict['title'] if titldict['kind'] != 'episode': # title3: the long imdb canonical name. if fromPtdf: title3 = title else: title3 = build_title(titldict, canonical=1, ptdf=1) else: title1 = normalizeTitle(title1) title3 = build_title(titldict, canonical=1, ptdf=1) else: # Just a title. # title1: the canonical title. title1 = canonicalTitle(title) title3 = '' # title2 is title1 without the article, or title1 unchanged. if title1: title2 = title1 t2s = title2.split(', ') if t2s[-1].lower() in _unicodeArticles: title2 = ', '.join(t2s[:-1]) _aux_logger.debug('title variations: 1:[%s] 2:[%s] 3:[%s]', title1, title2, title3) return title1, title2, title3 re_nameIndex = re.compile(r'\(([IVXLCDM]+)\)') def nameVariations(name, fromPtdf=False): """Build name variations useful for searches; if fromPtdf is true, the input is assumed to be in the plain text data files format.""" name1 = name2 = name3 = '' if fromPtdf or re_nameIndex.search(name): # We've a name with an (imdbIndex) namedict = analyze_name(name, canonical=1) # name1 is the name in the canonical format. name1 = namedict['name'] # name3 is the canonical name with the imdbIndex. if fromPtdf: if 'imdbIndex' in namedict: name3 = name else: name3 = build_name(namedict, canonical=1) else: # name1 is the name in the canonical format. name1 = canonicalName(name) name3 = '' # name2 is the name in the normal format, if it differs from name1. name2 = normalizeName(name1) if name1 == name2: name2 = '' _aux_logger.debug('name variations: 1:[%s] 2:[%s] 3:[%s]', name1, name2, name3) return name1, name2, name3 def ratcliff(s1, s2, sm): """Ratcliff-Obershelp similarity.""" STRING_MAXLENDIFFER = 0.7 s1len = len(s1) s2len = len(s2) if s1len < s2len: threshold = float(s1len) / s2len else: threshold = float(s2len) / s1len if threshold < STRING_MAXLENDIFFER: return 0.0 sm.set_seq2(s2.lower()) return sm.ratio() def merge_roles(mop): """Merge multiple roles.""" new_list = [] for m in mop: m_isinnewlist = False m_indexinnewlist = None if isinstance(m, Person): for i, person in enumerate(new_list): if person.isSamePerson(m): m_isinnewlist = True m_indexinnewlist = i break else: if m in new_list: m_isinnewlist = True m_indexinnewlist = new_list.index(m) if m_isinnewlist: keep_this = new_list[m_indexinnewlist] if not isinstance(keep_this.currentRole, list): keep_this.currentRole = [keep_this.currentRole] keep_this.currentRole.append(m.currentRole) else: new_list.append(m) return new_list def scan_names(name_list, name1, name2, name3, results=0, ro_thresold=None, _scan_character=False): """Scan a list of names, searching for best matches against the given variations.""" if ro_thresold is not None: RO_THRESHOLD = ro_thresold else: RO_THRESHOLD = 0.6 sm1 = SequenceMatcher() sm2 = SequenceMatcher() sm3 = SequenceMatcher() sm1.set_seq1(name1.lower()) if name2: sm2.set_seq1(name2.lower()) if name3: sm3.set_seq1(name3.lower()) resd = {} for i, n_data in name_list: nil = n_data['name'] # Distance with the canonical name. ratios = [ratcliff(name1, nil, sm1) + 0.05] namesurname = '' if not _scan_character: nils = nil.split(', ', 1) surname = nils[0] if len(nils) == 2: namesurname = '%s %s' % (nils[1], surname) else: nils = nil.split(' ', 1) surname = nils[-1] namesurname = nil if surname != nil: # Distance with the "Surname" in the database. ratios.append(ratcliff(name1, surname, sm1)) if not _scan_character: ratios.append(ratcliff(name1, namesurname, sm1)) if name2: ratios.append(ratcliff(name2, surname, sm2)) # Distance with the "Name Surname" in the database. if namesurname: ratios.append(ratcliff(name2, namesurname, sm2)) if name3: # Distance with the long imdb canonical name. ratios.append(ratcliff(name3, build_name(n_data, canonical=1), sm3) + 0.1) ratio = max(ratios) if ratio >= RO_THRESHOLD: if i in resd: if ratio > resd[i][0]: resd[i] = (ratio, (i, n_data)) else: resd[i] = (ratio, (i, n_data)) res = list(resd.values()) res.sort() res.reverse() if results > 0: res[:] = res[:results] return res def scan_titles(titles_list, title1, title2, title3, results=0, searchingEpisode=0, onlyEpisodes=0, ro_thresold=None): """Scan a list of titles, searching for best matches against the given variations.""" if ro_thresold is not None: RO_THRESHOLD = ro_thresold else: RO_THRESHOLD = 0.6 sm1 = SequenceMatcher() sm2 = SequenceMatcher() sm3 = SequenceMatcher() sm1.set_seq1(title1.lower()) sm2.set_seq2(title2.lower()) if title3: sm3.set_seq1(title3.lower()) if title3[-1] == '}': searchingEpisode = 1 hasArt = 0 if title2 != title1: hasArt = 1 resd = {} for i, t_data in titles_list: if onlyEpisodes: if t_data.get('kind') != 'episode': continue til = t_data['title'] if til[-1] == ')': dateIdx = til.rfind('(') if dateIdx != -1: til = til[:dateIdx].rstrip() if not til: continue ratio = ratcliff(title1, til, sm1) if ratio >= RO_THRESHOLD: resd[i] = (ratio, (i, t_data)) continue if searchingEpisode: if t_data.get('kind') != 'episode': continue elif t_data.get('kind') == 'episode': continue til = t_data['title'] # Distance with the canonical title (with or without article). # titleS -> titleR # titleS, the -> titleR, the if not searchingEpisode: til = canonicalTitle(til) ratios = [ratcliff(title1, til, sm1) + 0.05] # til2 is til without the article, if present. til2 = til tils = til2.split(', ') matchHasArt = 0 if tils[-1].lower() in _unicodeArticles: til2 = ', '.join(tils[:-1]) matchHasArt = 1 if hasArt and not matchHasArt: # titleS[, the] -> titleR ratios.append(ratcliff(title2, til, sm2)) elif matchHasArt and not hasArt: # titleS -> titleR[, the] ratios.append(ratcliff(title1, til2, sm1)) else: ratios = [0.0] if title3: # Distance with the long imdb canonical title. ratios.append(ratcliff(title3, build_title(t_data, canonical=1, ptdf=1), sm3) + 0.1) ratio = max(ratios) if ratio >= RO_THRESHOLD: if i in resd: if ratio > resd[i][0]: resd[i] = (ratio, (i, t_data)) else: resd[i] = (ratio, (i, t_data)) res = list(resd.values()) res.sort() res.reverse() if results > 0: res[:] = res[:results] return res def scan_company_names(name_list, name1, results=0, ro_thresold=None): """Scan a list of company names, searching for best matches against the given name. Notice that this function takes a list of strings, and not a list of dictionaries.""" if ro_thresold is not None: RO_THRESHOLD = ro_thresold else: RO_THRESHOLD = 0.6 sm1 = SequenceMatcher() sm1.set_seq1(name1.lower()) resd = {} withoutCountry = not name1.endswith(']') for i, n in name_list: o_name = n var = 0.0 if withoutCountry and n.endswith(']'): cidx = n.rfind('[') if cidx != -1: n = n[:cidx].rstrip() var = -0.05 # Distance with the company name. ratio = ratcliff(name1, n, sm1) + var if ratio >= RO_THRESHOLD: if i in resd: if ratio > resd[i][0]: resd[i] = (ratio, (i, analyze_company_name(o_name))) else: resd[i] = (ratio, (i, analyze_company_name(o_name))) res = list(resd.values()) res.sort() res.reverse() if results > 0: res[:] = res[:results] return res _translate = dict(B='1', C='2', D='3', F='1', G='2', J='2', K='2', L='4', M='5', N='5', P='1', Q='2', R='6', S='2', T='3', V='1', X='2', Z='2') _translateget = _translate.get _re_non_ascii = re.compile(r'^[^a-z]*', re.I) SOUNDEX_LEN = 5 def soundex(s): """Return the soundex code for the given string.""" # Maximum length of the soundex code. s = _re_non_ascii.sub('', s) if not s: return None s = s.upper() soundCode = s[0] for c in s[1:]: cw = _translateget(c, '0') if cw != '0' and soundCode[-1] != cw: soundCode += cw return soundCode[:SOUNDEX_LEN] or None def _sortKeywords(keyword, kwds): """Sort a list of keywords, based on the searched one.""" sm = SequenceMatcher() sm.set_seq1(keyword.lower()) ratios = [(ratcliff(keyword, k, sm), k) for k in kwds] checkContained = False if len(keyword) > 4: checkContained = True for idx, data in enumerate(ratios): ratio, key = data if key.startswith(keyword): ratios[idx] = (ratio + 0.5, key) elif checkContained and keyword in key: ratios[idx] = (ratio + 0.3, key) ratios.sort() ratios.reverse() return [r[1] for r in ratios] def filterSimilarKeywords(keyword, kwdsIterator): """Return a sorted list of keywords similar to the one given.""" seenDict = {} kwdSndx = soundex(keyword) matches = [] matchesappend = matches.append checkContained = False if len(keyword) > 4: checkContained = True for movieID, key in kwdsIterator: if key in seenDict: continue seenDict[key] = None if checkContained and keyword in key: matchesappend(key) continue if kwdSndx == soundex(key): matchesappend(key) return _sortKeywords(keyword, matches) # ============================= _litlist = ['screenplay/teleplay', 'novel', 'adaption', 'book', 'production process protocol', 'interviews', 'printed media reviews', 'essays', 'other literature'] _litd = dict([(x, ('literature', x)) for x in _litlist]) _buslist = ['budget', 'weekend gross', 'gross', 'opening weekend', 'rentals', 'admissions', 'filming dates', 'production dates', 'studios', 'copyright holder'] _busd = dict([(x, ('business', x)) for x in _buslist]) def _reGroupDict(d, newgr): """Regroup keys in the d dictionary in subdictionaries, based on the scheme in the newgr dictionary. E.g.: in the newgr, an entry 'LD label': ('laserdisc', 'label') tells the _reGroupDict() function to take the entry with label 'LD label' (as received from the sql database) and put it in the subsection (another dictionary) named 'laserdisc', using the key 'label'.""" r = {} newgrks = list(newgr.keys()) for k, v in list(d.items()): if k in newgrks: r.setdefault(newgr[k][0], {})[newgr[k][1]] = v else: r[k] = v return r def _groupListBy(l, index): """Regroup items in a list in a list of lists, grouped by the value at the given index.""" tmpd = {} for item in l: tmpd.setdefault(item[index], []).append(item) res = list(tmpd.values()) return res def sub_dict(d, keys): """Return the subdictionary of 'd', with just the keys listed in 'keys'.""" return dict([(k, d[k]) for k in keys if k in d]) def get_movie_data(movieID, kindDict, fromAka=0, _table=None): """Return a dictionary containing data about the given movieID; if fromAka is true, the AkaTitle table is searched; _table is reserved for the imdbpy2sql.py script.""" if _table is not None: Table = _table else: if not fromAka: Table = Title else: Table = AkaTitle try: m = Table.get(movieID) except Exception as e: _aux_logger.warn('Unable to fetch information for movieID %s: %s', movieID, e) mdict = {} return mdict mdict = {'title': m.title, 'kind': kindDict[m.kindID], 'year': m.productionYear, 'imdbIndex': m.imdbIndex, 'season': m.seasonNr, 'episode': m.episodeNr} if not fromAka: if m.seriesYears is not None: mdict['series years'] = str(m.seriesYears) if mdict['imdbIndex'] is None: del mdict['imdbIndex'] if mdict['year'] is None: del mdict['year'] else: try: mdict['year'] = int(mdict['year']) except (TypeError, ValueError): del mdict['year'] if mdict['season'] is None: del mdict['season'] else: try: mdict['season'] = int(mdict['season']) except: pass if mdict['episode'] is None: del mdict['episode'] else: try: mdict['episode'] = int(mdict['episode']) except: pass episodeOfID = m.episodeOfID if episodeOfID is not None: ser_dict = get_movie_data(episodeOfID, kindDict, fromAka) mdict['episode of'] = Movie(data=ser_dict, movieID=episodeOfID, accessSystem='sql') if fromAka: ser_note = AkaTitle.get(episodeOfID).note if ser_note: mdict['episode of'].notes = ser_note return mdict def _iterKeywords(results): """Iterate over (key.id, key.keyword) columns of a selection of the Keyword table.""" for key in results: yield key.id, key.keyword def getSingleInfo(table, movieID, infoType, notAList=False): """Return a dictionary in the form {infoType: infoListOrString}, retrieving a single set of information about a given movie, from the specified table.""" infoTypeID = InfoType.select(InfoType.q.info == infoType) if infoTypeID.count() == 0: return {} res = table.select(AND(table.q.movieID == movieID, table.q.infoTypeID == infoTypeID[0].id)) retList = [] for r in res: info = r.info note = r.note if note: info += '::%s' % note retList.append(info) if not retList: return {} if not notAList: return {infoType: retList} else: return {infoType: retList[0]} def _cmpTop(a, b, what='top 250 rank'): """Compare function used to sort top 250/bottom 10 rank.""" av = int(a[1].get(what)) bv = int(b[1].get(what)) if av == bv: return 0 return (-1, 1)[av > bv] def _cmpBottom(a, b): """Compare function used to sort top 250/bottom 10 rank.""" return _cmpTop(a, b, what='bottom 10 rank') class IMDbSqlAccessSystem(IMDbBase): """The class used to access IMDb's data through a SQL database.""" accessSystem = 'sql' def __init__(self, uri, adultSearch=True, *arguments, **keywords): """Initialize the access system.""" IMDbBase.__init__(self, *arguments, **keywords) DB_TABLES = [] try: from .alchemyadapter import getDBTables, NotFoundError, \ setConnection, AND, OR, IN, \ ISNULL, CONTAINSSTRING, toUTF8 # XXX: look ma'... black magic! It's used to make # TableClasses and some functions accessible # through the whole module. for k, v in [('NotFoundError', NotFoundError), ('AND', AND), ('OR', OR), ('IN', IN), ('ISNULL', ISNULL), ('CONTAINSSTRING', CONTAINSSTRING)]: globals()[k] = v self.toUTF8 = toUTF8 DB_TABLES = getDBTables(uri) for t in DB_TABLES: globals()[t._imdbpyName] = t except ImportError as e: raise IMDbError('unable to import SQLAlchemy') # Set the connection to the database. logger.debug('connecting to %s', uri) try: self._connection = setConnection(uri, DB_TABLES) except AssertionError as e: raise IMDbDataAccessError( 'unable to connect to the database server; ' + 'complete message: "%s"' % str(e)) self.Error = self._connection.module.Error # Maps some IDs to the corresponding strings. self._kind = {} self._kindRev = {} logger.debug('reading constants from the database') try: for kt in KindType.select(): self._kind[kt.id] = kt.kind self._kindRev[str(kt.kind)] = kt.id except self.Error: # NOTE: you can also get the error, but - at least with # MySQL - it also contains the password, and I don't # like the idea to print it out. raise IMDbDataAccessError( 'unable to connect to the database server') self._role = {} for rl in RoleType.select(): self._role[rl.id] = str(rl.role) self._info = {} self._infoRev = {} for inf in InfoType.select(): self._info[inf.id] = str(inf.info) self._infoRev[str(inf.info)] = inf.id self._compType = {} for cType in CompanyType.select(): self._compType[cType.id] = cType.kind info = [(it.id, it.info) for it in InfoType.select()] self._compcast = {} for cc in CompCastType.select(): self._compcast[cc.id] = str(cc.kind) self._link = {} for lt in LinkType.select(): self._link[lt.id] = str(lt.link) self._moviesubs = {} # Build self._moviesubs, a dictionary used to rearrange # the data structure for a movie object. for vid, vinfo in info: if not vinfo.startswith('LD '): continue self._moviesubs[vinfo] = ('laserdisc', vinfo[3:]) self._moviesubs.update(_litd) self._moviesubs.update(_busd) self.do_adult_search(adultSearch) def _findRefs(self, o, trefs, nrefs): """Find titles or names references in strings.""" if isinstance(o, str): for title in re_titleRef.findall(o): a_title = analyze_title(title, canonical=0) rtitle = build_title(a_title, ptdf=1) if rtitle in trefs: continue movieID = self._getTitleID(rtitle) if movieID is None: movieID = self._getTitleID(title) if movieID is None: continue m = Movie(title=rtitle, movieID=movieID, accessSystem=self.accessSystem) trefs[rtitle] = m rtitle2 = canonicalTitle(a_title.get('title', '')) if rtitle2 and rtitle2 != rtitle and rtitle2 != title: trefs[rtitle2] = m if title != rtitle: trefs[title] = m for name in re_nameRef.findall(o): a_name = analyze_name(name, canonical=1) rname = build_name(a_name, canonical=1) if rname in nrefs: continue personID = self._getNameID(rname) if personID is None: personID = self._getNameID(name) if personID is None: continue p = Person(name=rname, personID=personID, accessSystem=self.accessSystem) nrefs[rname] = p rname2 = normalizeName(a_name.get('name', '')) if rname2 and rname2 != rname: nrefs[rname2] = p if name != rname and name != rname2: nrefs[name] = p elif isinstance(o, (list, tuple)): for item in o: self._findRefs(item, trefs, nrefs) elif isinstance(o, dict): for value in list(o.values()): self._findRefs(value, trefs, nrefs) return trefs, nrefs def _extractRefs(self, o): """Scan for titles or names references in strings.""" trefs = {} nrefs = {} try: return self._findRefs(o, trefs, nrefs) except RuntimeError as e: # Symbian/python 2.2 has a poor regexp implementation. import warnings warnings.warn('RuntimeError in ' "imdb.parser.sql.IMDbSqlAccessSystem; " "if it's not a recursion limit exceeded and we're not " "running in a Symbian environment, it's a bug:\n%s" % e) return trefs, nrefs def _changeAKAencoding(self, akanotes, akatitle): """Return akatitle in the correct charset, as specified in the akanotes field; if akatitle doesn't need to be modified, return None.""" oti = akanotes.find('(original ') if oti == -1: return None ote = akanotes[oti + 10:].find(' title)') if ote != -1: cs_info = akanotes[oti + 10:oti + 10 + ote].lower().split() for e in cs_info: # excludes some strings that clearly are not encoding. if e in ('script', '', 'cyrillic', 'greek'): continue if e.startswith('iso-') and e.find('latin') != -1: e = e[4:].replace('-', '') try: lookup(e) lat1 = akatitle.encode('latin_1', 'replace') return str(lat1, e, 'replace') except (LookupError, ValueError, TypeError): continue return None def _buildNULLCondition(self, col, val): """Build a comparison for columns where values can be NULL.""" if val is None: return ISNULL(col) else: if isinstance(val, int): return col == val else: return col == self.toUTF8(val) def _getTitleID(self, title): """Given a long imdb canonical title, returns a movieID or None if not found.""" td = analyze_title(title) condition = None if td['kind'] == 'episode': epof = td['episode of'] seriesID = [s.id for s in Title.select( AND(Title.q.title == self.toUTF8(epof['title']), self._buildNULLCondition(Title.q.imdbIndex, epof.get('imdbIndex')), Title.q.kindID == self._kindRev[epof['kind']], self._buildNULLCondition(Title.q.productionYear, epof.get('year'))))] if seriesID: condition = AND(IN(Title.q.episodeOfID, seriesID), Title.q.title == self.toUTF8(td['title']), self._buildNULLCondition(Title.q.imdbIndex, td.get('imdbIndex')), Title.q.kindID == self._kindRev[td['kind']], self._buildNULLCondition(Title.q.productionYear, td.get('year'))) if condition is None: condition = AND(Title.q.title == self.toUTF8(td['title']), self._buildNULLCondition(Title.q.imdbIndex, td.get('imdbIndex')), Title.q.kindID == self._kindRev[td['kind']], self._buildNULLCondition(Title.q.productionYear, td.get('year'))) res = Title.select(condition) try: if res.count() != 1: return None except (UnicodeDecodeError, TypeError): return None return res[0].id def _getNameID(self, name): """Given a long imdb canonical name, returns a personID or None if not found.""" nd = analyze_name(name) res = Name.select(AND(Name.q.name == self.toUTF8(nd['name']), self._buildNULLCondition(Name.q.imdbIndex, nd.get('imdbIndex')))) try: if res.count() != 1: return None except (UnicodeDecodeError, TypeError): return None return res[0].id def _normalize_movieID(self, movieID): """Normalize the given movieID.""" try: return int(movieID) except (ValueError, OverflowError): raise IMDbError('movieID "%s" can\'t be converted to integer' % movieID) def _normalize_personID(self, personID): """Normalize the given personID.""" try: return int(personID) except (ValueError, OverflowError): raise IMDbError('personID "%s" can\'t be converted to integer' % personID) def _normalize_characterID(self, characterID): """Normalize the given characterID.""" try: return int(characterID) except (ValueError, OverflowError): raise IMDbError('characterID "%s" can\'t be converted to integer' % characterID) def _normalize_companyID(self, companyID): """Normalize the given companyID.""" try: return int(companyID) except (ValueError, OverflowError): raise IMDbError('companyID "%s" can\'t be converted to integer' % companyID) def get_imdbMovieID(self, movieID): """Translate a movieID in an imdbID. If not in the database, try an Exact Primary Title search on IMDb; return None if it's unable to get the imdbID. """ try: movie = Title.get(movieID) except NotFoundError: return None imdbID = movie.imdbID if imdbID is not None: return '%07d' % imdbID m_dict = get_movie_data(movie.id, self._kind) titline = build_title(m_dict, ptdf=False) imdbID = self.title2imdbID(titline, m_dict['kind']) # If the imdbID was retrieved from the web and was not in the # database, update the database (ignoring errors, because it's # possibile that the current user has not update privileges). # There're times when I think I'm a genius; this one of # those times... <g> if imdbID is not None and not isinstance(imdbID, list): try: movie.imdbID = int(imdbID) except: pass return imdbID def get_imdbPersonID(self, personID): """Translate a personID in an imdbID. If not in the database, try an Exact Primary Name search on IMDb; return None if it's unable to get the imdbID. """ try: person = Name.get(personID) except NotFoundError: return None imdbID = person.imdbID if imdbID is not None: return '%07d' % imdbID n_dict = {'name': person.name, 'imdbIndex': person.imdbIndex} namline = build_name(n_dict, canonical=False) imdbID = self.name2imdbID(namline) if imdbID is not None and not isinstance(imdbID, list): try: person.imdbID = int(imdbID) except: pass return imdbID def get_imdbCharacterID(self, characterID): """Translate a characterID in an imdbID. If not in the database, try an Exact Primary Name search on IMDb; return None if it's unable to get the imdbID. """ try: character = CharName.get(characterID) except NotFoundError: return None imdbID = character.imdbID if imdbID is not None: return '%07d' % imdbID n_dict = {'name': character.name, 'imdbIndex': character.imdbIndex} namline = build_name(n_dict, canonical=False) imdbID = self.character2imdbID(namline) if imdbID is not None and not isinstance(imdbID, list): try: character.imdbID = int(imdbID) except: pass return imdbID def get_imdbCompanyID(self, companyID): """Translate a companyID in an imdbID. If not in the database, try an Exact Primary Name search on IMDb; return None if it's unable to get the imdbID. """ try: company = CompanyName.get(companyID) except NotFoundError: return None imdbID = company.imdbID if imdbID is not None: return '%07d' % imdbID n_dict = {'name': company.name, 'country': company.countryCode} namline = build_company_name(n_dict) imdbID = self.company2imdbID(namline) if imdbID is not None and not isinstance(imdbID, list): try: company.imdbID = int(imdbID) except: pass return imdbID def do_adult_search(self, doAdult): """If set to 0 or False, movies in the Adult category are not episodeOf = title_dict.get('episode of') shown in the results of a search.""" self.doAdult = doAdult def _search_movie(self, title, results, _episodes=False): title = title.strip() if not title: return [] title_dict = analyze_title(title, canonical=1) s_title = title_dict['title'] if not s_title: return [] episodeOf = title_dict.get('episode of') if episodeOf: _episodes = False s_title_split = s_title.split(', ') if len(s_title_split) > 1 and \ s_title_split[-1].lower() in _unicodeArticles: s_title_rebuilt = ', '.join(s_title_split[:-1]) if s_title_rebuilt: s_title = s_title_rebuilt soundexCode = soundex(s_title) # XXX: improve the search restricting the kindID if the # "kind" of the input differs from "movie"? condition = conditionAka = None if _episodes: condition = AND(Title.q.phoneticCode == soundexCode, Title.q.kindID == self._kindRev['episode']) conditionAka = AND(AkaTitle.q.phoneticCode == soundexCode, AkaTitle.q.kindID == self._kindRev['episode']) elif title_dict['kind'] == 'episode' and episodeOf is not None: # set canonical=0 ? Should not make much difference. series_title = build_title(episodeOf, canonical=1) # XXX: is it safe to get "results" results? # Too many? Too few? serRes = results if serRes < 3 or serRes > 10: serRes = 10 searchSeries = self._search_movie(series_title, serRes) seriesIDs = [result[0] for result in searchSeries] if seriesIDs: condition = AND(Title.q.phoneticCode == soundexCode, IN(Title.q.episodeOfID, seriesIDs), Title.q.kindID == self._kindRev['episode']) conditionAka = AND(AkaTitle.q.phoneticCode == soundexCode, IN(AkaTitle.q.episodeOfID, seriesIDs), AkaTitle.q.kindID == self._kindRev['episode']) else: # XXX: bad situation: we have found no matching series; # try searching everything (both episodes and # non-episodes) for the title. condition = AND(Title.q.phoneticCode == soundexCode, IN(Title.q.episodeOfID, seriesIDs)) conditionAka = AND(AkaTitle.q.phoneticCode == soundexCode, IN(AkaTitle.q.episodeOfID, seriesIDs)) if condition is None: # XXX: excludes episodes? condition = AND(Title.q.kindID != self._kindRev['episode'], Title.q.phoneticCode == soundexCode) conditionAka = AND(AkaTitle.q.kindID != self._kindRev['episode'], AkaTitle.q.phoneticCode == soundexCode) # Up to 3 variations of the title are searched, plus the # long imdb canonical title, if provided. if not _episodes: title1, title2, title3 = titleVariations(title) else: title1 = title title2 = '' title3 = '' try: qr = [(q.id, get_movie_data(q.id, self._kind)) for q in Title.select(condition)] q2 = [(q.movieID, get_movie_data(q.id, self._kind, fromAka=1)) for q in AkaTitle.select(conditionAka)] qr += q2 except NotFoundError as e: raise IMDbDataAccessError( 'unable to search the database: "%s"' % str(e)) resultsST = results * 3 res = scan_titles(qr, title1, title2, title3, resultsST, searchingEpisode=episodeOf is not None, onlyEpisodes=_episodes, ro_thresold=0.0) res[:] = [x[1] for x in res] if res and not self.doAdult: mids = [x[0] for x in res] genreID = self._infoRev['genres'] adultlist = [al.movieID for al in MovieInfo.select( AND(MovieInfo.q.infoTypeID == genreID, MovieInfo.q.info == 'Adult', IN(MovieInfo.q.movieID, mids)))] res[:] = [x for x in res if x[0] not in adultlist] new_res = [] # XXX: can there be duplicates? for r in res: if r not in q2: new_res.append(r) continue mdict = r[1] aka_title = build_title(mdict, ptdf=1) orig_dict = get_movie_data(r[0], self._kind) orig_title = build_title(orig_dict, ptdf=1) if aka_title == orig_title: new_res.append(r) continue orig_dict['akas'] = [aka_title] new_res.append((r[0], orig_dict)) if results > 0: new_res[:] = new_res[:results] return new_res def _search_movie_advanced(self, title=None, adult=None, results=None, sort=None, sort_dir=None): return self._search_movie(title, results) def _search_episode(self, title, results): return self._search_movie(title, results, _episodes=True) def get_movie_main(self, movieID): # Every movie information is retrieved from here. infosets = self.get_movie_infoset() try: res = get_movie_data(movieID, self._kind) except NotFoundError as e: raise IMDbDataAccessError( 'unable to get movieID "%s": "%s"' % (movieID, str(e))) if not res: raise IMDbDataAccessError('unable to get movieID "%s"' % movieID) # Collect cast information. castdata = [[cd.personID, cd.personRoleID, cd.note, cd.nrOrder, self._role[cd.roleID]] for cd in CastInfo.select(CastInfo.q.movieID == movieID)] for p in castdata: person = Name.get(p[0]) p += [person.name, person.imdbIndex] if p[4] in ('actor', 'actress'): p[4] = 'cast' # Regroup by role/duty (cast, writer, director, ...) castdata[:] = _groupListBy(castdata, 4) for group in castdata: duty = group[0][4] for pdata in group: curRole = pdata[1] curRoleID = None if curRole is not None: robj = CharName.get(curRole) curRole = robj.name curRoleID = robj.id p = Person(personID=pdata[0], name=pdata[5], currentRole=curRole or '', roleID=curRoleID, notes=pdata[2] or '', accessSystem='sql') if pdata[6]: p['imdbIndex'] = pdata[6] p.billingPos = pdata[3] res.setdefault(duty, []).append(p) if duty == 'cast': res[duty] = merge_roles(res[duty]) res[duty].sort() # Info about the movie. minfo = [(self._info[m.infoTypeID], m.info, m.note) for m in MovieInfo.select(MovieInfo.q.movieID == movieID)] minfo += [('keywords', Keyword.get(m.keywordID).keyword, None) for m in MovieKeyword.select(MovieKeyword.q.movieID == movieID)] minfo = _groupListBy(minfo, 0) for group in minfo: sect = group[0][0] for mdata in group: data = mdata[1] if mdata[2]: data += '::%s' % mdata[2] res.setdefault(sect, []).append(data) # Companies info about a movie. cinfo = [(self._compType[m.companyTypeID], m.companyID, m.note) for m in MovieCompanies.select(MovieCompanies.q.movieID == movieID)] cinfo = _groupListBy(cinfo, 0) for group in cinfo: sect = group[0][0] for mdata in group: cDb = CompanyName.get(mdata[1]) cDbTxt = cDb.name if cDb.countryCode: cDbTxt += ' %s' % cDb.countryCode company = Company(name=cDbTxt, companyID=mdata[1], notes=mdata[2] or '', accessSystem=self.accessSystem) res.setdefault(sect, []).append(company) # AKA titles. akat = [(get_movie_data(at.id, self._kind, fromAka=1), at.note) for at in AkaTitle.select(AkaTitle.q.movieID == movieID)] if akat: res['akas'] = [] for td, note in akat: nt = build_title(td, ptdf=1) if note: net = self._changeAKAencoding(note, nt) if net is not None: nt = net nt += '::%s' % note if nt not in res['akas']: res['akas'].append(nt) # Complete cast/crew. compcast = [(self._compcast[cc.subjectID], self._compcast[cc.statusID]) for cc in CompleteCast.select(CompleteCast.q.movieID == movieID)] if compcast: for entry in compcast: val = str(entry[1]) res['complete %s' % entry[0]] = val # Movie connections. mlinks = [[ml.linkedMovieID, self._link[ml.linkTypeID]] for ml in MovieLink.select(MovieLink.q.movieID == movieID)] if mlinks: for ml in mlinks: lmovieData = get_movie_data(ml[0], self._kind) if lmovieData: m = Movie(movieID=ml[0], data=lmovieData, accessSystem='sql') ml[0] = m res['connections'] = {} mlinks[:] = _groupListBy(mlinks, 1) for group in mlinks: lt = group[0][1] res['connections'][lt] = [i[0] for i in group] # Episodes. episodes = {} eps_list = list(Title.select(Title.q.episodeOfID == movieID)) eps_list.sort(key=lambda e: '%s.%s' % (e.seasonNr or '', e.episodeNr or '')) if eps_list: ps_data = {'title': res['title'], 'kind': res['kind'], 'year': res.get('year'), 'imdbIndex': res.get('imdbIndex')} parentSeries = Movie(movieID=movieID, data=ps_data, accessSystem='sql') for episode in eps_list: episodeID = episode.id episode_data = get_movie_data(episodeID, self._kind) m = Movie(movieID=episodeID, data=episode_data, accessSystem='sql') m['episode of'] = parentSeries season = episode_data.get('season', 'UNKNOWN') if season not in episodes: episodes[season] = {} ep_number = episode_data.get('episode') if ep_number is None: ep_number = max((list(episodes[season].keys()) or [0])) + 1 episodes[season][ep_number] = m res['episodes'] = episodes res['number of episodes'] = sum([len(x) for x in list(episodes.values())]) res['number of seasons'] = len(list(episodes.keys())) # Regroup laserdisc information. res = _reGroupDict(res, self._moviesubs) # Do some transformation to preserve consistency with other # data access systems. if 'quotes' in res: for idx, quote in enumerate(res['quotes']): res['quotes'][idx] = quote.split('::') if 'runtimes' in res and len(res['runtimes']) > 0: rt = res['runtimes'][0] episodes = re_episodes.findall(rt) if episodes: res['runtimes'][0] = re_episodes.sub('', rt) if res['runtimes'][0][-2:] == '::': res['runtimes'][0] = res['runtimes'][0][:-2] if 'votes' in res: res['votes'] = int(res['votes'][0]) if 'rating' in res: res['rating'] = float(res['rating'][0]) if 'votes distribution' in res: res['votes distribution'] = res['votes distribution'][0] if 'mpaa' in res: res['mpaa'] = res['mpaa'][0] if 'top 250 rank' in res: try: res['top 250 rank'] = int(res['top 250 rank']) except: pass if 'bottom 10 rank' in res: try: res['bottom 100 rank'] = int(res['bottom 10 rank']) except: pass del res['bottom 10 rank'] for old, new in [('guest', 'guests'), ('trademarks', 'trade-mark'), ('articles', 'article'), ('pictorials', 'pictorial'), ('magazine-covers', 'magazine-cover-photo')]: if old in res: res[new] = res[old] del res[old] trefs, nrefs = {}, {} trefs, nrefs = self._extractRefs(sub_dict(res, Movie.keys_tomodify_list)) return {'data': res, 'titlesRefs': trefs, 'namesRefs': nrefs, 'info sets': infosets} # Just to know what kind of information are available. get_movie_alternate_versions = get_movie_main get_movie_business = get_movie_main get_movie_connections = get_movie_main get_movie_crazy_credits = get_movie_main get_movie_goofs = get_movie_main get_movie_keywords = get_movie_main get_movie_literature = get_movie_main get_movie_locations = get_movie_main get_movie_plot = get_movie_main get_movie_quotes = get_movie_main get_movie_release_dates = get_movie_main get_movie_soundtrack = get_movie_main get_movie_taglines = get_movie_main get_movie_technical = get_movie_main get_movie_trivia = get_movie_main get_movie_vote_details = get_movie_main get_movie_episodes = get_movie_main def _search_person(self, name, results): name = name.strip() if not name: return [] s_name = analyze_name(name)['name'] if not s_name: return [] soundexCode = soundex(s_name) name1, name2, name3 = nameVariations(name) # If the soundex is None, compare only with the first # phoneticCode column. if soundexCode is not None: condition = IN(soundexCode, [Name.q.namePcodeCf, Name.q.namePcodeNf, Name.q.surnamePcode]) conditionAka = IN(soundexCode, [AkaName.q.namePcodeCf, AkaName.q.namePcodeNf, AkaName.q.surnamePcode]) else: condition = ISNULL(Name.q.namePcodeCf) conditionAka = ISNULL(AkaName.q.namePcodeCf) try: qr = [(q.id, {'name': q.name, 'imdbIndex': q.imdbIndex}) for q in Name.select(condition)] q2 = [(q.personID, {'name': q.name, 'imdbIndex': q.imdbIndex}) for q in AkaName.select(conditionAka)] qr += q2 except NotFoundError as e: raise IMDbDataAccessError( 'unable to search the database: "%s"' % str(e)) res = scan_names(qr, name1, name2, name3, results) res[:] = [x[1] for x in res] # Purge empty imdbIndex. returnl = [] for x in res: tmpd = x[1] if tmpd['imdbIndex'] is None: del tmpd['imdbIndex'] returnl.append((x[0], tmpd)) new_res = [] # XXX: can there be duplicates? for r in returnl: if r not in q2: new_res.append(r) continue pdict = r[1] aka_name = build_name(pdict, canonical=1) p = Name.get(r[0]) orig_dict = {'name': p.name, 'imdbIndex': p.imdbIndex} if orig_dict['imdbIndex'] is None: del orig_dict['imdbIndex'] orig_name = build_name(orig_dict, canonical=1) if aka_name == orig_name: new_res.append(r) continue orig_dict['akas'] = [aka_name] new_res.append((r[0], orig_dict)) if results > 0: new_res[:] = new_res[:results] return new_res def get_person_main(self, personID): # Every person information is retrieved from here. infosets = self.get_person_infoset() try: p = Name.get(personID) except NotFoundError as e: raise IMDbDataAccessError( 'unable to get personID "%s": "%s"' % (personID, str(e))) res = {'name': p.name, 'imdbIndex': p.imdbIndex} if res['imdbIndex'] is None: del res['imdbIndex'] if not res: raise IMDbDataAccessError('unable to get personID "%s"' % personID) # Collect cast information. castdata = [(cd.movieID, cd.personRoleID, cd.note, self._role[cd.roleID], get_movie_data(cd.movieID, self._kind)) for cd in CastInfo.select(CastInfo.q.personID == personID)] # Regroup by role/duty (cast, writer, director, ...) castdata[:] = _groupListBy(castdata, 3) episodes = {} seenDuties = [] for group in castdata: for mdata in group: duty = orig_duty = group[0][3] if duty not in seenDuties: seenDuties.append(orig_duty) note = mdata[2] or '' if 'episode of' in mdata[4]: duty = 'episodes' if orig_duty not in ('actor', 'actress'): if note: note = ' %s' % note note = '[%s]%s' % (orig_duty, note) curRole = mdata[1] curRoleID = None if curRole is not None: robj = CharName.get(curRole) curRole = robj.name curRoleID = robj.id m = Movie(movieID=mdata[0], data=mdata[4], currentRole=curRole or '', roleID=curRoleID, notes=note, accessSystem='sql') if duty != 'episodes': res.setdefault(duty, []).append(m) else: episodes.setdefault(m['episode of'], []).append(m) if episodes: for k in episodes: episodes[k].sort() episodes[k].reverse() res['episodes'] = episodes for duty in seenDuties: if duty in res: if duty in ('actor', 'actress', 'himself', 'herself', 'themselves'): res[duty] = merge_roles(res[duty]) res[duty].sort() # Info about the person. pinfo = [(self._info[pi.infoTypeID], pi.info, pi.note) for pi in PersonInfo.select(PersonInfo.q.personID == personID)] # Regroup by duty. pinfo = _groupListBy(pinfo, 0) for group in pinfo: sect = group[0][0] for pdata in group: data = pdata[1] if pdata[2]: data += '::%s' % pdata[2] res.setdefault(sect, []).append(data) # AKA names. akan = [(an.name, an.imdbIndex) for an in AkaName.select(AkaName.q.personID == personID)] if akan: res['akas'] = [] for n in akan: nd = {'name': n[0]} if n[1]: nd['imdbIndex'] = n[1] nt = build_name(nd, canonical=1) res['akas'].append(nt) # Do some transformation to preserve consistency with other # data access systems. for key in ('birth date', 'birth notes', 'death date', 'death notes', 'birth name', 'height'): if key in res: res[key] = res[key][0] if 'guest' in res: res['notable tv guest appearances'] = res['guest'] del res['guest'] miscnames = res.get('nick names', []) if 'birth name' in res: miscnames.append(res['birth name']) if 'akas' in res: for mname in miscnames: if mname in res['akas']: res['akas'].remove(mname) if not res['akas']: del res['akas'] trefs, nrefs = self._extractRefs(sub_dict(res, Person.keys_tomodify_list)) return {'data': res, 'titlesRefs': trefs, 'namesRefs': nrefs, 'info sets': infosets} # Just to know what kind of information are available. get_person_filmography = get_person_main get_person_biography = get_person_main get_person_other_works = get_person_main get_person_episodes = get_person_main def _search_character(self, name, results): name = name.strip() if not name: return [] s_name = analyze_name(name)['name'] if not s_name: return [] s_name = normalizeName(s_name) soundexCode = soundex(s_name) surname = s_name.split(' ')[-1] surnameSoundex = soundex(surname) name2 = '' soundexName2 = None nsplit = s_name.split() if len(nsplit) > 1: name2 = '%s %s' % (nsplit[-1], ' '.join(nsplit[:-1])) if s_name == name2: name2 = '' else: soundexName2 = soundex(name2) # If the soundex is None, compare only with the first # phoneticCode column. if soundexCode is not None: if soundexName2 is not None: condition = OR(surnameSoundex == CharName.q.surnamePcode, IN(CharName.q.namePcodeNf, [soundexCode, soundexName2]), IN(CharName.q.surnamePcode, [soundexCode, soundexName2])) else: condition = OR(surnameSoundex == CharName.q.surnamePcode, IN(soundexCode, [CharName.q.namePcodeNf, CharName.q.surnamePcode])) else: condition = ISNULL(Name.q.namePcodeNf) try: qr = [(q.id, {'name': q.name, 'imdbIndex': q.imdbIndex}) for q in CharName.select(condition)] except NotFoundError as e: raise IMDbDataAccessError( 'unable to search the database: "%s"' % str(e)) res = scan_names(qr, s_name, name2, '', results, _scan_character=True) res[:] = [x[1] for x in res] # Purge empty imdbIndex. returnl = [] for x in res: tmpd = x[1] if tmpd['imdbIndex'] is None: del tmpd['imdbIndex'] returnl.append((x[0], tmpd)) return returnl def get_character_main(self, characterID, results=1000): # Every character information is retrieved from here. infosets = self.get_character_infoset() try: c = CharName.get(characterID) except NotFoundError as e: raise IMDbDataAccessError( 'unable to get characterID "%s": "%s"' % (characterID, e)) res = {'name': c.name, 'imdbIndex': c.imdbIndex} if res['imdbIndex'] is None: del res['imdbIndex'] if not res: raise IMDbDataAccessError('unable to get characterID "%s"' % characterID) # Collect filmography information. items = CastInfo.select(CastInfo.q.personRoleID == characterID) if results > 0: items = items[:results] filmodata = [(cd.movieID, cd.personID, cd.note, get_movie_data(cd.movieID, self._kind)) for cd in items if self._role[cd.roleID] in ('actor', 'actress')] fdata = [] for f in filmodata: curRole = None curRoleID = f[1] note = f[2] or '' if curRoleID is not None: robj = Name.get(curRoleID) curRole = robj.name m = Movie(movieID=f[0], data=f[3], currentRole=curRole or '', roleID=curRoleID, roleIsPerson=True, notes=note, accessSystem='sql') fdata.append(m) fdata = merge_roles(fdata) fdata.sort() if fdata: res['filmography'] = fdata return {'data': res, 'info sets': infosets} get_character_filmography = get_character_main get_character_biography = get_character_main def _search_company(self, name, results): name = name.strip() if not name: return [] soundexCode = soundex(name) # If the soundex is None, compare only with the first # phoneticCode column. if soundexCode is None: condition = ISNULL(CompanyName.q.namePcodeNf) else: if name.endswith(']'): condition = CompanyName.q.namePcodeSf == soundexCode else: condition = CompanyName.q.namePcodeNf == soundexCode try: qr = [(q.id, {'name': q.name, 'country': q.countryCode}) for q in CompanyName.select(condition)] except NotFoundError as e: raise IMDbDataAccessError( 'unable to search the database: "%s"' % str(e)) qr[:] = [(x[0], build_company_name(x[1])) for x in qr] res = scan_company_names(qr, name, results) res[:] = [x[1] for x in res] # Purge empty country keys. returnl = [] for x in res: tmpd = x[1] country = tmpd.get('country') if country is None and 'country' in tmpd: del tmpd['country'] returnl.append((x[0], tmpd)) return returnl def get_company_main(self, companyID, results=0): # Every company information is retrieved from here. infosets = self.get_company_infoset() try: c = CompanyName.get(companyID) except NotFoundError as e: raise IMDbDataAccessError( 'unable to get companyID "%s": "%s"' % (companyID, e)) res = {'name': c.name, 'country': c.countryCode} if res['country'] is None: del res['country'] if not res: raise IMDbDataAccessError('unable to get companyID "%s"' % companyID) # Collect filmography information. items = MovieCompanies.select(MovieCompanies.q.companyID == companyID) if results > 0: items = items[:results] filmodata = [(cd.movieID, cd.companyID, self._compType[cd.companyTypeID], cd.note, get_movie_data(cd.movieID, self._kind)) for cd in items] filmodata = _groupListBy(filmodata, 2) for group in filmodata: ctype = group[0][2] for movieID, companyID, ctype, note, movieData in group: movie = Movie(data=movieData, movieID=movieID, notes=note or '', accessSystem=self.accessSystem) res.setdefault(ctype, []).append(movie) res.get(ctype, []).sort() return {'data': res, 'info sets': infosets} def _search_keyword(self, keyword, results): constr = OR(Keyword.q.phoneticCode == soundex(keyword), CONTAINSSTRING(Keyword.q.keyword, self.toUTF8(keyword))) return filterSimilarKeywords(keyword, _iterKeywords(Keyword.select(constr)))[:results] def _get_keyword(self, keyword, results, page=None): keyID = Keyword.select(Keyword.q.keyword == keyword) if keyID.count() == 0: return [] keyID = keyID[0].id movies = MovieKeyword.select(MovieKeyword.q.keywordID == keyID)[:results] return [(m.movieID, get_movie_data(m.movieID, self._kind)) for m in movies] def _get_top_bottom_movies(self, kind): if kind == 'top': kind = 'top 250 rank' elif kind == 'bottom': # Not a refuse: the plain text data files contains only # the bottom 10 movies. kind = 'bottom 10 rank' else: return [] infoID = InfoType.select(InfoType.q.info == kind) if infoID.count() == 0: return [] infoID = infoID[0].id movies = MovieInfo.select(MovieInfo.q.infoTypeID == infoID) ml = [] for m in movies: minfo = get_movie_data(m.movieID, self._kind) for k in kind, 'votes', 'rating', 'votes distribution': valueDict = getSingleInfo(MovieInfo, m.movieID, k, notAList=True) if k in (kind, 'votes') and k in valueDict: valueDict[k] = int(valueDict[k]) elif k == 'rating' and k in valueDict: valueDict[k] = float(valueDict[k]) minfo.update(valueDict) ml.append((m.movieID, minfo)) sorter = (_cmpBottom, _cmpTop)[kind == 'top 250 rank'] ml.sort(sorter) return ml def __del__(self): """Ensure that the connection is closed.""" # TODO: on Python 3, using mysql+pymysql, raises random exceptions; # for now, skip it and hope it's garbage-collected. return if not hasattr(self, '_connection'): return logger.debug('closing connection to the database') try: self._connection.close() except: pass
63,944
Python
.py
1,521
29.795529
101
0.537194
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,226
dbschema.py
cinemagoer_cinemagoer/imdb/parser/sql/dbschema.py
# Copyright 2005-2017 Davide Alberani <[email protected]> # 2006 Giuseppe "Cowo" Corbelli <cowo --> lugbs.linux.it> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module provides the schema used to describe the layout of the database used by the :mod:`imdb.parser.sql` package; functions to create/drop tables and indexes are also provided. """ from __future__ import absolute_import, division, print_function, unicode_literals from imdb.parser.sql.logging import logger _dbschema_logger = logger.getChild('dbschema') # Placeholders for column types. INTCOL = 1 UNICODECOL = 2 STRINGCOL = 3 _strMap = {1: 'INTCOL', 2: 'UNICODECOL', 3: 'STRINGCOL'} class DBCol(object): """Define column objects.""" def __init__(self, name, kind, **params): self.name = name self.kind = kind self.index = None self.indexLen = None # If not None, two notations are accepted: 'TableName' # and 'TableName.ColName'; in the first case, 'id' is assumed # as the name of the pointed column. self.foreignKey = None if 'index' in params: self.index = params['index'] del params['index'] if 'indexLen' in params: self.indexLen = params['indexLen'] del params['indexLen'] if 'foreignKey' in params: self.foreignKey = params['foreignKey'] del params['foreignKey'] self.params = params def __str__(self): """Class representation.""" s = '<DBCol %s %s' % (self.name, _strMap[self.kind]) if self.index: s += ' INDEX' if self.indexLen: s += '[:%d]' % self.indexLen if self.foreignKey: s += ' FOREIGN' if 'default' in self.params: val = self.params['default'] if val is not None: val = '"%s"' % val s += ' DEFAULT=%s' % val for param in self.params: if param == 'default': continue s += ' %s' % param.upper() s += '>' return s def __repr__(self): """Class representation.""" s = '<DBCol(name="%s", %s' % (self.name, _strMap[self.kind]) if self.index: s += ', index="%s"' % self.index if self.indexLen: s += ', indexLen=%d' % self.indexLen if self.foreignKey: s += ', foreignKey="%s"' % self.foreignKey for param in self.params: val = self.params[param] if isinstance(val, str): val = '"%s"' % val s += ', %s=%s' % (param, val) s += ')>' return s class DBTable(object): """Define table objects.""" def __init__(self, name, *cols, **kwds): self.name = name self.cols = cols # Default values. self.values = kwds.get('values', {}) def __str__(self): """Class representation.""" return '<DBTable %s (%d cols, %d values)>' % ( self.name, len(self.cols), sum([len(v) for v in list(self.values.values())]) ) def __repr__(self): """Class representation.""" s = '<DBTable(name="%s"' % self.name col_s = ', '.join([repr(col).rstrip('>').lstrip('<') for col in self.cols]) if col_s: s += ', %s' % col_s if self.values: s += ', values=%s' % self.values s += ')>' return s # Default values to insert in some tables: {'column': (list, of, values, ...)} kindTypeDefs = { 'kind': ( 'movie', 'tv series', 'tv movie', 'video movie', 'tv mini series', 'video game', 'episode', 'short', 'tv short' ) } companyTypeDefs = { 'kind': ( 'distributors', 'production companies', 'special effects companies', 'miscellaneous companies' ) } infoTypeDefs = { 'info': ( 'runtimes', 'color info', 'genres', 'languages', 'certificates', 'sound mix', 'tech info', 'countries', 'taglines', 'keywords', 'alternate versions', 'crazy credits', 'goofs', 'soundtrack', 'quotes', 'release dates', 'trivia', 'locations', 'mini biography', 'birth notes', 'birth date', 'height', 'death date', 'spouse', 'other works', 'birth name', 'salary history', 'nick names', 'books', 'agent address', 'biographical movies', 'portrayed in', 'where now', 'trade mark', 'interviews', 'article', 'magazine cover photo', 'pictorial', 'death notes', 'LD disc format', 'LD year', 'LD digital sound', 'LD official retail price', 'LD frequency response', 'LD pressing plant', 'LD length', 'LD language', 'LD review', 'LD spaciality', 'LD release date', 'LD production country', 'LD contrast', 'LD color rendition', 'LD picture format', 'LD video noise', 'LD video artifacts', 'LD release country', 'LD sharpness', 'LD dynamic range', 'LD audio noise', 'LD color information', 'LD group genre', 'LD quality program', 'LD close captions-teletext-ld-g', 'LD category', 'LD analog left', 'LD certification', 'LD audio quality', 'LD video quality', 'LD aspect ratio', 'LD analog right', 'LD additional information', 'LD number of chapter stops', 'LD dialogue intellegibility', 'LD disc size', 'LD master format', 'LD subtitles', 'LD status of availablility', 'LD quality of source', 'LD number of sides', 'LD video standard', 'LD supplement', 'LD original title', 'LD sound encoding', 'LD number', 'LD label', 'LD catalog number', 'LD laserdisc title', 'screenplay-teleplay', 'novel', 'adaption', 'book', 'production process protocol', 'printed media reviews', 'essays', 'other literature', 'mpaa', 'plot', 'votes distribution', 'votes', 'rating', 'production dates', 'copyright holder', 'filming dates', 'budget', 'weekend gross', 'gross', 'opening weekend', 'rentals', 'admissions', 'studios', 'top 250 rank', 'bottom 10 rank' ) } compCastTypeDefs = { 'kind': ('cast', 'crew', 'complete', 'complete+verified') } linkTypeDefs = { 'link': ( 'follows', 'followed by', 'remake of', 'remade as', 'references', 'referenced in', 'spoofs', 'spoofed in', 'features', 'featured in', 'spin off from', 'spin off', 'version of', 'similar to', 'edited into', 'edited from', 'alternate language version of', 'unknown link' ) } roleTypeDefs = { 'role': ( 'actor', 'actress', 'producer', 'writer', 'cinematographer', 'composer', 'costume designer', 'director', 'editor', 'miscellaneous crew', 'production designer', 'guest' ) } # Schema of tables in our database. # XXX: Foreign keys can be used to create constrains between tables, # but they create indexes in the database, and this # means poor performances at insert-time. DB_SCHEMA = [ DBTable('Name', # namePcodeCf is the soundex of the name in the canonical format. # namePcodeNf is the soundex of the name in the normal format, if # different from namePcodeCf. # surnamePcode is the soundex of the surname, if different from the # other two values. # The 'id' column is simply skipped by SQLObject (it's a default); # the alternateID attribute here will be ignored by SQLAlchemy. DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('name', UNICODECOL, notNone=True, index='idx_name', indexLen=6), DBCol('imdbIndex', STRINGCOL, length=12, default=None), DBCol('imdbID', INTCOL, default=None, index='idx_imdb_id'), DBCol('gender', STRINGCOL, length=1, default=None, index='idx_gender'), DBCol('namePcodeCf', STRINGCOL, length=5, default=None, index='idx_pcodecf'), DBCol('namePcodeNf', STRINGCOL, length=5, default=None, index='idx_pcodenf'), DBCol('surnamePcode', STRINGCOL, length=5, default=None, index='idx_pcode'), DBCol('md5sum', STRINGCOL, length=32, default=None, index='idx_md5')), DBTable('CharName', # namePcodeNf is the soundex of the name in the normal format. # surnamePcode is the soundex of the surname, if different # from namePcodeNf. DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('name', UNICODECOL, notNone=True, index='idx_name', indexLen=6), DBCol('imdbIndex', STRINGCOL, length=12, default=None), DBCol('imdbID', INTCOL, default=None, index='idx_imdb_id'), DBCol('namePcodeNf', STRINGCOL, length=5, default=None, index='idx_pcodenf'), DBCol('surnamePcode', STRINGCOL, length=5, default=None, index='idx_pcode'), DBCol('md5sum', STRINGCOL, length=32, default=None, index='idx_md5')), DBTable('CompanyName', # namePcodeNf is the soundex of the name in the normal format. # namePcodeSf is the soundex of the name plus the country code. DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('name', UNICODECOL, notNone=True, index='idx_name', indexLen=6), DBCol('countryCode', STRINGCOL, length=255, default=None, index='idx_ccode'), DBCol('imdbID', INTCOL, default=None, index='idx_imdb_id'), DBCol('namePcodeNf', STRINGCOL, length=5, default=None, index='idx_pcodenf'), DBCol('namePcodeSf', STRINGCOL, length=5, default=None, index='idx_pcodesf'), DBCol('md5sum', STRINGCOL, length=32, default=None, index='idx_md5')), DBTable('KindType', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('kind', STRINGCOL, length=15, default=None, alternateID=True), values=kindTypeDefs), DBTable('Title', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('title', UNICODECOL, notNone=True, index='idx_title', indexLen=10), DBCol('imdbIndex', STRINGCOL, length=12, default=None), DBCol('kindID', INTCOL, notNone=True, index='idx_kindid'), DBCol('productionYear', INTCOL, default=None, index='idx_year'), DBCol('imdbID', INTCOL, default=None, index="idx_imdb_id"), DBCol('phoneticCode', STRINGCOL, length=5, default=None, index='idx_pcode'), DBCol('episodeOfID', INTCOL, default=None, index='idx_epof'), DBCol('seasonNr', INTCOL, default=None, index="idx_season_nr"), DBCol('episodeNr', INTCOL, default=None, index="idx_episode_nr"), # Maximum observed length is 44; 49 can store 5 comma-separated # year-year pairs. DBCol('seriesYears', STRINGCOL, length=49, default=None), DBCol('md5sum', STRINGCOL, length=32, default=None, index='idx_md5')), DBTable('CompanyType', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('kind', STRINGCOL, length=32, default=None, alternateID=True), values=companyTypeDefs), DBTable('AkaName', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('personID', INTCOL, notNone=True, index='idx_person'), DBCol('name', UNICODECOL, notNone=True, index='idx_name', indexLen=6), DBCol('imdbIndex', STRINGCOL, length=12, default=None), DBCol('namePcodeCf', STRINGCOL, length=5, default=None, index='idx_pcodecf'), DBCol('namePcodeNf', STRINGCOL, length=5, default=None, index='idx_pcodenf'), DBCol('surnamePcode', STRINGCOL, length=5, default=None, index='idx_pcode'), DBCol('md5sum', STRINGCOL, length=32, default=None, index='idx_md5')), DBTable('AkaTitle', # XXX: It's safer to set notNone to False, here. # alias for akas are stored completely in the AkaTitle table; # this means that episodes will set also a "tv series" alias name. # Reading the aka-title.list file it looks like there are # episode titles with aliases to different titles for both # the episode and the series title, while for just the series # there are no aliases. # E.g.: # aka title original title # "Series, The" (2005) {The Episode} "Other Title" (2005) {Other Title} # But there is no: # "Series, The" (2005) "Other Title" (2005) DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('movieID', INTCOL, notNone=True, index='idx_movieid'), DBCol('title', UNICODECOL, notNone=True, index='idx_title', indexLen=10), DBCol('imdbIndex', STRINGCOL, length=12, default=None), DBCol('kindID', INTCOL, notNone=True, index='idx_kindid'), DBCol('productionYear', INTCOL, default=None, index='idx_year'), DBCol('phoneticCode', STRINGCOL, length=5, default=None, index='idx_pcode'), DBCol('episodeOfID', INTCOL, default=None, index='idx_epof'), DBCol('seasonNr', INTCOL, default=None), DBCol('episodeNr', INTCOL, default=None), DBCol('note', UNICODECOL, default=None), DBCol('md5sum', STRINGCOL, length=32, default=None, index='idx_md5')), DBTable('RoleType', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('role', STRINGCOL, length=32, notNone=True, alternateID=True), values=roleTypeDefs), DBTable('CastInfo', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('personID', INTCOL, notNone=True, index='idx_pid'), DBCol('movieID', INTCOL, notNone=True, index='idx_mid'), DBCol('personRoleID', INTCOL, default=None, index='idx_cid'), DBCol('note', UNICODECOL, default=None), DBCol('nrOrder', INTCOL, default=None), DBCol('roleID', INTCOL, notNone=True, index='idx_rid')), DBTable('CompCastType', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('kind', STRINGCOL, length=32, notNone=True, alternateID=True), values=compCastTypeDefs), DBTable('CompleteCast', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('movieID', INTCOL, index='idx_mid'), DBCol('subjectID', INTCOL, notNone=True, index='idx_sid'), DBCol('statusID', INTCOL, notNone=True)), DBTable('InfoType', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('info', STRINGCOL, length=32, notNone=True, alternateID=True), values=infoTypeDefs), DBTable('LinkType', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('link', STRINGCOL, length=32, notNone=True, alternateID=True), values=linkTypeDefs), DBTable('Keyword', DBCol('id', INTCOL, notNone=True, alternateID=True), # XXX: can't use alternateID=True, because it would create # a UNIQUE index; unfortunately (at least with a common # collation like utf8_unicode_ci) MySQL will consider # some different keywords identical - like # "fianc√©e" and "fiancee". DBCol('keyword', UNICODECOL, notNone=True, index='idx_keyword', indexLen=5), DBCol('phoneticCode', STRINGCOL, length=5, default=None, index='idx_pcode')), DBTable('MovieKeyword', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('movieID', INTCOL, notNone=True, index='idx_mid'), DBCol('keywordID', INTCOL, notNone=True, index='idx_keywordid')), DBTable('MovieLink', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('movieID', INTCOL, notNone=True, index='idx_mid'), DBCol('linkedMovieID', INTCOL, notNone=True, index='idx_lmid'), DBCol('linkTypeID', INTCOL, notNone=True, index='idx_ltypeid')), DBTable('MovieInfo', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('movieID', INTCOL, notNone=True, index='idx_mid'), DBCol('infoTypeID', INTCOL, notNone=True, index='idx_infotypeid'), DBCol('info', UNICODECOL, notNone=True, index='idx_info', indexLen=10), DBCol('note', UNICODECOL, default=None)), DBTable('MovieCompanies', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('movieID', INTCOL, notNone=True, index='idx_mid'), DBCol('companyID', INTCOL, notNone=True, index='idx_cid'), DBCol('companyTypeID', INTCOL, notNone=True, index='idx_ctypeid'), DBCol('note', UNICODECOL, default=None)), DBTable('PersonInfo', DBCol('id', INTCOL, notNone=True, alternateID=True), DBCol('personID', INTCOL, notNone=True, index='idx_pid'), DBCol('infoTypeID', INTCOL, notNone=True, index='idx_itypeid'), DBCol('info', UNICODECOL, notNone=True), DBCol('note', UNICODECOL, default=None)) ] # Functions to manage tables. def dropTables(tables, ifExists=True): """Drop the tables.""" # In reverse order (useful to avoid errors about foreign keys). DB_TABLES_DROP = list(tables) DB_TABLES_DROP.reverse() for table in DB_TABLES_DROP: _dbschema_logger.info('dropping table %s', table._imdbpyName) table.dropTable(ifExists) def createTables(tables, ifNotExists=True): """Create the tables and insert default values.""" for table in tables: # Create the table. _dbschema_logger.info('creating table %s', table._imdbpyName) table.createTable(ifNotExists) # Insert default values, if any. if table._imdbpySchema.values: _dbschema_logger.info('inserting values into table %s', table._imdbpyName) for key in table._imdbpySchema.values: for value in table._imdbpySchema.values[key]: table(**{key: str(value)}) def createIndexes(tables, ifNotExists=True): """Create the indexes in the database. Return a list of errors, if any.""" errors = [] for table in tables: _dbschema_logger.info('creating indexes for table %s', table._imdbpyName) try: table.addIndexes(ifNotExists) except Exception as e: errors.append(e) continue return errors
19,323
Python
.py
377
41.880637
89
0.609273
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,227
alchemyadapter.py
cinemagoer_cinemagoer/imdb/parser/sql/alchemyadapter.py
# Copyright 2008-2017 Davide Alberani <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This module adapts the SQLAlchemy ORM to the internal mechanism. """ from __future__ import absolute_import, division, print_function, unicode_literals import re import sys import logging from sqlalchemy import * from sqlalchemy import schema try: from sqlalchemy import exc # 0.5 except ImportError: from sqlalchemy import exceptions as exc # 0.4 from imdb._exceptions import IMDbDataAccessError from imdb.parser.sql.logging import logger from .dbschema import * _alchemy_logger = logger.getChild('alchemy') # Used to convert table and column names. re_upper = re.compile(r'([A-Z])') # XXX: I'm not sure at all that this is the best method to connect # to the database and bind that connection to every table. metadata = MetaData() # Maps our placeholders to SQLAlchemy's column types. MAP_COLS = { INTCOL: Integer, UNICODECOL: UnicodeText, STRINGCOL: String } class NotFoundError(IMDbDataAccessError): """Exception raised when Table.get(id) returns no value.""" pass def _renameTable(tname): """Build the name of a table, as done by SQLObject.""" tname = re_upper.sub(r'_\1', tname) if tname.startswith('_'): tname = tname[1:] return tname.lower() def _renameColumn(cname): """Build the name of a column, as done by SQLObject.""" cname = cname.replace('ID', 'Id') return _renameTable(cname) class DNNameObj(object): """Used to access table.sqlmeta.columns[column].dbName (a string).""" def __init__(self, dbName): self.dbName = dbName def __repr__(self): return '<DNNameObj(dbName=%s) [id=%s]>' % (self.dbName, id(self)) class DNNameDict(object): """Used to access table.sqlmeta.columns (a dictionary).""" def __init__(self, colMap): self.colMap = colMap def __getitem__(self, key): return DNNameObj(self.colMap[key]) def __repr__(self): return '<DNNameDict(colMap=%s) [id=%s]>' % (self.colMap, id(self)) class SQLMetaAdapter(object): """Used to access table.sqlmeta (an object with .table, .columns and .idName attributes).""" def __init__(self, table, colMap=None): self.table = table if colMap is None: colMap = {} self.colMap = colMap def __getattr__(self, name): if name == 'table': return getattr(self.table, name) if name == 'columns': return DNNameDict(self.colMap) if name == 'idName': return self.colMap.get('id', 'id') return None def __repr__(self): return '<SQLMetaAdapter(table=%s, colMap=%s) [id=%s]>' % \ (repr(self.table), repr(self.colMap), id(self)) class QAdapter(object): """Used to access table.q attribute (remapped to SQLAlchemy table.c).""" def __init__(self, table, colMap=None): self.table = table if colMap is None: colMap = {} self.colMap = colMap def __getattr__(self, name): try: return getattr(self.table.c, self.colMap[name]) except KeyError: raise AttributeError("unable to get '%s'" % name) def __repr__(self): return '<QAdapter(table=%s, colMap=%s) [id=%s]>' % \ (repr(self.table), repr(self.colMap), id(self)) class RowAdapter(object): """Adapter for a SQLAlchemy RowProxy object.""" def __init__(self, row, table, colMap=None): self.row = row # FIXME: it's OBSCENE that 'table' should be passed from # TableAdapter through ResultAdapter only to land here, # where it's used to directly update a row item. self.table = table if colMap is None: colMap = {} self.colMap = colMap self.colMapKeys = list(colMap.keys()) def __getattr__(self, name): try: return getattr(self.row, self.colMap[name]) except KeyError: raise AttributeError("unable to get '%s'" % name) def __setattr__(self, name, value): # FIXME: I can't even think about how much performances suffer, # for this horrible hack (and it's used so rarely...) # For sure something like a "property" to map column names # to getter/setter functions would be much better, but it's # not possible (or at least not easy) to build them for a # single instance. if name in self.__dict__.get('colMapKeys', ()): # Trying to update a value in the database. row = self.__dict__['row'] table = self.__dict__['table'] colMap = self.__dict__['colMap'] params = {colMap[name]: value} table.update(table.c.id == row.id).execute(**params) # XXX: minor bug: after a value is assigned with the # 'rowAdapterInstance.colName = value' syntax, for some # reason rowAdapterInstance.colName still returns the # previous value (even if the database is updated). # Fix it? I'm not even sure it's ever used. return # For every other attribute. object.__setattr__(self, name, value) def __repr__(self): return '<RowAdapter(row=%s, table=%s, colMap=%s) [id=%s]>' % \ (repr(self.row), repr(self.table), repr(self.colMap), id(self)) class ResultAdapter(object): """Adapter for a SQLAlchemy ResultProxy object.""" def __init__(self, result, table, colMap=None): self.result = result self.table = table if colMap is None: colMap = {} self.colMap = colMap def count(self): return len(self) def __len__(self): # FIXME: why sqlite returns -1? (that's wrooong!) if self.result.rowcount == -1: return 0 return self.result.rowcount def __getitem__(self, key): rlist = list(self.result) res = rlist[key] if not isinstance(key, slice): # A single item. return RowAdapter(res, self.table, colMap=self.colMap) else: # A (possible empty) list of items. return [RowAdapter(x, self.table, colMap=self.colMap) for x in res] def __iter__(self): for item in self.result: yield RowAdapter(item, self.table, colMap=self.colMap) def __repr__(self): return '<ResultAdapter(result=%s, table=%s, colMap=%s) [id=%s]>' % \ (repr(self.result), repr(self.table), repr(self.colMap), id(self)) class TableAdapter(object): """Adapter for a SQLAlchemy Table object, to mimic a SQLObject class.""" def __init__(self, table, uri=None): """Initialize a TableAdapter object.""" self._imdbpySchema = table self._imdbpyName = table.name self.connectionURI = uri self.colMap = {} columns = [] for col in table.cols: # Column's paramters. params = {'nullable': True} params.update(col.params) if col.name == 'id': params['primary_key'] = True if 'notNone' in params: params['nullable'] = not params['notNone'] del params['notNone'] cname = _renameColumn(col.name) self.colMap[col.name] = cname colClass = MAP_COLS[col.kind] colKindParams = {} if 'length' in params: colKindParams['length'] = params['length'] del params['length'] colKind = colClass(**colKindParams) if 'alternateID' in params: # There's no need to handle them here. del params['alternateID'] # Create a column. colObj = Column(cname, colKind, **params) columns.append(colObj) self.tableName = _renameTable(table.name) # Create the table. self.table = Table(self.tableName, metadata, *columns) self._ta_insert = self.table.insert() self._ta_select = self.table.select # Adapters for special attributes. self.q = QAdapter(self.table, colMap=self.colMap) self.sqlmeta = SQLMetaAdapter(self.table, colMap=self.colMap) def select(self, conditions=None): """Return a list of results.""" result = self._ta_select(conditions).execute() return ResultAdapter(result, self.table, colMap=self.colMap) def get(self, theID): """Get an object given its ID.""" result = self.select(self.table.c.id == theID) # if not result: # raise NotFoundError, 'no data for ID %s' % theID # FIXME: isn't this a bit risky? We can't check len(result), # because sqlite returns -1... # What about converting it to a list and getting the first item? try: return result[0] except IndexError: raise NotFoundError('no data for ID %s' % theID) def dropTable(self, checkfirst=True): """Drop the table.""" dropParams = {'checkfirst': checkfirst} # Guess what? Another work-around for a ibm_db bug. if self.table.bind.engine.url.drivername.startswith('ibm_db'): del dropParams['checkfirst'] try: self.table.drop(**dropParams) except exc.ProgrammingError: # As above: re-raise the exception, but only if it's not ibm_db. if not self.table.bind.engine.url.drivername.startswith('ibm_db'): raise def createTable(self, checkfirst=True): """Create the table.""" self.table.create(checkfirst=checkfirst) # Create indexes for alternateID columns (other indexes will be # created later, at explicit request for performances reasons). for col in self._imdbpySchema.cols: if col.name == 'id': continue if col.params.get('alternateID', False): self._createIndex(col, checkfirst=checkfirst) def _createIndex(self, col, checkfirst=True): """Create an index for a given (schema) column.""" idx_name = '%s_%s' % (self.table.name, col.index or col.name) if checkfirst: for index in self.table.indexes: if index.name == idx_name: return index_args = {} if self.connectionURI.startswith('mysql'): if col.indexLen: index_args['mysql_length'] = col.indexLen elif col.kind in (UNICODECOL, STRINGCOL): index_args['mysql_length'] = min(5, col.params.get('length') or 5) idx = Index(idx_name, getattr(self.table.c, self.colMap[col.name]), **index_args) # XXX: beware that exc.OperationalError can be raised, is some # strange circumstances; that's why the index name doesn't # follow the SQLObject convention, but includes the table name: # sqlite, for example, expects index names to be unique at # db-level. try: idx.create() except exc.OperationalError as e: _alchemy_logger.warn('Skipping creation of the %s.%s index: %s' % (self.sqlmeta.table, col.name, e)) def addIndexes(self, ifNotExists=True): """Create all required indexes.""" for col in self._imdbpySchema.cols: if col.index: self._createIndex(col, checkfirst=ifNotExists) def __call__(self, *args, **kwds): """To insert a new row with the syntax: TableClass(key=value, ...)""" taArgs = {} for key, value in list(kwds.items()): taArgs[self.colMap.get(key, key)] = value self._ta_insert.execute(*args, **taArgs) def __repr__(self): return '<TableAdapter(table=%s) [id=%s]>' % (repr(self.table), id(self)) # Module-level "cache" for SQLObject classes, to prevent # "Table 'tableName' is already defined for this MetaData instance" errors, # when two or more connections to the database are made. # XXX: is this the best way to act? TABLES_REPOSITORY = {} def getDBTables(uri=None): """Return a list of TableAdapter objects to be used to access the database through the SQLAlchemy ORM. The connection uri is optional, and can be used to tailor the db schema to specific needs.""" DB_TABLES = [] for table in DB_SCHEMA: if table.name in TABLES_REPOSITORY: DB_TABLES.append(TABLES_REPOSITORY[table.name]) continue tableAdapter = TableAdapter(table, uri) DB_TABLES.append(tableAdapter) TABLES_REPOSITORY[table.name] = tableAdapter return DB_TABLES # Functions used to emulate SQLObject's logical operators. def AND(*params): """Emulate SQLObject's AND.""" return and_(*params) def OR(*params): """Emulate SQLObject's OR.""" return or_(*params) def IN(item, inList): """Emulate SQLObject's IN.""" if not isinstance(item, schema.Column): return OR(*[x == item for x in inList]) else: return item.in_(inList) def ISNULL(x): """Emulate SQLObject's ISNULL.""" # XXX: Should we use null()? Can null() be a global instance? # XXX: Is it safe to test None with the == operator, in this case? return x is None def ISNOTNULL(x): """Emulate SQLObject's ISNOTNULL.""" return x is not None def CONTAINSSTRING(expr, pattern): """Emulate SQLObject's CONTAINSSTRING.""" return expr.like('%%%s%%' % pattern) def toUTF8(s): """For some strange reason, sometimes SQLObject wants utf8 strings instead of unicode; with SQLAlchemy we just return the unicode text.""" return s class _AlchemyConnection(object): """A proxy for the connection object, required since _ConnectionFairy uses __slots__.""" def __init__(self, conn): self.conn = conn def __getattr__(self, name): return getattr(self.conn, name) def setConnection(uri, tables, encoding='utf8', debug=False): """Set connection for every table.""" params = {'encoding': encoding} # FIXME: why on earth MySQL requires an additional parameter, # is well beyond my understanding... if uri.startswith('mysql'): if '?' in uri: uri += '&' else: uri += '?' uri += 'charset=%s' % encoding if debug: params['echo'] = True if uri.startswith('ibm_db'): # Try to work-around a possible bug of the ibm_db DB2 driver. params['convert_unicode'] = True # XXX: is this the best way to connect? engine = create_engine(uri, **params) metadata.bind = engine eng_conn = engine.connect() if uri.startswith('sqlite'): major = sys.version_info[0] minor = sys.version_info[1] if major > 2 or (major == 2 and minor > 5): eng_conn.connection.connection.text_factory = str # XXX: OH MY, THAT'S A MESS! # We need to return a "connection" object, with the .dbName # attribute set to the db engine name (e.g. "mysql"), .paramstyle # set to the style of the paramters for query() calls, and the # .module attribute set to a module (?) with .OperationalError and # .IntegrityError attributes. # Another attribute of "connection" is the getConnection() function, # used to return an object with a .cursor() method. connection = _AlchemyConnection(eng_conn.connection) paramstyle = eng_conn.dialect.paramstyle connection.module = eng_conn.dialect.dbapi connection.paramstyle = paramstyle connection.getConnection = lambda: connection.connection connection.dbName = engine.url.drivername return connection
16,586
Python
.py
386
35.033679
89
0.620957
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,228
utils.py
cinemagoer_cinemagoer/imdb/parser/s3/utils.py
# Copyright 2018 Davide Alberani <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This package provides utilities for the s3 dataset. """ from __future__ import absolute_import, division, print_function, unicode_literals import re from difflib import SequenceMatcher import sqlalchemy from imdb.utils import _unicodeArticles, canonicalName, canonicalTitle SOUNDEX_LENGTH = 5 RO_THRESHOLD = 0.6 STRING_MAXLENDIFFER = 0.7 re_imdbids = re.compile(r'(nm|tt)') re_characters = re.compile(r'"(.+?)"') def transf_imdbid(x): return int(x[2:]) def transf_multi_imdbid(x): if not x: return x return re_imdbids.sub('', x) def transf_multi_character(x): if not x: return x ' / '.join(re_characters.findall(x)) def transf_int(x): try: return int(x) except: return None def transf_float(x): try: return float(x) except: return None def transf_bool(x): try: return x == '1' except: return None KIND = { 'tvEpisode': 'episode', 'tvMiniSeries': 'tv mini series', 'tvSeries': 'tv series', 'tvShort': 'tv short', 'tvSpecial': 'tv special', 'videoGame': 'video game' } def transf_kind(x): return KIND.get(x, x) # Database mapping. # 'type' force a conversion to a specific SQL type # 'transform' applies a conversion to the content (changes the data in the database) # 'rename' is applied when reading the column names (the columns names are unchanged, in the database) # 'index' mark the columns that need to be indexed # 'length' is applied to VARCHAR fields DB_TRANSFORM = { 'title_basics': { 'tconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'movieID', 'index': True}, 'titleType': {'type': sqlalchemy.String, 'transform': transf_kind, 'rename': 'kind', 'length': 16, 'index': True}, 'primaryTitle': {'rename': 'title'}, 'originalTitle': {'rename': 'original title'}, 'isAdult': {'type': sqlalchemy.Boolean, 'transform': transf_bool, 'rename': 'adult', 'index': True}, 'startYear': {'type': sqlalchemy.Integer, 'transform': transf_int, 'index': True}, 'endYear': {'type': sqlalchemy.Integer, 'transform': transf_int}, 'runtimeMinutes': {'type': sqlalchemy.Integer, 'transform': transf_int, 'rename': 'runtimes', 'index': True}, 't_soundex': {'type': sqlalchemy.String, 'length': 5, 'index': True} }, 'name_basics': { 'nconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'personID', 'index': True}, 'primaryName': {'rename': 'name'}, 'birthYear': {'type': sqlalchemy.Integer, 'transform': transf_int, 'rename': 'birth date', 'index': True}, 'deathYear': {'type': sqlalchemy.Integer, 'transform': transf_int, 'rename': 'death date', 'index': True}, 'primaryProfession': {'rename': 'primary profession'}, 'knownForTitles': {'transform': transf_multi_imdbid, 'rename': 'known for'}, 'ns_soundex': {'type': sqlalchemy.String, 'length': 5, 'index': True}, 'sn_soundex': {'type': sqlalchemy.String, 'length': 5, 'index': True}, 's_soundex': {'type': sqlalchemy.String, 'length': 5, 'index': True}, }, 'title_akas': { 'titleId': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'movieID', 'index': True}, 'ordering': {'type': sqlalchemy.Integer, 'transform': transf_int}, 'title': {}, 'region': {'type': sqlalchemy.String, 'length': 5, 'index': True}, 'language': {'type': sqlalchemy.String, 'length': 5, 'index': True}, 'types': {'type': sqlalchemy.String, 'length': 31, 'index': True}, 'attributes': {'type': sqlalchemy.String, 'length': 127}, 'isOriginalTitle': {'type': sqlalchemy.Boolean, 'transform': transf_bool, 'rename': 'original', 'index': True}, 't_soundex': {'type': sqlalchemy.String, 'length': 5, 'index': True} }, 'title_crew': { 'tconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'movieID', 'index': True}, 'directors': {'transform': transf_multi_imdbid, 'rename': 'director'}, 'writers': {'transform': transf_multi_imdbid, 'rename': 'writer'} }, 'title_episode': { 'tconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'movieID', 'index': True}, 'parentTconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'index': True}, 'seasonNumber': {'type': sqlalchemy.Integer, 'transform': transf_int, 'rename': 'seasonNr'}, 'episodeNumber': {'type': sqlalchemy.Integer, 'transform': transf_int, 'rename': 'episodeNr'} }, 'title_principals': { 'tconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'movieID', 'index': True}, 'ordering': {'type': sqlalchemy.Integer, 'transform': transf_int}, 'nconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'personID', 'index': True}, 'category': {'type': sqlalchemy.String, 'length': 64}, 'job': {'type': sqlalchemy.String, 'length': 1024}, 'characters': {'type': sqlalchemy.String, 'length': 1024, 'transform': transf_multi_character} }, 'title_ratings': { 'tconst': {'type': sqlalchemy.Integer, 'transform': transf_imdbid, 'rename': 'movieID', 'index': True}, 'averageRating': {'type': sqlalchemy.Float, 'transform': transf_float, 'rename': 'rating', 'index': True}, 'numVotes': {'type': sqlalchemy.Integer, 'transform': transf_int, 'rename': 'votes', 'index': True} } } _translate = dict(B='1', C='2', D='3', F='1', G='2', J='2', K='2', L='4', M='5', N='5', P='1', Q='2', R='6', S='2', T='3', V='1', X='2', Z='2') _translateget = _translate.get _re_non_ascii = re.compile(r'^[^a-z]*', re.I) def soundex(s, length=SOUNDEX_LENGTH): """Return the soundex code for the given string. :param s: the string to convert to soundex :type s: str :param length: length of the soundex code to generate :type length: int :returns: the soundex code :rtype: str""" s = _re_non_ascii.sub('', s) if not s: return None s = s.upper() soundCode = s[0] count = 1 for c in s[1:]: if count >= length: break cw = _translateget(c, '0') if cw != '0' and soundCode[-1] != cw: soundCode += cw count += 1 return soundCode or None def title_soundex(title): """Return the soundex code for the given title; the (optional) starting article is pruned. :param title: movie title :type title: str :returns: soundex of the title (without the article, if any) :rtype: str """ if not title: return None title = canonicalTitle(title) ts = title.split(', ') if ts[-1].lower() in _unicodeArticles: title = ', '.join(ts[:-1]) return soundex(title) def name_soundexes(name): """Return three soundex codes for the given name. :param name: person name :type name: str :returns: tuple of soundex codes: (S(Name Surname), S(Surname Name), S(Surname)) :rtype: tuple """ if not name: return None, None, None s1 = soundex(name) canonical_name = canonicalName(name) s2 = soundex(canonical_name) if s1 == s2: s2 = None s3 = soundex(canonical_name.split(', ')[0]) if s3 and s3 in (s1, s2): s3 = None return s1, s2, s3 def ratcliff(s1, s2, sm): """Ratcliff-Obershelp similarity. :param s1: first string to compare :type s1: str :param s2: second string to compare :type s2: str :param sm: sequence matcher to use for the comparison :type sm: :class:`difflib.SequenceMatcher` :returns: 0.0-1.0 similarity :rtype: float""" s1len = len(s1) s2len = len(s2) if s1len < s2len: threshold = float(s1len) / s2len else: threshold = float(s2len) / s1len if threshold < STRING_MAXLENDIFFER: return 0.0 sm.set_seq2(s2.lower()) return sm.ratio() def scan_names(name_list, name, results=0, ro_threshold=RO_THRESHOLD): """Scan a list of names, searching for best matches against some variations. :param name_list: list of (personID, {person_data}) tuples :type name_list: list :param name: searched name :type name: str :results: returns at most as much results (all, if 0) :type results: int :param ro_threshold: ignore results with a score lower than this value :type ro_threshold: float :returns: list of results sorted by similarity :rtype: list""" canonical_name = canonicalName(name).replace(',', '') sm1 = SequenceMatcher() sm2 = SequenceMatcher() sm1.set_seq1(name.lower()) sm2.set_seq1(canonical_name.lower()) resd = {} for i, n_data in name_list: nil = n_data['name'] # Distance with the canonical name. ratios = [ratcliff(name, nil, sm1) + 0.1, ratcliff(name, canonicalName(nil).replace(',', ''), sm2)] ratio = max(ratios) if ratio >= ro_threshold: if i in resd: if ratio > resd[i][0]: resd[i] = (ratio, (i, n_data)) else: resd[i] = (ratio, (i, n_data)) res = list(resd.values()) res.sort() res.reverse() if results > 0: res[:] = res[:results] return res def strip_article(title): no_article_title = canonicalTitle(title) t2s = no_article_title.split(', ') if t2s[-1].lower() in _unicodeArticles: no_article_title = ', '.join(t2s[:-1]) return no_article_title def scan_titles(titles_list, title, results=0, ro_threshold=RO_THRESHOLD): """Scan a list of titles, searching for best matches amongst some variations. :param titles_list: list of (movieID, {movie_data}) tuples :type titles_list: list :param title: searched title :type title: str :results: returns at most as much results (all, if 0) :type results: int :param ro_threshold: ignore results with a score lower than this value :type ro_threshold: float :returns: list of results sorted by similarity :rtype: list""" no_article_title = strip_article(title) sm1 = SequenceMatcher() sm1.set_seq1(title.lower()) sm2 = SequenceMatcher() sm2.set_seq2(no_article_title.lower()) resd = {} for i, t_data in titles_list: til = t_data['title'] ratios = [ratcliff(title, til, sm1) + 0.1, ratcliff(no_article_title, strip_article(til), sm2)] ratio = max(ratios) if t_data.get('kind') == 'episode': ratio -= .2 if ratio >= ro_threshold: if i in resd: if ratio > resd[i][0]: resd[i] = (ratio, (i, t_data)) else: resd[i] = (ratio, (i, t_data)) res = list(resd.values()) res.sort() res.reverse() if results > 0: res[:] = res[:results] return res
12,180
Python
.py
304
32.907895
108
0.60426
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,229
__init__.py
cinemagoer_cinemagoer/imdb/parser/s3/__init__.py
# -*- coding: utf-8 -*- # Copyright 2017-2019 Davide Alberani <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This package provides the IMDbS3AccessSystem class used to access IMDb's data through the Amazon S3 dataset. The :func:`imdb.IMDb` function will return an instance of this class when called with the ``accessSystem`` parameter is set to "s3" or "s3dataset". """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from operator import itemgetter import sqlalchemy from imdb import IMDbBase from imdb.Movie import Movie from imdb.Person import Person from .utils import DB_TRANSFORM, name_soundexes, scan_names, scan_titles, title_soundex def split_array(text): """Split a string assuming it's an array. :param text: the text to split :type text: str :returns: list of splitted strings :rtype: list """ if not isinstance(text, str): return text # for some reason, titles.akas.tsv.gz contains \x02 as a separator sep = ',' if ',' in text else '\x02' return text.split(sep) class IMDbS3AccessSystem(IMDbBase): """The class used to access IMDb's data through the s3 dataset.""" accessSystem = 's3' _s3_logger = logging.getLogger('imdbpy.parser.s3') _metadata = sqlalchemy.MetaData() def __init__(self, uri, adultSearch=True, *arguments, **keywords): """Initialize the access system.""" IMDbBase.__init__(self, *arguments, **keywords) self._engine = sqlalchemy.create_engine(uri, encoding='utf-8', echo=False) self._metadata.bind = self._engine self._metadata.reflect() self.T = self._metadata.tables def _rename(self, table, data): for column, conf in DB_TRANSFORM.get(table, {}).items(): if 'rename' not in conf: continue if column not in data: continue data[conf['rename']] = data[column] del data[column] return data def _clean(self, data, keys_to_remove=None): if keys_to_remove is None: keys_to_remove = [] for key in list(data.keys()): if key in keys_to_remove or data[key] in (None, '', []): del data[key] return data def _base_title_info(self, movieID, movies_cache=None, persons_cache=None): if movies_cache is None: movies_cache = {} if persons_cache is None: persons_cache = {} if movieID in movies_cache: return movies_cache[movieID] tb = self.T['title_basics'] movie = tb.select(tb.c.tconst == movieID).execute().fetchone() or {} data = self._rename('title_basics', dict(movie)) data['year'] = str(data.get('startYear') or '') if 'endYear' in data and data['endYear']: data['year'] += '-%s' % data['endYear'] genres = data.get('genres') or '' data['genres'] = split_array(genres.lower()) if 'runtimes' in data and data['runtimes']: data['runtimes'] = [data['runtimes']] self._clean(data, ('startYear', 'endYear', 'movieID')) movies_cache[movieID] = data return data def _base_person_info(self, personID, movies_cache=None, persons_cache=None): if movies_cache is None: movies_cache = {} if persons_cache is None: persons_cache = {} if personID in persons_cache: return persons_cache[personID] nb = self.T['name_basics'] person = nb.select(nb.c.nconst == personID).execute().fetchone() or {} data = self._rename('name_basics', dict(person)) movies = [] for movieID in split_array(data.get('known for') or ''): if not movieID: continue movieID = int(movieID) movie_data = self._base_title_info(movieID, movies_cache=movies_cache, persons_cache=persons_cache) movie = Movie(movieID=movieID, data=movie_data, accessSystem=self.accessSystem) movies.append(movie) data['known for'] = movies self._clean(data, ('ns_soundex', 'sn_soundex', 's_soundex', 'personID')) persons_cache[personID] = data return data def get_movie_main(self, movieID): movieID = int(movieID) data = self._base_title_info(movieID) _movies_cache = {movieID: data} _persons_cache = {} tc = self.T['title_crew'] movie = tc.select(tc.c.tconst == movieID).execute().fetchone() or {} tc_data = self._rename('title_crew', dict(movie)) writers = [] directors = [] for key, target in (('director', directors), ('writer', writers)): for personID in split_array(tc_data.get(key) or ''): if not personID: continue personID = int(personID) person_data = self._base_person_info(personID, movies_cache=_movies_cache, persons_cache=_persons_cache) person = Person(personID=personID, data=person_data, accessSystem=self.accessSystem) target.append(person) tc_data['director'] = directors tc_data['writer'] = writers data.update(tc_data) te = self.T['title_episode'] movie = te.select(te.c.tconst == movieID).execute().fetchone() or {} te_data = self._rename('title_episode', dict(movie)) if 'parentTconst' in te_data: te_data['episodes of'] = self._base_title_info(te_data['parentTconst']) self._clean(te_data, ('parentTconst',)) data.update(te_data) tp = self.T['title_principals'] movie_rows = tp.select(tp.c.tconst == movieID).execute().fetchall() or {} roles = {} for movie_row in movie_rows: movie_row = dict(movie_row) tp_data = self._rename('title_principals', dict(movie_row)) category = tp_data.get('category') if not category: continue if category in ('actor', 'actress', 'self'): category = 'cast' roles.setdefault(category, []).append(movie_row) for role in roles: roles[role].sort(key=itemgetter('ordering')) persons = [] for person_info in roles[role]: personID = person_info.get('nconst') if not personID: continue person_data = self._base_person_info(personID, movies_cache=_movies_cache, persons_cache=_persons_cache) person = Person(personID=personID, data=person_data, billingPos=person_info.get('ordering'), currentRole=person_info.get('characters'), notes=person_info.get('job'), accessSystem=self.accessSystem) persons.append(person) data[role] = persons tr = self.T['title_ratings'] movie = tr.select(tr.c.tconst == movieID).execute().fetchone() or {} tr_data = self._rename('title_ratings', dict(movie)) data.update(tr_data) ta = self.T['title_akas'] akas = ta.select(ta.c.titleId == movieID).execute() akas_list = [] for aka in akas: ta_data = self._rename('title_akas', dict(aka)) or {} for key in list(ta_data.keys()): if not ta_data[key]: del ta_data[key] for key in 't_soundex', 'movieID': if key in ta_data: del ta_data[key] for key in 'types', 'attributes': if key not in ta_data: continue ta_data[key] = split_array(ta_data[key]) akas_list.append(ta_data) if akas_list: data['akas'] = akas_list self._clean(data, ('movieID', 't_soundex')) return {'data': data, 'info sets': self.get_movie_infoset()} # we don't really have plot information, yet get_movie_plot = get_movie_main def get_person_main(self, personID): personID = int(personID) data = self._base_person_info(personID) self._clean(data, ('personID',)) return {'data': data, 'info sets': self.get_person_infoset()} get_person_filmography = get_person_main get_person_biography = get_person_main def _search_movie(self, title, results, _episodes=False): title = title.strip() if not title: return [] results = [] t_soundex = title_soundex(title) tb = self.T['title_basics'] conditions = [tb.c.t_soundex == t_soundex] if _episodes: conditions.append(tb.c.titleType == 'episode') results = tb.select(sqlalchemy.and_(*conditions)).execute() results = [(x['tconst'], self._clean(self._rename('title_basics', dict(x)), ('t_soundex',))) for x in results] # Also search the AKAs ta = self.T['title_akas'] if t_soundex is not None: ta_conditions = [ta.c.t_soundex == t_soundex] else: ta_conditions = [ta.c.title.ilike('%%%s%%' % title)] ta_results = ta.select(sqlalchemy.and_(*ta_conditions)).execute() ta_results = [(x['titleId'], self._clean(self._rename('title_akas', dict(x)), ('t_soundex',))) for x in ta_results] results += ta_results results = scan_titles(results, title) results = [x[1] for x in results] return results def _search_movie_advanced(self, title=None, adult=None, results=None, sort=None, sort_dir=None): return self._search_movie(title, results) def _search_episode(self, title, results): return self._search_movie(title, results=results, _episodes=True) def _search_person(self, name, results): name = name.strip() if not name: return [] results = [] ns_soundex, sn_soundex, s_soundex = name_soundexes(name) nb = self.T['name_basics'] conditions = [nb.c.ns_soundex == ns_soundex] if sn_soundex: conditions.append(nb.c.sn_soundex == sn_soundex) if s_soundex: conditions.append(nb.c.s_soundex == s_soundex) results = nb.select(sqlalchemy.or_(*conditions)).execute() results = [(x['nconst'], self._clean(self._rename('name_basics', dict(x)), ('ns_soundex', 'sn_soundex', 's_soundex'))) for x in results] results = scan_names(results, name) results = [x[1] for x in results] return results
11,613
Python
.py
253
35.29249
111
0.584054
cinemagoer/cinemagoer
1,219
352
80
GPL-2.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,230
setup.py
kmmbvnr_django-jenkins/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs from os import path from setuptools import setup read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read() setup( name='django-jenkins', version='1.11.0', author='Mikhail Podgurskiy', author_email='[email protected]', description='Plug and play continuous integration with django and jenkins', long_description=read(path.abspath(path.join(path.dirname(__file__), 'README.rst'))), license='LGPL', platforms=['Any'], keywords=['pyunit', 'unittest', 'testrunner', 'hudson', 'jenkins', 'django', 'pylint', 'pep8', 'pyflakes', 'csslint', 'scsslint', 'jshint', 'coverage'], url='http://github.com/kmmbvnr/django-jenkins', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Natural Language :: English', 'Operating System :: OS Independent', "Framework :: Django", "Framework :: Django :: 1.8", "Framework :: Django :: 1.9", 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Testing' ], install_requires=[ 'Django>=1.8', ], packages=['django_jenkins', 'django_jenkins.management', 'django_jenkins.tasks', 'django_jenkins.management.commands'], package_data={'django_jenkins': ['tasks/pylint.rc']}, zip_safe=False, include_package_data=True )
1,823
Python
.py
45
34.022222
89
0.62775
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,231
apps.py
kmmbvnr_django-jenkins/django_jenkins/apps.py
import sys from django.apps import AppConfig from django_jenkins.tasks.with_coverage import CoverageReporter class JenkinsConfig(AppConfig): """ Enable coverage measurement as soon as possible """ name = 'django_jenkins' def __init__(self, app_name, app_module): super(JenkinsConfig, self).__init__(app_name, app_module) self.coverage = None if 'jenkins' in sys.argv and '--enable-coverage' in sys.argv: """ Starting coverage as soon as possible """ self.coverage = CoverageReporter()
582
Python
.py
16
29.3125
69
0.655971
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,232
runner.py
kmmbvnr_django-jenkins/django_jenkins/runner.py
import os import sys import time from unittest import TextTestResult from xml.etree import ElementTree as ET from django.test.runner import DiscoverRunner from django.utils.encoding import smart_text class EXMLTestResult(TextTestResult): def __init__(self, *args, **kwargs): self.case_start_time = time.time() self.run_start_time = None self.tree = None super(EXMLTestResult, self).__init__(*args, **kwargs) def startTest(self, test): self.case_start_time = time.time() super(EXMLTestResult, self).startTest(test) def startTestRun(self): self.tree = ET.Element('testsuite') self.run_start_time = time.time() super(EXMLTestResult, self).startTestRun() def addSuccess(self, test): self.testcase = self._make_testcase_element(test) super(EXMLTestResult, self).addSuccess(test) def addFailure(self, test, err): self.testcase = self._make_testcase_element(test) test_result = ET.SubElement(self.testcase, 'failure') self._add_tb_to_test(test, test_result, err) super(EXMLTestResult, self).addFailure(test, err) def addError(self, test, err): self.testcase = self._make_testcase_element(test) test_result = ET.SubElement(self.testcase, 'error') self._add_tb_to_test(test, test_result, err) super(EXMLTestResult, self).addError(test, err) def addUnexpectedSuccess(self, test): self.testcase = self._make_testcase_element(test) test_result = ET.SubElement(self.testcase, 'skipped') test_result.set('message', 'Test Skipped: Unexpected Success') super(EXMLTestResult, self).addUnexpectedSuccess(test) def addSkip(self, test, reason): self.testcase = self._make_testcase_element(test) test_result = ET.SubElement(self.testcase, 'skipped') test_result.set('message', 'Test Skipped: %s' % reason) super(EXMLTestResult, self).addSkip(test, reason) def addExpectedFailure(self, test, err): self.testcase = self._make_testcase_element(test) test_result = ET.SubElement(self.testcase, 'skipped') self._add_tb_to_test(test, test_result, err) super(EXMLTestResult, self).addExpectedFailure(test, err) def stopTest(self, test): if self.buffer: output = sys.stdout.getvalue() if hasattr(sys.stdout, 'getvalue') else '' if output: sysout = ET.SubElement(self.testcase, 'system-out') sysout.text = smart_text(output, errors='ignore') error = sys.stderr.getvalue() if hasattr(sys.stderr, 'getvalue') else '' if error: syserr = ET.SubElement(self.testcase, 'system-err') syserr.text = smart_text(error, errors='ignore') super(EXMLTestResult, self).stopTest(test) def stopTestRun(self): run_time_taken = time.time() - self.run_start_time self.tree.set('name', 'Django Project Tests') self.tree.set('errors', str(len(self.errors))) self.tree.set('failures', str(len(self.failures))) self.tree.set('skips', str(len(self.skipped))) self.tree.set('tests', str(self.testsRun)) self.tree.set('time', "%.3f" % run_time_taken) super(EXMLTestResult, self).stopTestRun() def _make_testcase_element(self, test): time_taken = time.time() - self.case_start_time classname = ('%s.%s' % (test.__module__, test.__class__.__name__)).split('.') testcase = ET.SubElement(self.tree, 'testcase') testcase.set('time', "%.6f" % time_taken) testcase.set('classname', '.'.join(classname)) testcase.set('name', getattr(test, '_testMethodName', getattr(test, 'description', 'UNKNOWN'))) return testcase def _restoreStdout(self): '''Disables buffering once the stdout/stderr are reset.''' super(EXMLTestResult, self)._restoreStdout() self.buffer = False def _add_tb_to_test(self, test, test_result, err): '''Add a traceback to the test result element''' exc_class, exc_value, tb = err tb_str = self._exc_info_to_string(err, test) test_result.set('type', '%s.%s' % (exc_class.__module__, exc_class.__name__)) test_result.set('message', smart_text(exc_value)) test_result.text = smart_text(tb_str) def dump_xml(self, output_dir): """ Dumps test result to xml """ if not os.path.exists(output_dir): os.makedirs(output_dir) output = ET.ElementTree(self.tree) output.write(os.path.join(output_dir, 'junit.xml'), encoding="utf-8") class CITestSuiteRunner(DiscoverRunner): def __init__(self, output_dir='reports', debug=False, **kwargs): self.output_dir = output_dir self.debug = debug super(CITestSuiteRunner, self).__init__(**kwargs) def run_suite(self, suite, **kwargs): result = self.test_runner( verbosity=self.verbosity, failfast=self.failfast, resultclass=EXMLTestResult, buffer=not self.debug ).run(suite) result.dump_xml(self.output_dir) return result
5,264
Python
.py
110
39.009091
85
0.637285
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,233
run_pep8.py
kmmbvnr_django-jenkins/django_jenkins/tasks/run_pep8.py
import os.path import pep8 from django.conf import settings from . import set_option class Reporter(object): def add_arguments(self, parser): parser.add_argument("--pep8-exclude", dest="pep8-exclude", help="exclude files or directories which match these " "comma separated patterns (default: %s)" % (pep8.DEFAULT_EXCLUDE + ",south_migrations")) parser.add_argument("--pep8-select", dest="pep8-select", help="select errors and warnings (e.g. E,W6)") parser.add_argument("--pep8-ignore", dest="pep8-ignore", help="skip errors and warnings (e.g. E4,W)"), parser.add_argument("--pep8-max-line-length", dest="pep8-max-line-length", type=int, help="set maximum allowed line length (default: %d)" % pep8.MAX_LINE_LENGTH) parser.add_argument("--pep8-rcfile", dest="pep8-rcfile", help="PEP8 configuration file") def run(self, apps_locations, **options): output = open(os.path.join(options['output_dir'], 'pep8.report'), 'w') class JenkinsReport(pep8.BaseReport): def error(instance, line_number, offset, text, check): code = super(JenkinsReport, instance).error(line_number, offset, text, check) if code: sourceline = instance.line_offset + line_number output.write('%s:%s:%s: %s\n' % (instance.filename, sourceline, offset + 1, text)) pep8_options = {} config_file = self.get_config_path(options) if config_file is not None: pep8_options['config_file'] = config_file set_option(pep8_options, 'exclude', options['pep8-exclude'], config_file, default=pep8.DEFAULT_EXCLUDE + ",south_migrations", split=',') set_option(pep8_options, 'select', options['pep8-select'], config_file, split=',') set_option(pep8_options, 'ignore', options['pep8-ignore'], config_file, split=',') set_option(pep8_options, 'max_line_length', options['pep8-max-line-length'], config_file, default=pep8.MAX_LINE_LENGTH) pep8style = pep8.StyleGuide( parse_argv=False, reporter=JenkinsReport, **pep8_options) pep8style.options.report.start() for location in apps_locations: pep8style.input_dir(os.path.relpath(location)) pep8style.options.report.stop() output.close() def get_config_path(self, options): if options['pep8-rcfile']: return options['pep8-rcfile'] rcfile = getattr(settings, 'PEP8_RCFILE', None) if rcfile: return rcfile if os.path.exists('tox.ini'): return 'tox.ini' if os.path.exists('setup.cfg'): return 'setup.cfg'
2,996
Python
.py
57
39.210526
104
0.578911
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,234
run_flake8.py
kmmbvnr_django-jenkins/django_jenkins/tasks/run_flake8.py
import os import pep8 import sys try: from StringIO import StringIO except ImportError: from io import StringIO from flake8.api.legacy import get_style_guide # Quck hack again, 3d time flake8 would be removed, if no volounters found from django.conf import settings from . import set_option class Reporter(object): """ Runs flake8 on python files. """ def add_arguments(self, parser): parser.add_argument('--max-complexity', dest='flake8-max-complexity', type=int, help='McCabe complexity treshold') parser.add_argument("--pep8-exclude", dest="pep8-exclude", help="exclude files or directories which match these " "comma separated patterns (default: %s)" % (pep8.DEFAULT_EXCLUDE + ",south_migrations")) parser.add_argument("--pep8-select", dest="pep8-select", help="select errors and warnings (e.g. E,W6)") parser.add_argument("--pep8-ignore", dest="pep8-ignore", help="skip errors and warnings (e.g. E4,W)") parser.add_argument("--pep8-max-line-length", dest="pep8-max-line-length", type=int, help="set maximum allowed line length (default: %d)" % pep8.MAX_LINE_LENGTH) parser.add_argument("--pep8-rcfile", dest="pep8-rcfile", help="PEP8 configuration file") def run(self, apps_locations, **options): output = open(os.path.join(options['output_dir'], 'flake8.report'), 'w') pep8_options = {} config_file = self.get_config_path(options) if config_file is not None: pep8_options['config_file'] = config_file set_option(pep8_options, 'exclude', options['pep8-exclude'], config_file, default=pep8.DEFAULT_EXCLUDE + ",south_migrations", split=',') set_option(pep8_options, 'select', options['pep8-select'], config_file, split=',') set_option(pep8_options, 'ignore', options['pep8-ignore'], config_file, split=',') set_option(pep8_options, 'max_line_length', options['pep8-max-line-length'], config_file, default=pep8.MAX_LINE_LENGTH) set_option(pep8_options, 'max_complexity', options['flake8-max-complexity'], config_file, default=-1) old_stdout, flake8_output = sys.stdout, StringIO() sys.stdout = flake8_output pep8style = get_style_guide( parse_argv=False, jobs='1', **pep8_options) try: for location in apps_locations: pep8style.input_file(os.path.relpath(location)) finally: sys.stdout = old_stdout flake8_output.seek(0) output.write(flake8_output.read()) output.close() def get_config_path(self, options): if options['pep8-rcfile']: return options['pep8-rcfile'] rcfile = getattr(settings, 'PEP8_RCFILE', None) if rcfile: return rcfile if os.path.exists('tox.ini'): return 'tox.ini' if os.path.exists('setup.cfg'): return 'setup.cfg'
3,373
Python
.py
72
34.25
121
0.573346
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,235
__init__.py
kmmbvnr_django-jenkins/django_jenkins/tasks/__init__.py
import os import itertools from django.conf import settings from django.contrib.staticfiles import finders def static_files_iterator(tested_locations, extension, ignore_patterns=None, additional_settings_list=None): if ignore_patterns is None: ignore_patterns = [] source = (os.path.join(storage.location, path) for finder in finders.get_finders() for path, storage in finder.list(ignore_patterns)) if additional_settings_list and hasattr(settings, additional_settings_list): source = itertools.chain(source, getattr(settings, additional_settings_list)) return (path for path in source if path.endswith(extension) if any(path.startswith(location) for location in tested_locations)) def set_option(conf_dict, opt_name, opt_value, conf_file, default=None, split=None): if conf_file is None: if opt_value is None: opt_value = default if opt_value: if split: opt_value = opt_value.split(split) conf_dict[opt_name] = opt_value
1,072
Python
.py
23
39.086957
108
0.699711
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,236
run_pylint.py
kmmbvnr_django-jenkins/django_jenkins/tasks/run_pylint.py
import os from django.conf import settings from pylint import lint from pylint.reporters.text import TextReporter class ParseableTextReporter(TextReporter): """ Outputs messages in a form recognized by jenkins <filename>:<linenum>:<msg> """ name = 'parseable' line_format = '{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}' class Reporter(object): def add_arguments(self, parser): parser.add_argument("--pylint-rcfile", dest="pylint_rcfile", help="pylint configuration file") parser.add_argument("--pylint-errors-only", dest="pylint_errors_only", action="store_true", default=False, help="pylint output errors only mode") parser.add_argument("--pylint-load-plugins", dest="pylint_load_plugins", help="list of pylint plugins to load") def run(self, apps_locations, **options): output = open(os.path.join(options['output_dir'], 'pylint.report'), 'w') args = [] args.append("--rcfile=%s" % self.get_config_path(options)) if self.get_plugins(options): args.append('--load-plugins=%s' % self.get_plugins(options)) if options['pylint_errors_only']: args += ['--errors-only'] args += apps_locations lint.Run(args, reporter=ParseableTextReporter(output=output), exit=False) output.close() def get_plugins(self, options): if options.get('pylint_load_plugins', None): return options['pylint_load_plugins'] plugins = getattr(settings, 'PYLINT_LOAD_PLUGIN', None) if plugins: return ','.join(plugins) return None def get_config_path(self, options): if options['pylint_rcfile']: return options['pylint_rcfile'] rcfile = getattr(settings, 'PYLINT_RCFILE', 'pylint.rc') if os.path.exists(rcfile): return rcfile # use built-in root_dir = os.path.normpath(os.path.dirname(__file__)) return os.path.join(root_dir, 'pylint.rc')
2,204
Python
.py
50
33.2
81
0.589888
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,237
run_pyflakes.py
kmmbvnr_django-jenkins/django_jenkins/tasks/run_pyflakes.py
# -*- coding: utf-8 -*- import os import re import sys from pyflakes.scripts import pyflakes try: from StringIO import StringIO except ImportError: from io import StringIO class Reporter(object): def add_arguments(self, parser): parser.add_argument("--pyflakes-exclude-dir", action="append", default=['south_migrations'], dest="pyflakes_exclude_dirs", help="Path name to exclude") def run(self, apps_locations, **options): output = open(os.path.join(options['output_dir'], 'pyflakes.report'), 'w') # run pyflakes tool with captured output old_stdout, pyflakes_output = sys.stdout, StringIO() sys.stdout = pyflakes_output try: for location in apps_locations: if os.path.isdir(location): for dirpath, dirnames, filenames in os.walk(os.path.relpath(location)): if dirpath.endswith(tuple( ''.join([os.sep, exclude_dir]) for exclude_dir in options['pyflakes_exclude_dirs'])): continue for filename in filenames: if filename.endswith('.py'): pyflakes.checkPath(os.path.join(dirpath, filename)) else: pyflakes.checkPath(os.path.relpath(location)) finally: sys.stdout = old_stdout # save report pyflakes_output.seek(0) while True: line = pyflakes_output.readline() if not line: break message = re.sub(r': ', r': [E] PYFLAKES:', line) output.write(message) output.close()
1,816
Python
.py
44
27.704545
117
0.538287
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,238
with_coverage.py
kmmbvnr_django-jenkins/django_jenkins/tasks/with_coverage.py
import os import sys from importlib import import_module from django.conf import settings class CoverageReporter(object): def __init__(self): try: import coverage except ImportError: raise ImportError('coverage is not installed') if coverage.__version__ < '4': raise ImportError('coverage>=4 required') coverage_config_file = None for argv in sys.argv: if argv.startswith('--coverage-rcfile='): _, coverage_config_file = argv.split('=') self.coverage = coverage.coverage( branch=True, config_file=coverage_config_file or self.default_coverage_config()) self.coverage.start() def save(self, apps_locations, options): self.coverage.stop() self.coverage.get_data() morfs = self.get_morfs(self.coverage, apps_locations, options) if 'xml' in options['coverage_format']: self.coverage.xml_report(morfs=morfs, outfile=os.path.join(options['output_dir'], 'coverage.xml')) if 'bin' in options['coverage_format']: self.coverage.save() if 'html' in options['coverage_format']: # Dump coverage html self.coverage.html_report(morfs=morfs, directory=os.path.join(options['output_dir'], 'coverage')) def get_morfs(self, coverage, tested_locations, options): excluded = [] # Exclude by module modnames = options.get('coverage_excludes') or getattr(settings, 'COVERAGE_EXCLUDES', []) for modname in modnames: try: excluded.append(os.path.dirname(import_module(modname).__file__)) except ImportError: pass # Exclude by directory excluded.extend(getattr(settings, 'COVERAGE_EXCLUDES_FOLDERS', [])) return [filename for filename in coverage.data.measured_files() if not (os.sep + 'migrations' + os.sep) in filename if not (os.sep + 'south_migrations' + os.sep) in filename if any(filename.startswith(location) for location in tested_locations) if not any(filename.startswith(location) for location in excluded)] def default_coverage_config(self): rcfile = getattr(settings, 'COVERAGE_RCFILE', 'coverage.rc') if os.path.exists(rcfile): return rcfile return None
2,422
Python
.py
52
36.326923
110
0.627493
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,239
jenkins.py
kmmbvnr_django-jenkins/django_jenkins/management/commands/jenkins.py
import os import sys import warnings from importlib import import_module from django.apps import apps from django.conf import settings from django.core.management.commands.test import Command as TestCommand from django_jenkins.runner import CITestSuiteRunner def get_runner(settings, test_runner_class=None): if test_runner_class is None: test_runner_class = getattr( settings, 'JENKINS_TEST_RUNNER', 'django_jenkins.runner.CITestSuiteRunner') test_module_name, test_cls = test_runner_class.rsplit('.', 1) test_module = __import__(test_module_name, {}, {}, test_cls) test_runner = getattr(test_module, test_cls) if not issubclass(test_runner, CITestSuiteRunner): raise ValueError('Your custom TestRunner should extend ' 'the CITestSuiteRunner class.') return test_runner class Command(TestCommand): def __init__(self): self.test_runner = None self.tasks_cls = [import_module(module_name).Reporter for module_name in self.get_task_list()] self.tasks = [task_cls() for task_cls in self.tasks_cls] super(Command, self).__init__() def run_from_argv(self, argv): """ Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments. """ option = '--testrunner=' for arg in argv[2:]: if arg.startswith(option): self.test_runner = arg[len(option):] break super(Command, self).run_from_argv(argv) def get_task_list(self): return getattr(settings, 'JENKINS_TASKS', ()) def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument('--output-dir', dest='output_dir', default="reports", help='Report files directory'), parser.add_argument("--enable-coverage", action="store_true", default=False, help="Measure code coverage"), parser.add_argument('--debug', action='store_true', dest='debug', default=False, help='Do not intercept stdout and stderr, friendly for console debuggers'), parser.add_argument("--coverage-rcfile", dest="coverage_rcfile", default="", help="Specify configuration file."), parser.add_argument("--coverage-format", dest="coverage_format", default="xml", help="Specify coverage output formats html,xml,bin"), parser.add_argument("--coverage-exclude", action="append", default=[], dest="coverage_excludes", help="Module name to exclude"), parser.add_argument("--project-apps-tests", action="store_true", default=False, dest="project_apps_tests", help="Take tests only from project apps") parser._optionals.conflict_handler = 'resolve' for task in self.tasks: if hasattr(task, 'add_arguments'): task.add_arguments(parser) test_runner_class = get_runner(settings, self.test_runner) if hasattr(test_runner_class, 'add_arguments'): test_runner_class.add_arguments(parser) def handle(self, *test_labels, **options): TestRunner = get_runner(settings, options['testrunner']) options['verbosity'] = int(options.get('verbosity')) if options.get('liveserver') is not None: os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options['liveserver'] del options['liveserver'] output_dir = options['output_dir'] if not os.path.exists(output_dir): os.makedirs(output_dir) test_runner = TestRunner(**options) if not test_labels and options['project_apps_tests']: test_labels = getattr(settings, 'PROJECT_APPS', []) failures = test_runner.run_tests(test_labels) if failures: sys.exit(bool(failures)) else: tested_locations = self.get_tested_locations(test_labels) coverage = apps.get_app_config('django_jenkins').coverage if coverage: if options['verbosity'] >= 1: print('Storing coverage info...') coverage.save(tested_locations, options) # run reporters for task in self.tasks: if options['verbosity'] >= 1: print('Executing {0}...'.format(task.__module__)) task.run(tested_locations, **options) if options['verbosity'] >= 1: print('Done') def get_tested_locations(self, test_labels): locations = [] coverage = apps.get_app_config('django_jenkins').coverage if test_labels: pass elif hasattr(settings, 'PROJECT_APPS'): test_labels = settings.PROJECT_APPS elif coverage and coverage.coverage.source: warnings.warn("No PROJECT_APPS settings, using 'source' config from rcfile") locations = coverage.coverage.source else: warnings.warn('No PROJECT_APPS settings, coverage gathered over all apps') test_labels = settings.INSTALLED_APPS for test_label in test_labels: app_config = apps.get_containing_app_config(test_label) if app_config is not None: locations.append(app_config.path) else: warnings.warn('No app found for test: {0}'.format(test_label)) return locations
5,869
Python
.py
120
36.275
103
0.591608
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,240
test_non_bound.py
kmmbvnr_django-jenkins/tests/test_non_bound.py
from django.test import TestCase class NonBoundTest(TestCase): def test_executed(self): """ This test executed only if no --project-apps-tests option provided """
193
Python
.py
6
26.166667
74
0.681081
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,241
settings.py
kmmbvnr_django-jenkins/tests/settings.py
import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ROOT_URLCONF = 'test_app.urls' SECRET_KEY = 'nokey' MIDDLEWARE_CLASSES = () TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] PROJECT_APPS = ( 'django.contrib.sessions', # just to ensure that dotted apps test works 'django_jenkins', 'tests.test_app', 'tests.test_app_dirs', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', ) + PROJECT_APPS DATABASE_ENGINE = 'sqlite3' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.%s' % DATABASE_ENGINE, } } SOUTH_MIGRATION_MODULES = { 'test_app': 'test_app.south_migrations', } JENKINS_TASKS = ( 'django_jenkins.tasks.run_pylint', 'django_jenkins.tasks.run_pep8', 'django_jenkins.tasks.run_pyflakes', 'django_jenkins.tasks.run_flake8', ) COVERAGE_EXCLUDES = ['tests.test_app.not_for_coverage', ] COVERAGE_EXCLUDES_FOLDERS = [os.path.join(PROJECT_ROOT, 'test_app_dirs/not_for_coverage/'), ] # JSHINT_CHECKED_FILES = [os.path.join(PROJECT_ROOT, 'static/js/test.js')] # CSSLINT_CHECKED_FILES = [os.path.join(PROJECT_ROOT, 'static/css/test.css')] PYLINT_LOAD_PLUGIN = ( 'pylint_django', ) STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static/'), ] STATIC_URL = '/media/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': 'ERROR', 'propagate': True, }, } }
2,443
Python
.py
83
23.554217
93
0.620145
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,242
runner.py
kmmbvnr_django-jenkins/tests/runner.py
from django_jenkins.runner import CITestSuiteRunner class CustomTestRunner(CITestSuiteRunner): @classmethod def add_arguments(self, parser): parser.add_argument('--ok', default=False, action='store_true', help='Custom test runner option')
257
Python
.py
5
46.8
105
0.768
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,243
manage.py
kmmbvnr_django-jenkins/tests/manage.py
# -*- coding: utf-8 -*- import os, sys from django.core.management import execute_from_command_line PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, PROJECT_ROOT) if __name__ == "__main__": if len(sys.argv) == 1: sys.argv += ['test'] os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") execute_from_command_line(sys.argv)
404
Python
.py
10
37.1
74
0.682864
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,244
sample.py
kmmbvnr_django-jenkins/tests/test_app_dirs/models/sample.py
from django.db import models class TestDirModel(models.Model): test_text = models.CharField(max_length=250) class Meta: app_label = 'test_app_dirs'
166
Python
.py
5
28.6
48
0.72327
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,245
test_discovery_dir_tests.py
kmmbvnr_django-jenkins/tests/test_app_dirs/tests/test_discovery_dir_tests.py
# -*- coding: utf-8 -*- from django.test import TestCase class DirDiscoveryTest(TestCase): def test_should_be_dicoverd(self): """ Yep! """
169
Python
.py
7
18.857143
38
0.60625
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,246
models.py
kmmbvnr_django-jenkins/tests/test_app/models.py
from django.db import models from test_app.not_for_coverage import one, two # NOQA class TestModel(models.Model): test_text = models.CharField(max_length=250)
166
Python
.py
4
39
54
0.78125
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,247
urls.py
kmmbvnr_django-jenkins/tests/test_app/urls.py
# -*- coding: utf-8 -*- from django.conf.urls import url from django.views.generic.base import TemplateView urlpatterns = [ url(r'^test_click/$', TemplateView.as_view(template_name='test_app/wm_test_click.html'), name='wm_test_click') ]
250
Python
.py
7
32.857143
92
0.710744
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,248
tests.py
kmmbvnr_django-jenkins/tests/test_app/tests.py
# -*- coding: utf-8 -*- import io import sys from xml.etree import ElementTree as ET from django.core import mail from django.test import TestCase from unittest import skip from django.test import LiveServerTestCase from pyvirtualdisplay import Display from selenium import webdriver from django_jenkins.runner import EXMLTestResult class SaintyChecks(TestCase): # @classmethod # def setUpClass(cls): # raise Exception("Ups, should be disabled") def test_mailbox_stubs_not_broken(self): print("Testing mailbox django stubs") mail.send_mail('Test subject', 'Test message', '[email protected]', ['[email protected]']) self.assertTrue(1, len(mail.outbox)) @skip("Check skiped test") def test_is_skipped(self): print("This test should be skipped") def test_junit_xml_with_utf8_stdout_and_stderr(self): sys.stdout.write('\xc4\x85') sys.stderr.write('\xc4\x85') def test_junit_xml_with_invalid_stdout_and_stderr_encoding(self): sys.stdout.write('\xc4') sys.stderr.write('\xc4') # def test_failure(self): # raise Exception("Ups, should be disabled") class EXMLTestResultTests(TestCase): def setUp(self): self.exml_result = EXMLTestResult(None, None, 1) self.exml_result.startTestRun() self.result_element = ET.SubElement(self.exml_result.tree, 'result') def test_non_ascii_traceback(self): try: self.explode_with_unicode_traceback() except ValueError: err = sys.exc_info() else: self.fail() self.exml_result._add_tb_to_test(TestCase('fail'), self.result_element, err) output = self.write_element(self.result_element) self.assert_(output) def test_non_ascii_message(self): try: self.explode_with_unicode_message() except ValueError: err = sys.exc_info() else: self.fail() self.exml_result._add_tb_to_test(TestCase('fail'), self.result_element, err) output = self.write_element(self.result_element) self.assert_(output) def write_element(self, element): # write out the element the way that our TestResult.dump_xml does. # (except not actually to disk.) tree = ET.ElementTree(element) output = io.BytesIO() # this bit blows up if components of the output are byte-strings with non-ascii content. tree.write(output, encoding='utf-8') output_bytes = output.getvalue() return output_bytes def explode_with_unicode_traceback(self): # The following will result in an ascii error message, but the traceback will contain the # full source line, including the comment's non-ascii characters. raise ValueError("dead") # "⚠ Not enough ☕" def explode_with_unicode_message(self): # This source code has only ascii, the exception has a non-ascii message. raise ValueError(u"\N{BIOHAZARD SIGN} Too much \N{HOT BEVERAGE}") class SeleniumTests(LiveServerTestCase): @classmethod def setUpClass(cls): cls.display = Display(visible=0, size=(1024, 768)) cls.display.start() cls.selenium = webdriver.Firefox() super(SeleniumTests, cls).setUpClass() @classmethod def tearDownClass(cls): super(SeleniumTests, cls).tearDownClass() cls.selenium.quit() cls.display.stop() def test_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/test_click/')) self.selenium.find_element_by_id("wm_click").click() self.assertEqual('Button clicked', self.selenium.find_element_by_id("wm_target").text)
3,756
Python
.py
88
35.113636
97
0.666758
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,249
0001_initial.py
kmmbvnr_django-jenkins/tests/test_app/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='TestModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('test_text', models.CharField(max_length=250)), ], options={ }, bases=(models.Model,), ), ]
562
Python
.py
18
22.388889
114
0.558442
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,250
0001_initial.py
kmmbvnr_django-jenkins/tests/test_app/south_migrations/0001_initial.py
from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): a = 1 # pyflakes/pylint violation pass def backwards(self, orm): pass
200
Python
.py
7
22.714286
41
0.685864
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,251
example_steps.py
kmmbvnr_django-jenkins/tests/test_app/features/example_steps.py
# -*- coding: utf-8 -*- from lettuce import step, before @before.each_scenario def setup_scenario(scenario): scenario.numbers = [] @step('(?:Given|And|When) the number "(.*)"(?: is added to (?:it|them))?') def given_the_number(step, number): step.scenario.numbers.append(int(number)) @step('Then the result should be "(.*)"') def then_the_result_should_equal(step, result): actual = sum(step.scenario.numbers) assert int(result) == actual, "%s != %s" % (result, actual)
489
Python
.py
12
38.166667
74
0.675105
kmmbvnr/django-jenkins
944
279
19
LGPL-3.0
9/5/2024, 5:09:21 PM (Europe/Amsterdam)
5,252
setup.py
overviewer_Minecraft-Overviewer/setup.py
#!/usr/bin/env python3 import sys import traceback # quick version check if sys.version_info[0] == 2 or (sys.version_info[0] == 3 and sys.version_info[1] < 4): print("Sorry, the Overviewer requires at least Python 3.4 to run.") sys.exit(1) from distutils.core import setup from distutils.extension import Extension from distutils.command.build import build from distutils.command.clean import clean from distutils.command.build_ext import build_ext from distutils.command.sdist import sdist from distutils.cmd import Command from distutils.dir_util import remove_tree from distutils.sysconfig import get_python_inc from distutils import log import os, os.path import glob import platform import time import overviewer_core.util as util import numpy try: import py2exe except ImportError: py2exe = None try: import py2app from setuptools.extension import Extension except ImportError: py2app = None # make sure our current working directory is the same directory # setup.py is in curdir = os.path.split(sys.argv[0])[0] if curdir: os.chdir(curdir) # now, setup the keyword arguments for setup # (because we don't know until runtime if py2exe/py2app is available) setup_kwargs = {} setup_kwargs['ext_modules'] = [] setup_kwargs['cmdclass'] = {} setup_kwargs['options'] = {} # # metadata # # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(fname).read() setup_kwargs['name'] = 'Minecraft-Overviewer' setup_kwargs['version'] = util.findGitVersion() setup_kwargs['description'] = 'Generates large resolution images of a Minecraft map.' setup_kwargs['url'] = 'http://overviewer.org/' setup_kwargs['author'] = 'Andrew Brown' setup_kwargs['author_email'] = '[email protected]' setup_kwargs['license'] = 'GNU General Public License v3' setup_kwargs['long_description'] = read('README.rst') # top-level files that should be included as documentation doc_files = ['COPYING.txt', 'README.rst', 'CONTRIBUTORS.rst', 'sample_config.py'] # helper to create a 'data_files'-type sequence recursively for a given dir def recursive_data_files(src, dest=None): if dest is None: dest = src ret = [] for dirpath, dirnames, filenames in os.walk(src): current_dest = os.path.relpath(dirpath, src) if current_dest == '.': current_dest = dest else: current_dest = os.path.join(dest, current_dest) current_sources = map(lambda p: os.path.join(dirpath, p), filenames) ret.append((current_dest, current_sources)) return ret # helper to create a 'package_data'-type sequence recursively for a given dir def recursive_package_data(src, package_dir='overviewer_core'): full_src = os.path.join(package_dir, src) ret = [] for dirpath, dirnames, filenames in os.walk(full_src, topdown=False): current_path = os.path.relpath(dirpath, package_dir) for filename in filenames: ret.append(os.path.join(current_path, filename)) return ret # Finds the system-wide path from within a venv. # Taken from https://github.com/pyinstaller/pyinstaller/blob/master/PyInstaller/hooks/pre_find_module_path/hook-distutils.py def find_system_module_path(): # opcode is not a virtualenv module, so we can use it to find the stdlib. Technique taken from virtualenv's # "distutils" package detection at # https://github.com/pypa/virtualenv/blob/16.3.0/virtualenv_embedded/distutils-init.py#L5 import opcode system_module_path = os.path.normpath(os.path.dirname(opcode.__file__)) return system_module_path # # py2exe options # if py2exe is not None: setup_kwargs['comments'] = "http://overviewer.org" # py2exe likes a very particular type of version number: setup_kwargs['version'] = util.findGitVersion().replace("-",".") setup_kwargs['console'] = ['overviewer.py', 'contribManager.py'] setup_kwargs['data_files'] = [('', doc_files)] setup_kwargs['data_files'] += recursive_data_files('overviewer_core/data/textures', 'textures') setup_kwargs['data_files'] += recursive_data_files('overviewer_core/data/web_assets', 'web_assets') setup_kwargs['data_files'] += recursive_data_files('overviewer_core/data/js_src', 'js_src') setup_kwargs['data_files'] += recursive_data_files('contrib', 'contrib') setup_kwargs['zipfile'] = None if platform.system() == 'Windows' and '64bit' in platform.architecture(): b = 3 else: b = 1 setup_kwargs['options']['py2exe'] = {'bundle_files' : b, 'excludes': 'Tkinter', 'includes': ['fileinput', 'overviewer_core.items', 'overviewer_core.aux_files.genPOI']} # # py2app options # if py2app is not None: setup_kwargs['app'] = ['overviewer.py'] setup_kwargs['options']['py2app'] = {'argv_emulation' : False} setup_kwargs['setup_requires'] = ['py2app'] # # script, package, and data # setup_kwargs['packages'] = ['overviewer_core', 'overviewer_core/aux_files'] setup_kwargs['scripts'] = ['overviewer.py'] setup_kwargs['package_data'] = {'overviewer_core': recursive_package_data('data/textures') + recursive_package_data('data/web_assets') + recursive_package_data('data/js_src')} if py2exe is None: setup_kwargs['data_files'] = [('share/doc/minecraft-overviewer', doc_files)] # # c_overviewer extension # # Third-party modules - we depend on numpy for everything # Obtain the numpy include directory. This logic works across numpy versions. try: numpy_include = numpy.get_include() except AttributeError: numpy_include = numpy.get_numpy_include() try: pil_include = os.environ['PIL_INCLUDE_DIR'].split(os.pathsep) except Exception: pil_include = [ os.path.join(get_python_inc(plat_specific=1), 'Imaging') ] if not os.path.exists(pil_include[0]): pil_include = [ ] # used to figure out what files to compile # auto-created from files in primitives/, but we need the raw names so # we can use them later. primitives = [] for name in glob.glob("overviewer_core/src/primitives/*.c"): name = os.path.split(name)[-1] name = os.path.splitext(name)[0] primitives.append(name) c_overviewer_files = ['main.c', 'composite.c', 'iterate.c', 'endian.c', 'rendermodes.c', 'block_class.c'] c_overviewer_files += ['primitives/%s.c' % (mode) for mode in primitives] c_overviewer_files += ['Draw.c'] c_overviewer_includes = ['overviewer.h', 'rendermodes.h'] c_overviewer_files = ['overviewer_core/src/' + s for s in c_overviewer_files] c_overviewer_includes = ['overviewer_core/src/' + s for s in c_overviewer_includes] # really ugly hack for our scuffed CI, remove this once we move # to something else. The problem is that virtualenv somehow # now overrides the base_prefix (which it shouldn't do) which # makes distutils unable to find our Python library python_lib_dirs = None if platform.system() == 'Windows': ci_python_dir = os.path.split(find_system_module_path())[0] python_lib_dirs = [os.path.join(ci_python_dir, "Libs")] setup_kwargs['ext_modules'].append(Extension( 'overviewer_core.c_overviewer', c_overviewer_files, include_dirs=['.', numpy_include] + pil_include, library_dirs=python_lib_dirs, depends=c_overviewer_includes, extra_link_args=[] )) # tell build_ext to build the extension in-place # (NOT in build/) setup_kwargs['options']['build_ext'] = {'inplace' : 1} # custom clean command to remove in-place extension # and the version file, primitives header class CustomClean(clean): def run(self): # do the normal cleanup clean.run(self) # try to remove '_composite.{so,pyd,...}' extension, # regardless of the current system's extension name convention build_ext = self.get_finalized_command('build_ext') ext_fname = build_ext.get_ext_filename('overviewer_core.c_overviewer') versionpath = os.path.join("overviewer_core", "overviewer_version.py") primspath = os.path.join("overviewer_core", "src", "primitives.h") for fname in [ext_fname, primspath]: if os.path.exists(fname): try: log.info("removing '%s'", fname) if not self.dry_run: os.remove(fname) except OSError: log.warning("'%s' could not be cleaned -- permission denied", fname) else: log.debug("'%s' does not exist -- can't clean it", fname) # now try to purge all *.pyc files for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), ".")): for f in files: if f.endswith(".pyc"): if self.dry_run: log.warning("Would remove %s", os.path.join(root,f)) else: os.remove(os.path.join(root, f)) def generate_version_py(): try: outstr = "" outstr += "VERSION=%r\n" % util.findGitVersion() outstr += "HASH=%r\n" % util.findGitHash() outstr += "BUILD_DATE=%r\n" % time.asctime() outstr += "BUILD_PLATFORM=%r\n" % platform.processor() outstr += "BUILD_OS=%r\n" % platform.platform() f = open("overviewer_core/overviewer_version.py", "w") f.write(outstr) f.close() except Exception: print("WARNING: failed to build overviewer_version file") def generate_primitives_h(): global primitives prims = [p.lower().replace('-', '_') for p in primitives] outstr = "/* this file is auto-generated by setup.py */\n" for p in prims: outstr += "extern RenderPrimitiveInterface primitive_{0};\n".format(p) outstr += "static RenderPrimitiveInterface *render_primitives[] = {\n" for p in prims: outstr += " &primitive_{0},\n".format(p) outstr += " NULL\n" outstr += "};\n" with open("overviewer_core/src/primitives.h", "w") as f: f.write(outstr) class CustomSDist(sdist): def run(self): # generate the version file generate_version_py() generate_primitives_h() sdist.run(self) class CustomBuild(build): def run(self): # generate the version file try: generate_version_py() generate_primitives_h() build.run(self) print("\nBuild Complete") except Exception: traceback.print_exc(limit=1) print("\nFailed to build Overviewer!") print("Please review the errors printed above and the build instructions") print("at <http://docs.overviewer.org/en/latest/building/>. If you are") print("still having build problems, file an incident on the github tracker") print("or find us in IRC.") sys.exit(1) class CustomBuildExt(build_ext): def build_extensions(self): c = self.compiler.compiler_type if c == "msvc": # customize the build options for this compilier for e in self.extensions: e.extra_link_args.append("/MANIFEST") e.extra_link_args.append("/DWINVER=0x060") e.extra_link_args.append("/D_WIN32_WINNT=0x060") if c == "unix": # customize the build options for this compilier for e in self.extensions: e.extra_compile_args.append("-Wno-unused-variable") # quell some annoying warnings e.extra_compile_args.append("-Wno-unused-function") # quell some annoying warnings e.extra_compile_args.append("-Wdeclaration-after-statement") e.extra_compile_args.append("-Werror=declaration-after-statement") e.extra_compile_args.append("-O3") e.extra_compile_args.append("-std=gnu99") # build in place, and in the build/ tree self.inplace = False build_ext.build_extensions(self) self.inplace = True build_ext.build_extensions(self) setup_kwargs['cmdclass']['clean'] = CustomClean setup_kwargs['cmdclass']['sdist'] = CustomSDist setup_kwargs['cmdclass']['build'] = CustomBuild setup_kwargs['cmdclass']['build_ext'] = CustomBuildExt ### setup(**setup_kwargs)
12,409
Python
.py
286
37.34965
175
0.668269
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,253
contribManager.py
overviewer_Minecraft-Overviewer/contribManager.py
#!/usr/bin/env python3 """The contrib manager is used to help control the contrib scripts that are shipped with overviewer in Windows packages.""" import ast import os.path import sys scripts = { # keys are names, values are scripts "convertCyrillic": "cyrillic_convert.py", "playerInspect": "playerInspect.py", "testRender": "testRender.py", "pngit": "png-it.py", "gallery": "gallery.py", "regionTrimmer": "regionTrimmer.py", "contributors": "contributors.py" } # you can symlink or hardlink contribManager.py to another name to have it # automatically find the right script to run. For example: # > ln -s contribManager.py pngit.exe # > chmod +x pngit.exe # > ./pngit.exe -h # figure out what script to execute argv = os.path.basename(sys.argv[0]) if argv[-4:] == ".exe": argv = argv[0:-4] if argv[-3:] == ".py": argv = argv[0:-3] usage = """Usage: %s --list-contribs | <script name> <arguments> Executes a contrib script. Options: --list-contribs Lists the supported contrib scripts """ % os.path.basename(sys.argv[0]) if argv in scripts.keys(): script = scripts[argv] sys.argv[0] = script else: if "--list-contribs" in sys.argv: for contrib in scripts.keys(): # use an AST to extract the docstring for this module script = scripts[contrib] with open(os.path.join("contrib", script)) as f: d = f.read() node = ast.parse(d, script) docstring = ast.get_docstring(node) if docstring: docstring = docstring.strip().splitlines()[0] else: docstring = "(No description found. Add one by adding a docstring to %s.)" % script print("%s : %s" % (contrib, docstring)) sys.exit(0) if len(sys.argv) > 1 and sys.argv[1] in scripts.keys(): script = scripts[sys.argv[1]] sys.argv = [script] + sys.argv[2:] else: print(usage, file=sys.stderr) sys.exit(1) torun = os.path.join("contrib", script) if not os.path.exists(torun): print("Script '%s' is missing!" % script, file=sys.stderr) sys.exit(1) exec(compile(open(torun, "rb").read(), torun, 'exec'))
2,264
Python
.py
61
31.606557
99
0.623971
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,254
sample_config.py
overviewer_Minecraft-Overviewer/sample_config.py
# This is a sample config file, meant to give you an idea of how to format your # config file and what's possible. # Define the path to your world here. 'My World' in this case will show up as # the world name on the map interface. If you change it, be sure to also change # the referenced world names in the render definitions below. worlds['My World'] = "/path/to/your/world" # Define where to put the output here. outputdir = "/tmp/test_render" # This is an item usually specified in a renders dictionary below, but if you # set it here like this, it becomes the default for all renders that don't # define it. # Try "smooth_lighting" for even better looking maps! rendermode = "lighting" renders["render1"] = { 'world': 'My World', 'title': 'A regular render', } # This example is the same as above, but rotated renders["render2"] = { 'world': 'My World', 'northdirection': 'upper-right', 'title': 'Upper-right north direction', } # Here's how to do a nighttime render. Also try "smooth_night" instead of "night" renders["render3"] = { 'world': 'My World', 'title': 'Nighttime', # Notice how this overrides the rendermode default specified above 'rendermode': 'night', }
1,254
Python
.py
30
38.166667
81
0.697617
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,255
overviewer.py
overviewer_Minecraft-Overviewer/overviewer.py
#!/usr/bin/env python3 # This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function import platform import sys # quick version check if sys.version_info[0] == 2 or (sys.version_info[0] == 3 and sys.version_info[1] < 4): print("Sorry, the Overviewer requires at least Python 3.4 to run.") sys.exit(1) import os import os.path import re import subprocess import multiprocessing import time import logging from argparse import ArgumentParser from collections import OrderedDict from overviewer_core import util from overviewer_core import logger from overviewer_core import textures from overviewer_core import optimizeimages, world from overviewer_core import config_parser, tileset, assetmanager, dispatcher from overviewer_core import cache from overviewer_core import observer from overviewer_core.nbt import CorruptNBTError helptext = """ %(prog)s [--rendermodes=...] [options] <World> <Output Dir> %(prog)s --config=<config file> [options]""" def main(): # bootstrap the logger with defaults logger.configure() if os.name == "posix": if os.geteuid() == 0: logging.warning("You are running Overviewer as root. " "It is recommended that you never do this, " "as it is dangerous for your system. If you are running " "into permission errors, fix your file/directory " "permissions instead. Overviewer does not need access to " "critical system resources and therefore does not require " "root access.") try: with open("/etc/redhat-release", "r") as release_f: rel_contents = release_f.read() try: major_rel = re.search(r'\d(\.\d+)?', rel_contents).group(0).split('.')[0] if major_rel == "6": logging.warning( "We will be dropping support for this release of your distribution " "soon. Please upgrade as soon as possible, or you will not receive " "future Overviewer updates.") except AttributeError: pass except IOError: pass try: cpus = multiprocessing.cpu_count() except NotImplementedError: cpus = 1 avail_north_dirs = ['lower-left', 'upper-left', 'upper-right', 'lower-right', 'auto'] # Parse for basic options parser = ArgumentParser(usage=helptext) parser.add_argument("-c", "--config", dest="config", action="store", help="Specify the config file to use.") parser.add_argument("-p", "--processes", dest="procs", action="store", type=int, help="The number of local worker processes to spawn. Defaults to the " "number of CPU cores your computer has.") parser.add_argument("--pid", dest="pid", action="store", help="Specify the pid file to use.") # Options that only apply to the config-less render usage parser.add_argument("--rendermodes", dest="rendermodes", action="store", help="If you're not using a config file, specify which rendermodes to " "render with this option. This is a comma-separated list.") parser.add_argument("world", nargs='?', help="Path or name of the world you want to render.") parser.add_argument("output", nargs='?', help="Output directory for the rendered map.") # Useful one-time render modifiers: render_modifiers = parser.add_mutually_exclusive_group() render_modifiers.add_argument("--forcerender", dest="forcerender", action="store_true", help="Force re-render the entire map.") render_modifiers.add_argument("--check-tiles", dest="checktiles", action="store_true", help="Check each tile on disk and re-render old tiles.") render_modifiers.add_argument("--no-tile-checks", dest="notilechecks", action="store_true", help="Only render tiles that come from chunks that have changed " "since the last render (the default).") # Useful one-time debugging options: parser.add_argument("--check-terrain", dest="check_terrain", action="store_true", help="Try to locate the texture files. Useful for debugging texture" " problems.") parser.add_argument("-V", "--version", dest="version", help="Display version information and then exits.", action="store_true") parser.add_argument("--check-version", dest="checkversion", help="Fetch information about the latest version of Overviewer.", action="store_true") parser.add_argument("--update-web-assets", dest='update_web_assets', action="store_true", help="Update web assets. Will *not* render tiles or update " "overviewerConfig.js.") # Log level options: parser.add_argument("-q", "--quiet", dest="quiet", action="count", default=0, help="Print less output. You can specify this option multiple times.") parser.add_argument("-v", "--verbose", dest="verbose", action="count", default=0, help="Print more output. You can specify this option multiple times.") parser.add_argument("--simple-output", dest="simple", action="store_true", default=False, help="Use a simple output format, with no colors or progress bars.") # create a group for "plugin exes" # (the concept of a plugin exe is only loosely defined at this point) exegroup = parser.add_argument_group("Other Scripts", "These scripts may accept different " "arguments than the ones listed above.") exegroup.add_argument("--genpoi", dest="genpoi", action="store_true", help="Run the genPOI script.") exegroup.add_argument("--skip-scan", dest="skipscan", action="store_true", help="When running GenPOI, don't scan for entities.") exegroup.add_argument("--skip-players", dest="skipplayers", action="store_true", help="When running GenPOI, don't scan player data.") args, unknowns = parser.parse_known_args() # Check for possible shell quoting issues if len(unknowns) > 0 and args.world and args.output: possible_mistakes = [] for i in range(len(unknowns) + 1): possible_mistakes.append(" ".join([args.world, args.output] + unknowns[:i])) possible_mistakes.append(" ".join([args.output] + unknowns[:i])) for mistake in possible_mistakes: if os.path.exists(mistake): logging.warning("Looks like you tried to make me use {0} as an argument, but " "forgot to quote the argument correctly. Try using \"{0}\" " "instead if the spaces are part of the path.".format(mistake)) parser.error("Too many arguments.") parser.error("Too many arguments.") # first thing to do is check for stuff in the exegroup: if args.genpoi: # remove the "--genpoi" option from sys.argv before running genPI sys.argv.remove("--genpoi") g = __import__("overviewer_core.aux_files", {}, {}, ["genPOI"]) g.genPOI.main() return 0 # re-configure the logger now that we've processed the command line options logger.configure(logging.INFO + 10 * args.quiet - 10 * args.verbose, verbose=args.verbose > 0, simple=args.simple) ########################################################################## # This section of main() runs in response to any one-time options we have, # such as -V for version reporting if args.version: print("Minecraft Overviewer %s" % util.findGitVersion() + " (%s)" % util.findGitHash()[:7]) try: import overviewer_core.overviewer_version as overviewer_version print("built on %s" % overviewer_version.BUILD_DATE) if args.verbose > 0: print("Build machine: %s %s" % (overviewer_version.BUILD_PLATFORM, overviewer_version.BUILD_OS)) print("Read version information from %r" % overviewer_version.__file__) except ImportError: print("(build info not found)") if args.verbose > 0: print("Python executable: %r" % sys.executable) print(sys.version) if not args.checkversion: return 0 if args.checkversion: print("Currently running Minecraft Overviewer %s" % util.findGitVersion() + " (%s)" % util.findGitHash()[:7]) try: from urllib import request import json latest_ver = json.loads(request.urlopen("http://overviewer.org/download.json") .read())['src'] print("Latest version of Minecraft Overviewer %s (%s)" % (latest_ver['version'], latest_ver['commit'][:7])) print("See https://overviewer.org/downloads for more information.") except Exception: print("Failed to fetch latest version info.") if args.verbose > 0: import traceback traceback.print_exc() else: print("Re-run with --verbose for more details.") return 1 return 0 if args.pid: if os.path.exists(args.pid): try: with open(args.pid, 'r') as fpid: pid = int(fpid.read()) if util.pid_exists(pid): print("Overviewer is already running (pid exists) - exiting.") return 0 except (IOError, ValueError): pass with open(args.pid, "w") as f: f.write(str(os.getpid())) # if --check-terrain was specified, but we have NO config file, then we cannot # operate on a custom texture path. we do terrain checking with a custom texture # pack later on, after we've parsed the config file if args.check_terrain and not args.config: import hashlib from overviewer_core.textures import Textures tex = Textures() logging.info("Looking for a few common texture files...") try: f = tex.find_file("assets/minecraft/textures/block/sandstone_top.png", verbose=True) f = tex.find_file("assets/minecraft/textures/block/grass_block_top.png", verbose=True) f = tex.find_file("assets/minecraft/textures/block/diamond_ore.png", verbose=True) f = tex.find_file("assets/minecraft/textures/block/acacia_planks.png", verbose=True) # 1.16 f = tex.find_file("assets/minecraft/textures/block/ancient_debris_top.png", verbose=True) except IOError: logging.error("Could not find any texture files.") return 1 return 0 # if no arguments are provided, print out a helpful message if not (args.world and args.output) and not args.config: # first provide an appropriate error for bare-console users # that don't provide any options if util.is_bare_console(): print("\n") print("The Overviewer is a console program. Please open a Windows command prompt") print("first and run Overviewer from there. Further documentation is available at") print("http://docs.overviewer.org/\n") print("\n") print("For a quick-start guide on Windows, visit the following URL:\n") print("http://docs.overviewer.org/en/latest/win_tut/windowsguide/\n") else: # more helpful message for users who know what they're doing logging.error("You must either specify --config or give me a world directory " "and output directory.") parser.print_help() list_worlds() return 1 ########################################################################## # This section does some sanity checking on the command line options passed # in. It checks to see if --config was given that no worldname/destdir were # given, and vice versa if args.config and (args.world and args.output): print() print("If you specify --config, you need to specify the world to render as well as " "the destination in the config file, not on the command line.") print("Put something like this in your config file:") print("worlds['myworld'] = %r" % args[0]) print("outputdir = %r" % (args[1] if len(args) > 1 else "/path/to/output")) print() logging.error("You cannot specify both --config AND a world + output directory on the " "command line.") parser.print_help() return 1 if not args.config and (args.world or args.output) and not (args.world and args.output): logging.error("You must specify both the world directory and an output directory") parser.print_help() return 1 ######################################################################### # These two halfs of this if statement unify config-file mode and # command-line mode. mw_parser = config_parser.MultiWorldParser() if not args.config: # No config file mode. worldpath, destdir = map(os.path.expanduser, [args.world, args.output]) logging.debug("Using %r as the world directory", worldpath) logging.debug("Using %r as the output directory", destdir) mw_parser.set_config_item("worlds", {'world': worldpath}) mw_parser.set_config_item("outputdir", destdir) rendermodes = ['lighting'] if args.rendermodes: rendermodes = args.rendermodes.replace("-", "_").split(",") # Now for some good defaults renders = OrderedDict() for rm in rendermodes: renders["world-" + rm] = { "world": "world", "title": "Overviewer Render (%s)" % rm, "rendermode": rm, } mw_parser.set_config_item("renders", renders) else: if args.rendermodes: logging.error("You cannot specify --rendermodes if you give a config file. " "Configure your rendermodes in the config file instead.") parser.print_help() return 1 # Parse the config file try: mw_parser.parse(os.path.expanduser(args.config)) except config_parser.MissingConfigException as e: # this isn't a "bug", so don't print scary traceback logging.error(str(e)) util.nice_exit(1) # Add in the command options here, perhaps overriding values specified in # the config if args.procs: mw_parser.set_config_item("processes", args.procs) # Now parse and return the validated config try: config = mw_parser.get_validated_config() except Exception as ex: if args.verbose: logging.exception("An error was encountered with your configuration. " "See the information below.") else: # no need to print scary traceback! logging.error("An error was encountered with your configuration.") logging.error(str(ex)) return 1 if args.check_terrain: # we are already in the "if configfile" branch logging.info("Looking for a few common texture files...") for render_name, render in config['renders'].items(): logging.info("Looking at render %r.", render_name) # find or create the textures object texopts = util.dict_subset(render, ["texturepath"]) tex = textures.Textures(**texopts) f = tex.find_file("assets/minecraft/textures/block/sandstone_top.png", verbose=True) f = tex.find_file("assets/minecraft/textures/block/grass_block_top.png", verbose=True) f = tex.find_file("assets/minecraft/textures/block/diamond_ore.png", verbose=True) f = tex.find_file("assets/minecraft/textures/block/oak_planks.png", verbose=True) return 0 ############################################################ # Final validation steps and creation of the destination directory logging.info("Welcome to Minecraft Overviewer version %s (%s)!" % (util.findGitVersion(), util.findGitHash()[:7])) logging.debug("Current log level: {0}.".format(logging.getLogger().level)) def set_renderchecks(checkname, num): for name, render in config['renders'].items(): if render.get('renderchecks', 0) == 3: logging.warning(checkname + " ignoring render " + repr(name) + " since it's " "marked as \"don't render\".") else: render['renderchecks'] = num if args.forcerender: logging.info("Forcerender mode activated. ALL tiles will be rendered.") set_renderchecks("forcerender", 2) elif args.checktiles: logging.info("Checking all tiles for updates manually.") set_renderchecks("checktiles", 1) elif args.notilechecks: logging.info("Disabling all tile mtime checks. Only rendering tiles " "that need updating since last render.") set_renderchecks("notilechecks", 0) if not config['renders']: logging.error("You must specify at least one render in your config file. Check the " "documentation at http://docs.overviewer.org if you're having trouble.") return 1 ##################### # Do a few last minute things to each render dictionary here for rname, render in config['renders'].items(): # Convert render['world'] to the world path, and store the original # in render['worldname_orig'] try: worldpath = config['worlds'][render['world']] except KeyError: logging.error("Render %s's world is '%s', but I could not find a corresponding entry " "in the worlds dictionary.", rname, render['world']) return 1 render['worldname_orig'] = render['world'] render['world'] = worldpath # If 'forcerender' is set, change renderchecks to 2 if render.get('forcerender', False): render['renderchecks'] = 2 # check if overlays are set, if so, make sure that those renders exist if render.get('overlay', []) != []: for x in render.get('overlay'): if x != rname: try: renderLink = config['renders'][x] except KeyError: logging.error("Render %s's overlay is '%s', but I could not find a " "corresponding entry in the renders dictionary.", rname, x) return 1 else: logging.error("Render %s's overlay contains itself.", rname) return 1 destdir = config['outputdir'] if not destdir: logging.error("You must specify the output directory in your config file.") logging.error("e.g. outputdir = '/path/to/outputdir'") return 1 if not os.path.exists(destdir): try: os.mkdir(destdir) except OSError: logging.exception("Could not create the output directory.") return 1 ######################################################################## # Now we start the actual processing, now that all the configuration has # been gathered and validated # create our asset manager... ASSMAN assetMrg = assetmanager.AssetManager(destdir, config.get('customwebassets', None)) # If we've been asked to update web assets, do that and then exit if args.update_web_assets: assetMrg.output_noconfig() logging.info("Web assets have been updated.") return 0 # The changelist support. changelists = {} for render in config['renders'].values(): if 'changelist' in render: path = render['changelist'] if path not in changelists: out = open(path, "w") logging.debug("Opening changelist %s (%s).", out, out.fileno()) changelists[path] = out else: out = changelists[path] render['changelist'] = out.fileno() tilesets = [] # saves us from creating the same World object over and over again worldcache = {} # same for textures texcache = {} # Set up the cache objects to use caches = [] caches.append(cache.LRUCache(size=100)) # TODO: optionally more caching layers here renders = config['renders'] for render_name, render in renders.items(): logging.debug("Found the following render thing: %r", render) # find or create the world object try: w = worldcache[render['world']] except KeyError: try: w = world.World(render['world']) except CorruptNBTError as e: logging.error("Failed to open world %r.", render['world']) raise e except world.UnsupportedVersion as e: for ln in str(e).split('\n'): logging.error(ln) sys.exit(1) worldcache[render['world']] = w # find or create the textures object texopts = util.dict_subset(render, ["texturepath", "bgcolor", "northdirection"]) texopts_key = tuple(texopts.items()) if texopts_key not in texcache: tex = textures.Textures(**texopts) logging.info("Generating textures...") tex.generate() logging.debug("Finished generating textures.") texcache[texopts_key] = tex else: tex = texcache[texopts_key] try: logging.debug("Asking for regionset %r." % render['dimension'][1]) rset = w.get_regionset(render['dimension'][1]) except IndexError: logging.error("Sorry, I can't find anything to render! Are you sure there are .mca " "files in the world directory of %s?" % render['world']) return 1 if rset is None: # indicates no such dimension was found logging.warning("Sorry, you requested dimension '%s' for %s, but I couldn't find it.", render['dimension'][0], render_name) continue ################# # Apply any regionset transformations here # Insert a layer of caching above the real regionset. Any world # tranformations will pull from this cache, but their results will not # be cached by this layer. This uses a common pool of caches; each # regionset cache pulls from the same underlying cache object. rset = world.CachedRegionSet(rset, caches) # If a crop is requested, wrap the regionset here if "crop" in render: rsets = [] for zone in render['crop']: rsets.append(world.CroppedRegionSet(rset, *zone)) else: rsets = [rset] # If this is to be a rotated regionset, wrap it in a RotatedRegionSet # object if (render['northdirection'] > 0): newrsets = [] for r in rsets: r = world.RotatedRegionSet(r, render['northdirection']) newrsets.append(r) rsets = newrsets ############################### # Do the final prep and create the TileSet object # create our TileSet from this RegionSet tileset_dir = os.path.abspath(os.path.join(destdir, render_name)) # only pass to the TileSet the options it really cares about render['name'] = render_name # perhaps a hack. This is stored here for the asset manager tileSetOpts = util.dict_subset(render, [ "name", "imgformat", "renderchecks", "rerenderprob", "bgcolor", "defaultzoom", "imgquality", "imglossless", "optimizeimg", "rendermode", "worldname_orig", "title", "dimension", "changelist", "showspawn", "overlay", "base", "poititle", "maxzoom", "showlocationmarker", "minzoom", "center"]) tileSetOpts.update({"spawn": w.find_true_spawn()}) # TODO find a better way to do this for rset in rsets: tset = tileset.TileSet(w, rset, assetMrg, tex, tileSetOpts, tileset_dir) tilesets.append(tset) # If none of the requested dimenstions exist, tilesets will be empty if not tilesets: logging.error("There are no tilesets to render! There's nothing to do, so exiting.") return 1 # Do tileset preprocessing here, before we start dispatching jobs logging.info("Preprocessing...") for ts in tilesets: ts.do_preprocessing() # Output initial static data and configuration assetMrg.initialize(tilesets) # multiprocessing dispatcher if config['processes'] == 1: dispatch = dispatcher.Dispatcher() else: dispatch = dispatcher.MultiprocessingDispatcher( local_procs=config['processes']) dispatch.render_all(tilesets, config['observer']) dispatch.close() assetMrg.finalize(tilesets) for out in changelists.values(): logging.debug("Closing %s (%s).", out, out.fileno()) out.close() if config['processes'] == 1: logging.debug("Final cache stats:") for c in caches: logging.debug("\t%s: %s hits, %s misses", c.__class__.__name__, c.hits, c.misses) if args.pid: os.remove(args.pid) logging.info("Your render has been written to '%s', open index.html to view it." % destdir) return 0 def list_worlds(): "Prints out a brief summary of saves found in the default directory" print() worlds = world.get_worlds() if not worlds: print('No world saves found in the usual place.') return print("Detected saves:") # get max length of world name worldNameLen = max([len(x) for x in worlds] + [len("World")]) formatString = "%-" + str(worldNameLen) + "s | %-8s | %-16s | %s " print(formatString % ("World", "Playtime", "Modified", "Path")) print(formatString % ("-" * worldNameLen, "-" * 8, '-' * 16, '-' * 4)) for name, info in sorted(worlds.items()): if isinstance(name, str) and name.startswith("World") and len(name) == 6: try: world_n = int(name[-1]) # we'll catch this one later, when it shows up as an # integer key continue except ValueError: pass if info['LastPlayed'] > 0: timestamp = time.strftime("%Y-%m-%d %H:%M", time.localtime(info['LastPlayed'] / 1000)) else: timestamp = "" if info['Time'] > 0: playtime = info['Time'] / 20 playstamp = '%d:%02d' % (playtime / 3600, playtime / 60 % 60) else: playstamp = "" path = info['path'] print(formatString % (name, playstamp, timestamp, path)) found_corrupt = any([x.get("IsCorrupt") for x in worlds.values()]) if found_corrupt: print() print("An error has been detected in one or more of your worlds (see the above table).") print("This is usually due to a corrupt level.dat file. Corrupt worlds need to be " "repaired before Overviewer can render them.") if __name__ == "__main__": multiprocessing.freeze_support() try: ret = main() util.nice_exit(ret) except textures.TextureException as e: # this isn't a "bug", so don't print scary traceback logging.error(str(e)) util.nice_exit(1) except Exception as e: logging.exception("""An error has occurred. This may be a bug. Please let us know! See http://docs.overviewer.org/en/latest/index.html#help This is the error that occurred:""") util.nice_exit(1) except KeyboardInterrupt: logging.info("Interrupted by user. Aborting.") util.nice_exit(2)
29,543
Python
.py
583
39.626072
118
0.595166
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,256
test_contributors.py
overviewer_Minecraft-Overviewer/test/test_contributors.py
import unittest from io import StringIO, BytesIO from textwrap import dedent from unittest.mock import patch import contrib.contributors as contrib class TestContributors(unittest.TestCase): def setUp(self): self.contrib_file_lines = dedent("""\ ============ Contributors ============ This file contains a list of every person who has contributed code to Overviewer. --------------- Original Author --------------- * Andrew Brown <[email protected]> ------------------------- Long-term Contributions ------------------------- These contributors have made many changes, over a fairly long time span, or for many different parts of the code. * Alejandro Aguilera <[email protected]> ------------------------ Short-term Contributions ------------------------ These contributors have made specific changes for a particular bug fix or feature. * 3decibels <[email protected]>""").split("\n") def test_format_contributor_single_name(self): contributor = {"name": "John", "email": "<[email protected]>"} self.assertEqual( contrib.format_contributor(contributor), " * John <[email protected]>" ) def test_format_contributor_multiple_names(self): contributor = {"name": "John Smith", "email": "<[email protected]>"} self.assertEqual( contrib.format_contributor(contributor), " * John Smith <[email protected]>" ) def test_get_old_contributors(self): expected = [{"name": "Andrew Brown", "email": "<[email protected]>"}, {"name": "Alejandro Aguilera", "email": "<[email protected]>"}, {"name": "3decibels", "email": "<[email protected]>"}] self.assertListEqual(contrib.get_old_contributors(self.contrib_file_lines), expected) @patch('subprocess.run') def test_get_contributors(self, mock_run): mock_run.return_value.stdout = dedent("""\ 1 3decibels <[email protected]> 585 Aaron Griffith <[email protected]> 1 Aaron1011 <[email protected]> """).encode() expected = [{"count": 1, "name": "3decibels", "email": "<[email protected]>"}, {"count": 585, "name": "Aaron Griffith", "email": "<[email protected]>"}, {"count": 1, "name": "Aaron1011", "email": "<[email protected]>"}] self.assertListEqual(contrib.get_contributors(), expected) def test_get_new_contributors_new_contributors_alphabetical_order(self): contributors = [{"count": 1, "name": "3decibels", "email": "<[email protected]>"}, {"count": 585, "name": "Aaron Griffith", "email": "<[email protected]>"}, {"count": 1, "name": "Aaron1011", "email": "<[email protected]>"}] old_contributors = [{"name": "Andrew Brown", "email": "<[email protected]>"}, {"name": "Alejandro Aguilera", "email": "<[email protected]>"}, {"name": "3decibels", "email": "<[email protected]>"}] new_contributors, new_alias, new_email = contrib.get_new_contributors( contributors, old_contributors) self.assertListEqual(new_contributors, [{"count": 1, "name": "Aaron1011", "email": "<[email protected]>"}, { "count": 585, "name": "Aaron Griffith", "email": "<[email protected]>"}]) def test_get_new_contributors_new_alias(self): contributors = [{"count": 1, "name": "new_name", "email": "<[email protected]>"}, {"count": 585, "name": "Aaron Griffith", "email": "<[email protected]>"}, {"count": 1, "name": "Aaron1011", "email": "<[email protected]>"}] old_contributors = [{"name": "Andrew Brown", "email": "<[email protected]>"}, {"name": "Alejandro Aguilera", "email": "<[email protected]>"}, {"name": "3decibels", "email": "<[email protected]>"}] new_contributors, new_alias, new_email = contrib.get_new_contributors( contributors, old_contributors) self.assertListEqual( new_alias, [({"count": 1, "name": "new_name", "email": "<[email protected]>"}, "3decibels")]) def test_get_new_contributors_new_email(self): contributors = [{"count": 1, "name": "3decibels", "email": "<[email protected]>"}, {"count": 585, "name": "Aaron Griffith", "email": "<[email protected]>"}, {"count": 1, "name": "Aaron1011", "email": "<[email protected]>"}] old_contributors = [{"name": "Andrew Brown", "email": "<[email protected]>"}, {"name": "Alejandro Aguilera", "email": "<[email protected]>"}, {"name": "3decibels", "email": "<[email protected]>"}] new_contributors, new_alias, new_email = contrib.get_new_contributors( contributors, old_contributors) self.assertListEqual( new_email, [({"count": 1, "name": "3decibels", "email": "<[email protected]>"}, "<[email protected]>")]) def test_merge_short_term_contributors(self): new_contributors = [{"count": 1, "name": "Aaron1011", "email": "<[email protected]>"}, { "count": 585, "name": "Aaron Griffith", "email": "<[email protected]>"}] expected = ['============', 'Contributors', '============', '', 'This file contains a list of every person who has contributed code to', 'Overviewer.', '', '---------------', 'Original Author', '---------------', '', ' * Andrew Brown <[email protected]>', '', '-------------------------', 'Long-term Contributions', '-------------------------', '', 'These contributors have made many changes, over a fairly long time span, or', 'for many different parts of the code.', '', ' * Alejandro Aguilera <[email protected]>', '', '------------------------', 'Short-term Contributions', '------------------------', '', 'These contributors have made specific changes for a particular bug fix or', 'feature.', '', ' * 3decibels <[email protected]>', ' * Aaron1011 <[email protected]>\n', ' * Aaron Griffith <[email protected]>\n'] self.assertListEqual(contrib.merge_short_term_contributors( self.contrib_file_lines, new_contributors), expected) if __name__ == "__main__": unittest.main()
7,247
Python
.py
129
41.48062
118
0.506279
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,257
test_cyrillic_convert.py
overviewer_Minecraft-Overviewer/test/test_cyrillic_convert.py
import unittest import tempfile from contrib.cyrillic_convert import convert class TestCyrillicConvert(unittest.TestCase): def test_convert(self): gibberish = '{chunk: [-2, 0],y: 65,msg: "ðåëèãèè",x: -20,z: 4,type: "sign"}' cyrillic = '{chunk: [-2, 0],y: 65,msg: "религии",x: -20,z: 4,type: "sign"}' self.assertEqual(convert(gibberish), cyrillic)
392
Python
.py
8
42.375
84
0.673025
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,258
test_regionTrimmer.py
overviewer_Minecraft-Overviewer/test/test_regionTrimmer.py
import unittest from pathlib import Path from tempfile import TemporaryDirectory import networkx import contrib.regionTrimmer as region_trimmer class TestRegionTrimmer(unittest.TestCase): def test_get_nodes(self): coords = [(0, 0), (0, -1), (-1, 0), (-1, -1)] with TemporaryDirectory() as tmpdirname: region_file = Path(tmpdirname) for x, z in coords: region_fname = "r.{x}.{z}.mca".format(x=x, z=z) (region_file / region_fname).touch() nodes = region_trimmer.get_nodes(region_file) self.assertListEqual(sorted(nodes), sorted(coords)) def test_get_nodes_returns_empty_list_when_no_region_files(self): with TemporaryDirectory() as tmpdirname: region_file = Path(tmpdirname) (region_file / "not_region_file.txt").touch() nodes = region_trimmer.get_nodes(region_file) self.assertListEqual(nodes, []) def test_get_region_file_from_node(self): node = (0, 0) regionset_path = Path('/path/to/regions') self.assertEqual(region_trimmer.get_region_file_from_node( regionset_path, node), Path('/path/to/regions/r.0.0.mca')) def test_get_graph_bounds(self): """ Should return (max_x, min_x, max_z, min_z) of all nodes """ graph = networkx.Graph() graph.add_nodes_from([(0, 0), (0, -1), (-1, 0), (-1, -1)]) self.assertEqual(region_trimmer.get_graph_bounds(graph), (0, -1, 0, -1)) def test_get_graph_center_by_bounds(self): self.assertEqual(region_trimmer.get_graph_center_by_bounds((0, -1, 0, -1)), (-1, -1)) def test_generate_edges(self): graph = networkx.Graph() graph.add_nodes_from( [(0, 0), (0, -1), (-1, 0), (-1, -1)] ) graph = region_trimmer.generate_edges(graph) self.assertEqual( graph.adj, { (0, -1): {(0, 0): {}, (-1, -1): {}}, (0, 0): { (0, -1): {}, (-1, 0): {}, (-1, -1): {}, }, (-1, 0): {(0, 0): {}, (-1, -1): {}}, (-1, -1): { (0, -1): {}, (0, 0): {}, (-1, 0): {}, }, }, )
2,357
Python
.py
57
30.122807
93
0.505461
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,259
test_tileobj.py
overviewer_Minecraft-Overviewer/test/test_tileobj.py
import unittest from overviewer_core.tileset import iterate_base4, RenderTile items = [ ((-4,-8), (0,0)), ((-2,-8), (0,1)), ((0,-8), (1,0)), ((2,-8), (1,1)), ((-4,-4), (0,2)), ((-2,-4), (0,3)), ((0,-4), (1,2)), ((2,-4), (1,3)), ((-4,0), (2,0)), ((-2,0), (2,1)), ((0,0), (3,0)), ((2,0), (3,1)), ((-4,4), (2,2)), ((-2,4), (2,3)), ((0,4), (3,2)), ((2,4), (3,3)), ] class TileTest(unittest.TestCase): def test_compute_path(self): """Tests that the correct path is computed when a col,row,depth is given to compute_path """ for path in iterate_base4(7): t1 = RenderTile.from_path(path) col = t1.col row = t1.row depth = len(path) t2 = RenderTile.compute_path(col, row, depth) self.assertEqual(t1, t2) def test_equality(self): t1 = RenderTile(-6, -20, (0,1,2,3)) self.assertEqual(t1, RenderTile(-6, -20, (0,1,2,3))) self.assertNotEqual(t1, RenderTile(-4, -20, (0,1,2,3))) self.assertNotEqual(t1, RenderTile(-6, -24, (0,1,2,3))) self.assertNotEqual(t1, RenderTile(-6, -20, (0,1,2,0))) def test_depth2_from_path(self): """Test frompath on all 16 tiles of a depth 2 tree""" for (col, row), path in items: t = RenderTile.from_path(path) self.assertEqual(t.col, col) self.assertEqual(t.row, row) def test_depth2_compute_path(self): """Test comptue_path on all 16 tiles of a depth 2 tree""" for (col, row), path in items: t = RenderTile.compute_path(col, row, 2) self.assertEqual(t.path, path) if __name__ == "__main__": unittest.main()
1,836
Python
.py
51
26.941176
74
0.497169
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,260
test_cache.py
overviewer_Minecraft-Overviewer/test/test_cache.py
import unittest from overviewer_core import cache class TestLRU(unittest.TestCase): def setUp(self): self.lru = cache.LRUCache(size=5) def test_single_insert(self): self.lru[1] = 2 self.assertEqual(self.lru[1], 2) def test_multiple_insert(self): self.lru[1] = 2 self.lru[3] = 4 self.lru[5] = 6 self.assertEqual(self.lru[1], 2) self.assertEqual(self.lru[3], 4) self.assertEqual(self.lru[5], 6) def test_full(self): self.lru[1] = 'asdf' self.lru[2] = 'asdf' self.lru[3] = 'asdf' self.lru[4] = 'asdf' self.lru[5] = 'asdf' self.lru[6] = 'asdf' self.assertRaises(KeyError, self.lru.__getitem__, 1) self.assertEqual(self.lru[2], 'asdf') self.assertEqual(self.lru[3], 'asdf') self.assertEqual(self.lru[4], 'asdf') self.assertEqual(self.lru[5], 'asdf') self.assertEqual(self.lru[6], 'asdf') def test_lru(self): self.lru[1] = 'asdf' self.lru[2] = 'asdf' self.lru[3] = 'asdf' self.lru[4] = 'asdf' self.lru[5] = 'asdf' self.assertEqual(self.lru[1], 'asdf') self.assertEqual(self.lru[2], 'asdf') self.assertEqual(self.lru[4], 'asdf') self.assertEqual(self.lru[5], 'asdf') # 3 should be evicted now self.lru[6] = 'asdf' self.assertRaises(KeyError, self.lru.__getitem__, 3) self.assertEqual(self.lru[1], 'asdf') self.assertEqual(self.lru[2], 'asdf') self.assertEqual(self.lru[4], 'asdf') self.assertEqual(self.lru[5], 'asdf') self.assertEqual(self.lru[6], 'asdf')
1,684
Python
.py
46
28.347826
60
0.574939
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,261
__init__.py
overviewer_Minecraft-Overviewer/test/__init__.py
# Magic spell to have us find overviewer_core import sys import os import os.path sys.path.insert(0, os.path.join(os.path.split(__file__)[0], '..'))
149
Python
.py
5
28.8
66
0.729167
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,262
test_rendertileset.py
overviewer_Minecraft-Overviewer/test/test_rendertileset.py
import unittest from itertools import chain from overviewer_core.tileset import iterate_base4, RendertileSet from overviewer_core.util import roundrobin class RendertileSetTest(unittest.TestCase): # If you change this definition, you must also change the hard-coded # results list in test_posttraverse() tile_paths = frozenset([ # Entire subtree 0/0 is in the set, nothing else under 0 (0,0,0), (0,0,1), (0,0,2), (0,0,3), # A few tiles under quadrant 1 (1,0,3), (1,1,3), (1,2,0), # Entire subtree under quadrant 2 is in the set (2,0,0), (2,0,1), (2,0,2), (2,0,3), (2,1,0), (2,1,1), (2,1,2), (2,1,3), (2,2,0), (2,2,1), (2,2,2), (2,2,3), (2,3,0), (2,3,1), (2,3,2), (2,3,3), # Nothing under quadrant 3 ]) # The paths as yielded by posttraversal, in an expanding-from-the-center # order. tile_paths_posttraversal_lists = [ [ (0,0,3), (0,0,1), (0,0,2), (0,0,0), (0,0), (0,), ], [ (1,2,0), (1,2), (1,0,3), (1,0), (1,1,3), (1,1), (1,), ], [ (2,1,1), (2,1,0), (2,1,3), (2,1,2), (2,1), (2,0,1), (2,0,3), (2,0,0), (2,0,2), (2,0), (2,3,1), (2,3,0), (2,3,3), (2,3,2), (2,3), (2,2,1), (2,2,0), (2,2,3), (2,2,2), (2,2), (2,), ], ] # Non-round robin post-traversal: finish the first top-level quadrant # before moving to the second etc. tile_paths_posttraversal = list(chain(*tile_paths_posttraversal_lists)) + [()] # Round-robin post-traversal: start rendering to all directions from the # center. tile_paths_posttraversal_robin = list(roundrobin(tile_paths_posttraversal_lists)) + [()] def setUp(self): self.tree = RendertileSet(3) for t in self.tile_paths: self.tree.add(t) def test_query(self): """Make sure the correct tiles in the set""" for path in iterate_base4(3): if path in self.tile_paths: self.assertTrue( self.tree.query_path(path) ) else: self.assertFalse( self.tree.query_path(path) ) def test_iterate(self): """Make sure iterating over the tree returns each tile exactly once""" dirty = set(self.tile_paths) for p in self.tree: # Can't use assertIn, was only added in 2.7 self.assertTrue(p in dirty) # Should not see this one again dirty.remove(p) # Make sure they were all returned self.assertEqual(len(dirty), 0) def test_iterate_levelmax(self): """Same as test_iterate, but specifies the level explicitly""" dirty = set(self.tile_paths) for p in self.tree.iterate(3): # Can't use assertIn, was only added in 2.7 self.assertTrue(p in dirty) # Should not see this one again dirty.remove(p) # Make sure they were all returned self.assertEqual(len(dirty), 0) def test_iterate_fail(self): """Meta-test: Make sure test_iterate() would actually fail""" # if an extra item were returned""" self.tree.add((1,1,1)) self.assertRaises(AssertionError, self.test_iterate) # If something was supposed to be returned but wasn't tree = RendertileSet(3) c = len(self.tile_paths) // 2 for t in self.tile_paths: tree.add(t) c -= 1 if c <= 0: break self.tree = tree self.assertRaises(AssertionError, self.test_iterate) def test_count(self): self.assertEqual(self.tree.count(), len(self.tile_paths)) def test_bool(self): "Tests the boolean status of a node" self.assertTrue(self.tree) t = RendertileSet(3) self.assertFalse(t) t.add((0,0,0)) self.assertTrue(t) def test_query_level(self): "Tests querying at a level other than max" # level 2 l2 = set() for p in self.tile_paths: l2.add(p[0:2]) for path in iterate_base4(2): if path in l2: self.assertTrue( self.tree.query_path(path) ) else: self.assertFalse( self.tree.query_path(path) ) # level 1: self.assertTrue( self.tree.query_path((0,))) self.assertTrue( self.tree.query_path((1,))) self.assertTrue( self.tree.query_path((2,))) self.assertFalse( self.tree.query_path((3,))) def test_iterate_level(self): """Test iterating at a level other than max""" # level 2 l2 = set() for p in self.tile_paths: l2.add(p[0:2]) for p in self.tree.iterate(2): self.assertTrue(p in l2, "%s was not supposed to be returned!" % (p,)) l2.remove(p) self.assertEqual(len(l2), 0, "Never iterated over these items: %s" % l2) # level 1 l1 = set() for p in self.tile_paths: l1.add(p[0:1]) for p in self.tree.iterate(1): self.assertTrue(p in l1, "%s was not supposed to be returned!" % (p,)) l1.remove(p) self.assertEqual(len(l1), 0, "Never iterated over these items: %s" % l1) def test_posttraverse(self): """Test a post-traversal of the tree's dirty tiles""" # Expect the results in this proper order. iterator = iter(self.tree.posttraversal()) for expected, actual in zip(self.tile_paths_posttraversal, iterator): self.assertEqual(actual, expected) self.assertRaises(StopIteration, next, iterator) def test_posttraverse_roundrobin(self): """Test a round-robin post-traversal of the tree's dirty tiles""" # Expect the results in this proper order. iterator = iter(self.tree.posttraversal(robin=True)) for expected, actual in zip(self.tile_paths_posttraversal_robin, iterator): self.assertEqual(actual, expected) self.assertRaises(StopIteration, next, iterator) def test_count_all(self): """Tests getting a count of all tiles (render tiles plus upper tiles) """ c = self.tree.count_all() self.assertEqual(c, 35) if __name__ == "__main__": unittest.main()
6,912
Python
.py
196
24.903061
92
0.529693
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,263
test_tileset.py
overviewer_Minecraft-Overviewer/test/test_tileset.py
import unittest import tempfile import shutil from collections import defaultdict import os import os.path import random from overviewer_core import tileset # Supporing data # chunks list: chunkx, chunkz mapping to chunkmtime # In comments: col, row chunks = { (0, 0): 5, # 0, 0 (0, 1): 5, # 1, 1 (0, 2): 5, # 2, 2 (0, 3): 5, # 3, 3 (0, 4): 5, # 4, 4 (1, 0): 5, # 1, -1 (1, 1): 5, # 2, 0 (1, 2): 5, # 3, 1 (1, 3): 5, # 4, 2 (1, 4): 5, # 5, 3 (2, 0): 5, # 2, -2 (2, 1): 5, # 3, -1 (2, 2): 5, # 4, 0 (2, 3): 5, # 5, 1 (2, 4): 5, # 6, 2 (3, 0): 5, # 3, -3 (3, 1): 5, # 4, -2 (3, 2): 5, # 5, -1 (3, 3): 5, # 6, 0 (3, 4): 5, # 7, 1 (4, 0): 5, # 4, -4 (4, 1): 5, # 5, -3 (4, 2): 5, # 6, -2 (4, 3): 5, # 7, -1 (4, 4): 5, # 8, 0 } # Supporting resources ###################### class FakeRegionset(object): def __init__(self, chunks): self.chunks = dict(chunks) def get_chunk(self, x,z): return NotImplementedError() def iterate_chunks(self): for (x,z),mtime in self.chunks.items(): yield x,z,mtime def iterate_newer_chunks(self, filemtime): for (x,z),mtime in self.chunks.items(): yield x,z,mtime def get_chunk_mtime(self, x, z): try: return self.chunks[x,z] except KeyError: return None class FakeAssetmanager(object): def __init__(self, lastrendertime): self.lrm = lastrendertime def get_tileset_config(self, _): return {'lastrendertime': self.lrm} def get_tile_set(chunks): """Given the dictionary mapping chunk coordinates their mtimes, returns a dict mapping the tiles that are to be rendered to their mtimes that are expected. Useful for passing into the create_fakedir() function. Used by the compare_iterate_to_expected() method. """ tile_set = defaultdict(int) for (chunkx, chunkz), chunkmtime in chunks.items(): col, row = tileset.convert_coords(chunkx, chunkz) for tilec, tiler in tileset.get_tiles_by_chunk(col, row): tile = tileset.RenderTile.compute_path(tilec, tiler, 5) tile_set[tile.path] = max(tile_set[tile.path], chunkmtime) # At this point, tile_set holds all the render-tiles for tile, tile_mtime in tile_set.copy().items(): # All render-tiles are length 5. Hard-code its upper tiles for i in reversed(range(5)): tile_set[tile[:i]] = max(tile_set[tile[:i]], tile_mtime) return dict(tile_set) def create_fakedir(outputdir, tiles): """Takes a base output directory and a tiles dict mapping tile paths to tile mtimes as returned by get_tile_set(), creates the "tiles" (empty files) and sets mtimes appropriately """ for tilepath, tilemtime in tiles.items(): dirpath = os.path.join(outputdir, *(str(x) for x in tilepath[:-1])) if len(tilepath) == 0: imgname = "base.png" else: imgname = str(tilepath[-1]) + ".png" if not os.path.exists(dirpath): os.makedirs(dirpath) finalpath = os.path.join(dirpath, imgname) open(finalpath, 'w').close() os.utime(finalpath, (tilemtime, tilemtime)) # The test cases ################ class TilesetTest(unittest.TestCase): def setUp(self): # Set up the region set self.rs = FakeRegionset(chunks) self.tempdirs = [] # Consistent random numbers self.r = random.Random(1) def tearDown(self): for d in self.tempdirs: shutil.rmtree(d) def get_outputdir(self): d = tempfile.mkdtemp(prefix="OVTEST") self.tempdirs.append(d) return d def get_tileset(self, options, outputdir, preprocess=None): """Returns a newly created TileSet object and return it. A set of default options are provided. Any options passed in will override the defaults. The output directory is passed in and it is recommended to use a directory from self.get_outputdir() preprocess, if given, is a function that takes the tileset object. It is called before do_preprocessing() """ defoptions = { 'name': 'world name', 'bgcolor': '#000000', 'imgformat': 'png', 'optimizeimg': 0, 'rendermode': 'normal', 'rerenderprob': 0 } defoptions.update(options) ts = tileset.TileSet(None, self.rs, FakeAssetmanager(0), None, defoptions, outputdir) if preprocess: preprocess(ts) ts.do_preprocessing() return ts def compare_iterate_to_expected(self, ts, chunks): """Runs iterate_work_items on the tileset object and compares its output to what we'd expect if it was run with the given chunks chunks is a dictionary whose keys are chunkx,chunkz. This method calculates from that set of chunks the tiles they touch and their parent tiles, and compares that to the output of ts.iterate_work_items(). """ paths = set(x[0] for x in ts.iterate_work_items(0)) # Get what tiles we expect to be returned expected = get_tile_set(chunks) # Check that all paths returned are in the expected list for tilepath in paths: self.assertTrue(tilepath in expected, "%s was not expected to be returned. Expected %s" % (tilepath, expected)) # Now check that all expected tiles were indeed returned for tilepath in expected.keys(): self.assertTrue(tilepath in paths, "%s was expected to be returned but wasn't: %s" % (tilepath, paths)) def test_get_phase_length(self): ts = self.get_tileset({'renderchecks': 2}, self.get_outputdir()) self.assertEqual(ts.get_num_phases(), 1) self.assertEqual(ts.get_phase_length(0), len(get_tile_set(chunks))) def test_forcerender_iterate(self): """Tests that a rendercheck mode 2 iteration returns every render-tile and upper-tile """ ts = self.get_tileset({'renderchecks': 2}, self.get_outputdir()) self.compare_iterate_to_expected(ts, self.rs.chunks) def test_update_chunk(self): """Tests that an update in one chunk properly updates just the necessary tiles for rendercheck mode 0, normal operation. This shouldn't touch the filesystem at all. """ # Update one chunk with a newer mtime updated_chunks = { (0,0): 6 } self.rs.chunks.update(updated_chunks) # Create the tileset and set its last render time to 5 ts = self.get_tileset({'renderchecks': 0}, self.get_outputdir(), lambda ts: setattr(ts, 'last_rendertime', 5)) # Now see if the return is what we expect self.compare_iterate_to_expected(ts, updated_chunks) def test_update_chunk2(self): """Same as above but with a different set of chunks """ # Pick 3 random chunks to update chunks = list(self.rs.chunks.keys()) self.r.shuffle(chunks) updated_chunks = {} for key in chunks[:3]: updated_chunks[key] = 6 self.rs.chunks.update(updated_chunks) ts = self.get_tileset({'renderchecks': 0}, self.get_outputdir(), lambda ts: setattr(ts, 'last_rendertime', 5)) self.compare_iterate_to_expected(ts, updated_chunks) def test_rendercheckmode_1(self): """Tests that an interrupted render will correctly pick up tiles that need rendering """ # For this we actually need to set the tile mtimes on disk and have the # TileSet object figure out from that what it needs to render. # Strategy: set some tiles on disk to mtime 3, and TileSet needs to # find them and update them to mtime 5 as reported by the RegionSet # object. # Chosen at random: outdated_tiles = [ (0,3,3,3,3), (1,2,2,2,1), (2,1,1), (3,) ] # These are the tiles that we also expect it to return, even though # they were not outdated, since they depend on the outdated tiles additional = [ (0,3,3,3), (0,3,3), (0,3), (0,), (1,2,2,2), (1,2,2), (1,2), (1,), (2,1), (2,), (), ] outputdir = self.get_outputdir() # Fill the output dir with tiles all_tiles = get_tile_set(self.rs.chunks) all_tiles.update(dict((x,3) for x in outdated_tiles)) create_fakedir(outputdir, all_tiles) # Create the tileset and do the scan ts = self.get_tileset({'renderchecks': 1}, outputdir) # Now see if it's right paths = set(x[0] for x in ts.iterate_work_items(0)) expected = set(outdated_tiles) | set(additional) for tilepath in paths: self.assertTrue(tilepath in expected, "%s was not expected to be returned. Expected %s" % (tilepath, expected)) for tilepath in expected: self.assertTrue(tilepath in paths, "%s was expected to be returned but wasn't: %s" % (tilepath, paths))
9,561
Python
.py
232
32.034483
123
0.586062
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,264
test_testRender.py
overviewer_Minecraft-Overviewer/test/test_testRender.py
import tempfile import unittest from unittest.mock import patch from subprocess import CalledProcessError, PIPE, STDOUT import contrib.testRender as test_render from io import StringIO from shlex import split class TestTestRender(unittest.TestCase): @patch("contrib.testRender.run") def test_check_call_raises_CalledProcessError_from_subprocess_run(self, m_run): m_run.side_effect = CalledProcessError(1, "python program.js") with self.assertRaises(CalledProcessError): test_render.check_call(["python", "program.js"]) @patch("contrib.testRender.run") def test_check_call_captures_stdout_if_not_verbose(self, m_run): test_render.check_call(["python", "program.py"]) args, kwargs = m_run.call_args self.assertEqual(kwargs['stdout'], PIPE) self.assertEqual(kwargs['stderr'], STDOUT) @patch("contrib.testRender.run") def test_check_call_does_not_capture_stdout_if_verbose(self, m_run): test_render.check_call(["python", "program.py"], verbose=True) args, kwargs = m_run.call_args self.assertEqual(kwargs['stdout'], None) self.assertEqual(kwargs['stderr'], None) @patch('sys.stdout', new_callable=StringIO) @patch("contrib.testRender.run") def test_check_call_prints_exception_output_if_verbose(self, m_run, m_out): m_run.side_effect = CalledProcessError( 1, "python program.js", output="SyntaxError: invalid syntax") with self.assertRaises(CalledProcessError): test_render.check_call(["python", "program.js"], verbose=True) self.assertEqual(m_out.getvalue().strip(), "SyntaxError: invalid syntax") @patch("contrib.testRender.run") def test_check_output_captures_stdout(self, m_run): test_render.check_call(["python", "program.py"]) args, kwargs = m_run.call_args self.assertEqual(kwargs['stdout'], PIPE) @patch('contrib.testRender.check_output') def test_get_commits(self, m_check_output): gitrange = '2eca1a5fb5fa7eeb5494abb350cd535f67acfb8b..08a86a52abfabd59ac68b37dc7e5270bd7fb328a' m_check_output.return_value = ( "commit 2eca1a5fb5fa7eeb5494abb350cd535f67acfb8b\nAuthor: Andrew " "<andrew@fry.(none)>\nDate: Sun Aug 22 10:16:10 2010 -0400\n\n " " initial comit\n\n:000000 100644 0000000 c398ada A\tchunk.py\n:000000 " "100644 0000000 d5ee6ed A\tnbt.py\n:000000 100644 0000000 8fc65c9 A\ttextures.py\n:" "000000 100644 0000000 6934326 A\tworld.py\n\ncommit 08a86a52abfabd59ac68b37dc7e5270bd7fb328a" "\nAuthor: Andrew <andrew@fry.(none)>\nDate: Tue Aug 24 21:11:57 2010 -0400\n\n " "uses multiprocessing to speed up rendering. Caches chunks\n\n:1" ) result = list(test_render.get_commits(gitrange)) self.assertListEqual(result, ['2eca1a5fb5fa7eeb5494abb350cd535f67acfb8b', '08a86a52abfabd59ac68b37dc7e5270bd7fb328a']) @patch('contrib.testRender.check_output', return_value="my-feature-branch") def test_get_current_branch(self, m_check_output): self.assertEqual(test_render.get_current_branch(), "my-feature-branch") @patch('contrib.testRender.check_output', return_value="HEAD") def test_get_current_branch_returns_none_for_detached_head(self, m_check_output): self.assertIsNone(test_render.get_current_branch()) @patch('contrib.testRender.check_output', return_value="3f1f3d748e1c79843279ba18ab65a34368b95b67") def test_get_current_commit(self, m_check_output): self.assertEqual( test_render.get_current_branch(), "3f1f3d748e1c79843279ba18ab65a34368b95b67" ) @patch('contrib.testRender.get_current_branch', return_value="my-feature-branch") def test_get_current_ref_returns_branch_name_if_possible(self, m_branch): self.assertEqual(test_render.get_current_ref(), "my-feature-branch") @patch('contrib.testRender.get_current_commit', return_value="3f1f3d748e1c79843279ba18ab65a34368b95b67") @patch('contrib.testRender.get_current_branch', return_value=None) def test_get_current_ref_returns_current_commit_if_no_branch(self, m_branch, m_commit): self.assertEqual( test_render.get_current_ref(), "3f1f3d748e1c79843279ba18ab65a34368b95b67" ) @patch('contrib.testRender.check_output') def test_get_commits(self, m_check_output): m_check_output.return_value = "\n".join( [ "41ceaeab58473416bb79680ab21211764e6f1908", "a4d0daa91c25a51ca95182301e503c020900dafe", "05906c81f5778a543dfab14e77231db0a99bae24", ] ) gitrange = "41ceaeab58473416bb79680ab21211764e6f1908..05906c81f5778a543dfab14e77231db0a99bae24" result = list(test_render.get_commits(gitrange)) self.assertListEqual( result, [ "41ceaeab58473416bb79680ab21211764e6f1908", "a4d0daa91c25a51ca95182301e503c020900dafe", "05906c81f5778a543dfab14e77231db0a99bae24" ] )
5,178
Python
.py
94
46.085106
108
0.691321
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,265
test_settings.py
overviewer_Minecraft-Overviewer/test/test_settings.py
import unittest from collections import OrderedDict from overviewer_core import config_parser from overviewer_core.settingsValidators import ValidationException from overviewer_core import world from overviewer_core import rendermodes class SettingsTest(unittest.TestCase): def setUp(self): self.s = config_parser.MultiWorldParser() def test_missing(self): "Validates that a non-existant settings.py causes an exception" self.assertRaises(config_parser.MissingConfigException, self.s.parse, "doesnotexist.py") def test_existing_file(self): self.s.parse("test/data/settings/settings_test_1.py") things = self.s.get_validated_config() # no exceptions so far. that's a good thing # Test the default self.assertEqual(things['renders']['myworld']['bgcolor'], (26,26,26,0)) # Test a non-default self.assertEqual(things['renders']['otherworld']['bgcolor'], (255,255,255,0)) self.assertEqual(things['renders']['myworld']['northdirection'], world.UPPER_LEFT) def test_rendermode_validation(self): self.s.parse("test/data/settings/settings_test_rendermode.py") self.assertRaises(ValidationException,self.s.get_validated_config) def test_manual(self): """Tests that manually setting the config parser works, you don't have to do it from a file """ fromfile = config_parser.MultiWorldParser() fromfile.parse("test/data/settings/settings_test_1.py") self.s.set_config_item("worlds", { 'test': "test/data/settings/test_world", }) self.s.set_config_item("renders", OrderedDict([ ("myworld", { "title": "myworld title", "world": "test", "rendermode": rendermodes.normal, "northdirection": "upper-left", }), ("otherworld", { "title": "otherworld title", "world": "test", "rendermode": rendermodes.normal, "bgcolor": "#ffffff" }), ])) self.s.set_config_item("outputdir", "/tmp/fictional/outputdir") first = fromfile.get_validated_config() del first["observer"] second = self.s.get_validated_config() del second["observer"] self.assertEqual(first, second) def test_rendermode_string(self): self.s.set_config_item("worlds", { 'test': "test/data/settings/test_world", }) self.s.set_config_item("outputdir", "/tmp/fictional/outputdir") self.s.set_config_item("renders", { "myworld": { "title": "myworld title", "world": "test", "rendermode": "normal", "northdirection": "upper-left", }, }) p = self.s.get_validated_config() self.assertEqual(p['renders']['myworld']['rendermode'], rendermodes.normal) if __name__ == "__main__": unittest.main()
3,161
Python
.py
71
33.112676
96
0.58966
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,266
test_playerInspect.py
overviewer_Minecraft-Overviewer/test/test_playerInspect.py
import unittest from io import StringIO from pathlib import Path from textwrap import dedent from unittest.mock import patch, MagicMock import contrib.playerInspect as player_inspect class TestPlayerInspect(unittest.TestCase): def setUp(self): self.player_data = { 'AbsorptionAmount': 0.0, 'Air': 300, 'Attributes': [ {'Base': 20.0, 'Name': 'generic.maxHealth'}, {'Base': 0.0, 'Name': 'generic.knockbackResistance'}, {'Base': 0.10000000149011612, 'Name': 'generic.movementSpeed'}, {'Base': 0.0, 'Name': 'generic.armor'}, {'Base': 0.0, 'Name': 'generic.armorToughness'}, {'Base': 1.0, 'Name': 'generic.attackDamage'}, {'Base': 4.0, 'Name': 'generic.attackSpeed'}, {'Base': 0.0, 'Name': 'generic.luck'} ], 'DataVersion': 1631, 'DeathTime': 0, 'Dimension': 0, 'EnderItems': [], 'FallDistance': 0.0, 'FallFlying': 0, 'Fire': -20, 'Health': 20.0, 'HurtByTimestamp': 0, 'HurtTime': 0, 'Inventory': [{'Count': 1, 'Slot': -106, 'id': 'minecraft:sign'}], 'Invulnerable': 0, 'Motion': [0.0, -0.0784000015258789, 0.0], 'OnGround': 1, 'PortalCooldown': 0, 'Pos': [-96.11859857363737, 70.0, -44.17768261916891], 'Rotation': [-72.00011444091797, 38.250030517578125], 'Score': 0, 'SelectedItemSlot': 0, 'SleepTimer': 0, 'Sleeping': 0, "SpawnX": 10, "SpawnY": 52, "SpawnZ": 10, 'UUIDLeast': -7312926203658200544, 'UUIDMost': 6651100054519957107, 'XpLevel': 0, 'XpP': 0.0, 'XpSeed': 0, 'XpTotal': 0, 'abilities': { 'flySpeed': 0.05000000074505806, 'flying': 0, 'instabuild': 1, 'invulnerable': 1, 'mayBuild': 1, 'mayfly': 1, 'walkSpeed': 0.10000000149011612 }, 'foodExhaustionLevel': 0.0, 'foodLevel': 20, 'foodSaturationLevel': 5.0, 'foodTickTimer': 0, 'playerGameType': 1, 'recipeBook': { 'isFilteringCraftable': 0, 'isFurnaceFilteringCraftable': 0, 'isFurnaceGuiOpen': 0, 'isGuiOpen': 0, 'recipes': [], 'toBeDisplayed': [] }, 'seenCredits': 0 } @patch('sys.stdout', new_callable=StringIO) def test_print_player(self, mock_stdout): expected = "\n".join([ "Position:\t-96, 70, -44\t(dim: 0)", "Spawn:\t\t10, 52, 10", "Health:\t20\tLevel:\t\t0\t\tGameType:\t1", "Food:\t20\tTotal XP:\t0", "Inventory: 1 items", " 1 minecraft:sign\n"]) player_inspect.print_player(self.player_data) self.assertEqual(mock_stdout.getvalue(), expected) @patch('sys.stdout', new_callable=StringIO) def test_print_player_no_spawn(self, mock_stdout): expected = "\n".join([ "Position:\t-96, 70, -44\t(dim: 0)", "Health:\t20\tLevel:\t\t0\t\tGameType:\t1", "Food:\t20\tTotal XP:\t0", "Inventory: 1 items", " 1 minecraft:sign\n"]) player_data = { k: v for k, v in self.player_data.items() if k not in("SpawnX", "SpawnY", "SpawnZ") } player_inspect.print_player(player_data) self.assertEqual(mock_stdout.getvalue(), expected) @patch('sys.stdout', new_callable=StringIO) def test_print_player_sub_entry(self, mock_stdout): expected = "\n".join([ "\tPosition:\t-96, 70, -44\t(dim: 0)", "\tSpawn:\t\t10, 52, 10", "\tHealth:\t20\tLevel:\t\t0\t\tGameType:\t1", "\tFood:\t20\tTotal XP:\t0", "\tInventory: 1 items\n"]) player_inspect.print_player(self.player_data, sub_entry=True) self.assertEqual(mock_stdout.getvalue(), expected) @patch('sys.stdout', new_callable=StringIO) def test_print_player_sub_entry_no_spawn(self, mock_stdout): expected = "\n".join([ "\tPosition:\t-96, 70, -44\t(dim: 0)", "\tHealth:\t20\tLevel:\t\t0\t\tGameType:\t1", "\tFood:\t20\tTotal XP:\t0", "\tInventory: 1 items\n"]) player_data = { k: v for k, v in self.player_data.items() if k not in("SpawnX", "SpawnY", "SpawnZ") } player_inspect.print_player(player_data, sub_entry=True) self.assertEqual(mock_stdout.getvalue(), expected) def test_find_all_player_files(self): dir_path = MagicMock(Path) files = [Path('def0492d-0fe9-43ff-a3d5-8c3fc9160c94.dat'), Path('074c808a-1f04-4bdd-8385-bd74601210a1.dat'), Path('104e149d-a802-4a27-ac8f-ceab5279087c.dat')] dir_path.iterdir.return_value = (f for f in files) expected = [(Path('def0492d-0fe9-43ff-a3d5-8c3fc9160c94.dat'), 'def0492d-0fe9-43ff-a3d5-8c3fc9160c94'), (Path('074c808a-1f04-4bdd-8385-bd74601210a1.dat'), '074c808a-1f04-4bdd-8385-bd74601210a1'), (Path('104e149d-a802-4a27-ac8f-ceab5279087c.dat'), '104e149d-a802-4a27-ac8f-ceab5279087c')] result = player_inspect.find_all_player_files(dir_path) self.assertListEqual(list(result), expected) def test_find_player_file(self): dir_path = MagicMock(Path) files = [Path('def0492d-0fe9-43ff-a3d5-8c3fc9160c94.dat'), Path('074c808a-1f04-4bdd-8385-bd74601210a1.dat'), Path('104e149d-a802-4a27-ac8f-ceab5279087c.dat')] dir_path.iterdir.return_value = (f for f in files) expected = (Path('104e149d-a802-4a27-ac8f-ceab5279087c.dat'), '104e149d-a802-4a27-ac8f-ceab5279087c') result = player_inspect.find_player_file( dir_path, selected_player='104e149d-a802-4a27-ac8f-ceab5279087c') self.assertEqual(result, expected) def test_find_player_file_raises_when_selected_player_not_found(self): dir_path = MagicMock(Path) files = [Path('def0492d-0fe9-43ff-a3d5-8c3fc9160c94.dat'), Path('104e149d-a802-4a27-ac8f-ceab5279087c.dat')] dir_path.iterdir.return_value = (f for f in files) with self.assertRaises(FileNotFoundError): player_inspect.find_player_file(dir_path, selected_player='NON_EXISTENT_UUID')
6,849
Python
.py
155
32.058065
90
0.546231
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,267
test_world.py
overviewer_Minecraft-Overviewer/test/test_world.py
import unittest import os from overviewer_core import world class ExampleWorldTest(unittest.TestCase): @unittest.skip("Broken old garbage, find a newer world") def test_basic(self): "Basic test of the world constructor and regionset constructor" if not os.path.exists("test/data/worlds/exmaple"): raise unittest.SkipTest("test data doesn't exist. Maybe you need to init/update your submodule?") w = world.World("test/data/worlds/exmaple") regionsets = w.get_regionsets() self.assertEqual(len(regionsets), 3) regionset = regionsets[0] self.assertEqual(regionset.get_region_path(0,0), 'test/data/worlds/exmaple/DIM-1/region/r.0.0.mcr') self.assertEqual(regionset.get_region_path(-1,0), 'test/data/worlds/exmaple/DIM-1/region/r.-1.0.mcr') self.assertEqual(regionset.get_region_path(1,1), 'test/data/worlds/exmaple/DIM-1/region/r.0.0.mcr') self.assertEqual(regionset.get_region_path(35,35), None) # a few random chunks. reference timestamps fetched with libredstone self.assertEqual(regionset.get_chunk_mtime(0,0), 1316728885) self.assertEqual(regionset.get_chunk_mtime(-1,-1), 1316728886) self.assertEqual(regionset.get_chunk_mtime(5,0), 1316728905) self.assertEqual(regionset.get_chunk_mtime(-22,16), 1316786786) if __name__ == "__main__": unittest.main()
1,427
Python
.py
24
51.333333
110
0.704942
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,268
settings_test_1.py
overviewer_Minecraft-Overviewer/test/data/settings/settings_test_1.py
worlds['test'] = "test/data/settings/test_world" renders["myworld"] = { "title": "myworld title", "world": "test", "rendermode": normal, "northdirection": "upper-left", } renders["otherworld"] = { "title": "otherworld title", "world": "test", "rendermode": normal, "bgcolor": "#ffffff" } outputdir = "/tmp/fictional/outputdir"
363
Python
.py
14
22.357143
48
0.632948
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,269
settings_test_rendermode.py
overviewer_Minecraft-Overviewer/test/data/settings/settings_test_rendermode.py
worlds['test'] = "test/data/settings/test_world" renders["world"] = { "world": "test", "title": "myworld title", "rendermode": "bad_rendermode", "northdirection": "upper-left", } outputdir = "/tmp/fictional/outputdir"
238
Python
.py
8
26.25
48
0.653509
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,270
conf.py
overviewer_Minecraft-Overviewer/docs/conf.py
# -*- coding: utf-8 -*- # # Overviewer documentation build configuration file, created by # sphinx-quickstart on Thu Sep 22 10:19:03 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Overviewer' copyright = u'2010-2019 The Overviewer Team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "0.13" # The full version, including alpha/beta/rc tags. release = "0.13" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Overviewerdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Overviewer.tex', u'Overviewer Documentation', u'The Overviewer Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'overviewer', u'Overviewer Documentation', [u'The Overviewer Team'], 1) ]
7,041
Python
.py
158
43.107595
80
0.732161
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,271
png-it.py
overviewer_Minecraft-Overviewer/contrib/png-it.py
""" Outputs one huge PNG file using the tiles from an Overviewer map. """ from __future__ import print_function import sys from argparse import ArgumentParser from glob import glob from os.path import exists, join, split from PIL import Image def main(): parser = ArgumentParser() parser.add_argument('--memory-limit', '-m', metavar='SIZE', type=int, dest='memory_limit', required=True, help="Limit the amount of RAM to use in MiB. If it is " "expected that we'll exceed the limit, the script will abort.") parser.add_argument('--zoom-level', '-z', metavar='LEVEL', type=int, dest='zoom_level', required=True, help="Which zoom level to use from the Overviewer map. " "NOTE: the RAM usage will increase exponentially with the zoom level.") parser.add_argument('--crop', '-c', metavar='CROP', type=int, dest='crop', default=0, help="Crop a frame around the image, as a percentage of the original. " "For example in a image of 1000x2000 pixels, a 10%% crop will crop 100 " "pixels in the left and right sides and 200 pixels in the bottom and " "top sides. NOTE: this is not exact but will be rounded to the nearest " "Overviewer map tile.") parser.add_argument('--center', '-e', metavar='X,Y', dest='center', default=None, help="Mark what will be the center of the image, two comma separated " "percentage values.") parser.add_argument('--autocrop', '-a', dest='autocrop', default=False, action='store_true', help="Calculate the center and crop vales automatically to show all the " "tiles in the smallest possible image size. Unless you want a very " "specific image this option is recommended.") parser.add_argument('--output', '-o', type=str, dest='output', default="output.png", metavar='OUTPUT', help="Path for the resulting PNG. The image will be " "saved as a PNG file, no matter what extension you use.") parser.add_argument('tileset', metavar='TILESET') args = parser.parse_args() if args.autocrop and (args.center or args.crop): parser.error("You cannot specify --center or --crop with --autocrop.") # check for the output if args.output != '-': folder, filename = split(args.output) if folder != '' and not exists(folder): parser.error("The destination folder '{0}' doesn't exist.".format(folder)) # calculate stuff n = args.zoom_level length_in_tiles = 2**n tile_size = (384, 384) px_size = 4 # bytes # create a list with all the images in the zoom level path = args.tileset for i in range(args.zoom_level): path = join(path, "?") path += ".png" all_images = glob(path) if not all_images: print("Error! No images found in this zoom level. Is this really an Overviewer tile set " "directory?", file=sys.stderr) sys.exit(1) # autocrop will calculate the center and crop values automagically if args.autocrop: min_x = min_y = length_in_tiles max_x = max_y = 0 counter = 0 total = len(all_images) print("Checking tiles for autocrop calculations:", file=sys.stderr) # get the maximum and minimum tiles coordinates of the map for path in all_images: t = get_tuple_coords(args, path) c = get_tile_coords_from_tuple(args, t) min_x = min(min_x, c[0]) min_y = min(min_y, c[1]) max_x = max(max_x, c[0]) max_y = max(max_y, c[1]) counter += 1 if (counter % 100 == 0 or counter == total or counter == 1): print("Checked {0} of {1}.".format(counter, total), file=sys.stderr) # the center of the map will be in the middle of the occupied zone center = (int((min_x + max_x) / 2.0), int((min_y + max_y) / 2.0)) # see the next next comment to know what center_vector is center_vector = (int(center[0] - (length_in_tiles / 2.0 - 1)), int(center[1] - (length_in_tiles / 2.0 - 1))) # I'm not completely sure why, but the - 1 factor in ^ makes everything nicer. # min_x - center_vector[0] will be the unused amount of tiles in # the left and the right of the map (and this is true because we # are in the actual center of the map) crop = (min_x - center_vector[0], min_y - center_vector[1]) else: # center_vector is the vector that joins the center tile with # the new center tile in tile coords # tile coords are how many tile are on the left, x, and # how many above, y. The top-left tile has coords (0,0) if args.center: center_x, center_y = args.center.split(",") center_x = int(center_x) center_y = int(center_y) center_tile_x = int(2**n * (center_x / 100.0)) center_tile_y = int(2**n * (center_y / 100.0)) center_vector = (int(center_tile_x - length_in_tiles / 2.0), int(center_tile_y - length_in_tiles / 2.0)) else: center_vector = (0, 0) # crop if needed tiles_to_crop = int(2**n * (args.crop / 100.0)) crop = (tiles_to_crop, tiles_to_crop) final_img_size = (tile_size[0] * length_in_tiles, tile_size[1] * length_in_tiles) final_cropped_img_size = (final_img_size[0] - 2 * crop[0] * tile_size[0], final_img_size[1] - 2 * crop[1] * tile_size[1]) mem = final_cropped_img_size[0] * final_cropped_img_size[1] * px_size # bytes! print("The image size will be {0}x{1}." .format(final_cropped_img_size[0], final_cropped_img_size[1]), file=sys.stderr) print("A total of {0} MB of memory will be used.".format(mem / 1024**2), file=sys.stderr) if mem / 1024.0**2.0 > args.memory_limit: print("Error! The expected RAM usage exceeds the specified limit. Exiting.", file=sys.stderr) sys.exit(1) # Create a new huge image final_img = Image.new("RGBA", final_cropped_img_size, (26, 26, 26, 0)) # Paste ALL the images total = len(all_images) counter = 0 print("Pasting images:", file=sys.stderr) for path in all_images: img = Image.open(path) t = get_tuple_coords(args, path) x, y = get_cropped_centered_img_coords(args, tile_size, center_vector, crop, t) final_img.paste(img, (x, y)) counter += 1 if (counter % 100 == 0 or counter == total or counter == 1): print("Pasted {0} of {1}.".format(counter, total), file=sys.stderr) print("Done!", file=sys.stderr) print("Saving image... (this may take a while)", file=sys.stderr) final_img.save(args.output if args.output != '-' else sys.stdout, "PNG") def get_cropped_centered_img_coords(options, tile_size, center_vector, crop, t): """ Returns the new image coords used to paste tiles in the big image. Takes options, the size of tiles, center vector, crop value (see calculate stuff) and a tuple from get_tuple_coords. """ x, y = get_tile_coords_from_tuple(options, t) new_tile_x = x - crop[0] - center_vector[0] new_tile_y = y - crop[1] - center_vector[1] new_img_x = new_tile_x * tile_size[0] new_img_y = new_tile_y * tile_size[1] return new_img_x, new_img_y def get_tile_coords_from_tuple(options, t): """ Gets a tuple of coords from get_tuple_coords and returns the number of tiles from the top left corner to this tile. The top-left tile has coordinates (0,0) """ x = 0 y = 0 z = options.zoom_level n = 1 for i in t: if i == 1: x += 2**(z - n) elif i == 2: y += 2**(z - n) elif i == 3: x += 2**(z - n) y += 2**(z - n) n += 1 return (x, y) def get_tuple_coords(options, path): """ Extracts the "quadtree coordinates" (the numbers in the folder of the tile sets) from an image path. Returns a tuple with them. The upper most folder is in the left of the tuple.""" l = [] path, head = split(path) head = head.split(".")[0] # remove the .png l.append(int(head)) for i in range(options.zoom_level - 1): path, head = split(path) l.append(int(head)) # the list is reversed l.reverse() return tuple(l) def get_image(tileset, t): """ Returns the path of an image, takes a tuple with the "quadtree coordinates", these are the numbers in the folders of the tile set. """ path = tileset for d in t: path = join(path, str(d)) path += ".png" return path if __name__ == '__main__': main()
9,008
Python
.py
184
39.847826
97
0.592833
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,272
cyrillic_convert.py
overviewer_Minecraft-Overviewer/contrib/cyrillic_convert.py
#!/usr/bin/env python3 """Convert gibberish back into Cyrillic""" import fileinput import argparse import sys gibberish_to_cyrillic = { 'À': 'А', 'Á': 'Б', 'Â': 'В', 'Ã': 'Г', 'Ä': 'Д', 'Å': 'Е', 'Æ': 'Ж', 'Ç': 'З', 'È': 'И', 'É': 'Й', 'Ê': 'К', 'Ë': 'Л', 'Ì': 'М', 'Í': 'Н', 'Î': 'О', 'Ï': 'П', 'Ð': 'Р', 'Ñ': 'С', 'Ò': 'Т', 'Ó': 'У', 'Ô': 'Ф', 'Õ': 'Х', 'Ö': 'Ц', '×': 'Ч', 'Ø': 'Ш', 'Ù': 'Щ', 'Ú': 'Ъ', 'Û': 'Ы', 'Ü': 'Ь', 'Ý': 'Э', 'Þ': 'Ю', 'ß': 'Я', 'à': 'а', 'á': 'б', 'â': 'в', 'ã': 'г', 'ä': 'д', 'å': 'е', 'æ': 'ж', 'ç': 'з', 'è': 'и', 'é': 'й', 'ê': 'к', 'ë': 'л', 'ì': 'м', 'í': 'н', 'î': 'о', 'ï': 'п', 'ð': 'р', 'ñ': 'с', 'ò': 'т', 'ó': 'у', 'ô': 'ф', 'õ': 'х', 'ö': 'ц', '÷': 'ч', 'ø': 'ш', 'ù': 'щ', 'ú': 'ъ', 'û': 'ы', 'ü': 'ь', 'ý': 'э', 'þ': 'ю', 'ÿ': 'я' } trans_table = {ord(k): v for k, v in gibberish_to_cyrillic.items()} def convert(s): return s.translate(trans_table) if __name__ == '__main__': description = """ If you have signs that should be Cyrillic, but are instead gibberish, this script will convert it back to proper Cyrillic. """ parser = argparse.ArgumentParser(description=description) parser.add_argument('file', metavar='markers.js') args = parser.parse_args() convert(args.markers_file) for line in fileinput.input(files=markers_file, inplace=1): print(convert(s), end='')
1,753
Python
.py
85
14.447059
73
0.407963
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,273
regionTrimmer.py
overviewer_Minecraft-Overviewer/contrib/regionTrimmer.py
#!/usr/bin/env python3 """Deletes outlying and unconnected regions""" import argparse import logging from pathlib import Path import networkx logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def get_region_file_from_node(regionset_path, node): return regionset_path / ('r.%d.%d.mca' % node) def get_nodes(regionset_path): return [ tuple(int(x) for x in r.stem.split('.')[1:3]) for r in regionset_path.glob('r.*.*.mca') ] def generate_edges(graph): offsets = (-1, 1) nodes = graph.nodes() for node in nodes: for offset in offsets: graph.add_edges_from( (node, offset_node) for offset_node in [ (node[0] + offset, node[1]), (node[0], node[1] + offset), (node[0] + offset, node[1] + offset), ] if offset_node in nodes ) return graph def generate_subgraphs(nodes): graph = networkx.Graph() graph.add_nodes_from(nodes) generate_edges(graph) return graph, [graph.subgraph(c) for c in networkx.connected_components(graph)] def get_graph_bounds(graph): nodes = graph.nodes() return ( max(n[0] for n in nodes), min(n[0] for n in nodes), max(n[1] for n in nodes), min(n[1] for n in nodes), ) def get_graph_center_by_bounds(bounds): dx = bounds[0] - bounds[1] dy = bounds[2] - bounds[3] return (dx // 2 + bounds[1], dy // 2 + bounds[3]) def trim_regions(graph, regions_path, dry_run=True, filter_func=lambda n: True): regions = [ (n, get_region_file_from_node(regions_path, n)) for n in graph.nodes() if filter_func(n) ] logger.info("Trimming regions: %s", ", ".join(x[1] for x in regions)) for n, region_file in regions: graph.remove_node(n) if dry_run is False: unlink_file(region_file) def is_outside_main(center, main_section_bounds): return center[0] <= main_section_bounds[0] and center[0] >= main_section_bounds[1] and \ center[1] <= main_section_bounds[2] and center[1] >= main_section_bounds[3] def is_outside_bounds(node, trim_center, trim_bounds): return node[0] >= trim_center[0] + trim_bounds[0] or \ node[0] <= trim_center[0] - trim_bounds[0] or \ node[1] >= trim_center[1] + trim_bounds[1] or \ node[1] <= trim_center[1] - trim_bounds[1] def unlink_file(path): try: path.unlink() except OSError as err: logger.warning("Unable to delete file: %s", path) logger.warning("Error recieved was: %s", err) def main(args): for path in args.paths: logger.info("Using regionset path: %s", path) nodes = get_nodes(path) if not len(nodes): logger.error("Found no nodes, are you sure there are .mca files in %s ?", path) return logger.info("Found %d nodes", len(nodes)) logger.info("Generating graphing nodes...") graph, subgraphs = generate_subgraphs(nodes) assert len(graph.nodes()) == sum(len(sg.nodes()) for sg in subgraphs) if len(subgraphs) == 1: logger.warning("All regions are contiguous, the needful is done!") return logger.info("Found %d discrete region sections", len(subgraphs)) subgraphs = sorted(subgraphs, key=lambda sg: len(sg), reverse=True) for i, sg in enumerate(subgraphs): logger.info("Region section #%02d: %04d nodes", i + 1, len(sg.nodes())) bounds = get_graph_bounds(sg) logger.info("Bounds: %d <-> %d x %d <-> %d", *get_graph_bounds(sg)) center = get_graph_center_by_bounds(bounds) logger.info("Center: %d x %d", *center) main_section = subgraphs[0] main_section_bounds = get_graph_bounds(main_section) main_section_center = get_graph_center_by_bounds(main_section_bounds) logger.info("Using %d node graph as main section,", len(main_section.nodes())) satellite_sections = subgraphs[1:] for ss in satellite_sections: bounds = get_graph_bounds(ss) center = get_graph_center_by_bounds(bounds) logger.info(("Checking satellite section with %d nodes, " "%d <-> %d x %d <-> %d bounds and %d x %d center"), len(ss.nodes()), *(bounds + center)) if args.trim_disconnected: trim_regions(ss, path, dry_run=args.dry_run) if args.trim_outside_main: if is_outside_main(ss, center, main_section_bounds): logger.info("Section is outside main section bounds") trim_regions(ss, path, dry_run=args.dry_run) else: logger.info("Section falls inside main section bounds, ignoring") if args.trim_outside_bounds: logger.info("Checking regions outside specified bounds") trim_center = args.trim_outside_bounds.get("center", main_section_center) trim_bounds = args.trim_outside_bounds["bounds"] trim_regions(ss, path, dry_run=args.dry_run, filter_func=lambda n: is_outside_bounds(n, trim_center, trim_bounds)) def dir_path(path): p = Path(path) if not p.is_dir(): raise argparse.ArgumentTypeError("Not a valid directory path") return p def center_bound(value): x = [int(v) for v in value.split(",")] if len(x) == 4: return {"center": x[:2], "bounds": x[2:]} elif len(x) == 2: return {"bounds": x} else: raise argparse.ArgumentTypeError("Invalid center/bound value") if __name__ == "__main__": logging.basicConfig() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("paths", metavar="<path/to/region/directory>", nargs="+", type=dir_path) parser.add_argument("-D", "--trim-disconnected", action="store_true", default=False, help="Trim all disconnected regions") parser.add_argument("-M", "--trim-outside-main", action="store_true", default=False, help="Trim disconnected regions outside main section bounds") parser.add_argument("-B", "--trim-outside-bounds", metavar="[center_X,center_Y,]bound_X,bound_Y", type=center_bound, help=("Trim outside given bounds " "(given as [center_X,center_Y,]bound_X,bound_Y)")) parser.add_argument("-n", "--dry-run", action="store_true", default=False, help="Don't actually delete anything") args = parser.parse_args() main(args)
6,788
Python
.py
149
35.90604
100
0.593064
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,274
contributors.py
overviewer_Minecraft-Overviewer/contrib/contributors.py
#!/usr/bin/env python3 """Update the contributor list Alias handling is done by git with .mailmap New contributors are merged in the short-term list. Moving them to a "higher" list should be a manual process. """ import re from pathlib import Path import subprocess CONTRIB_FILE_CONTRIBUTOR_RE = re.compile(r'\* (.+) (<.+>)') def format_contributor(contributor): return " * {0} {1}".format(contributor["name"], contributor["email"]) def get_contributors(): """ Parse all contributors from output of git shortlog -se """ contributors = [] p_git = subprocess.run(["git", "shortlog", "-se"], stdout=subprocess.PIPE) for line in p_git.stdout.decode('utf-8').split('\n'): m = re.search(r"(\d+)\t(.+) (<.+>)", line) if m: contributors.append({ "count": int(m.group(1)), "name": m.group(2), "email": m.group(3) }) return contributors def get_old_contributors(contrib_file_lines): """ Parse existing contributors from CONTRIBUTORS.rst Returns: (list) Contributors as {"name", "email"} dicts """ old_contributors = [] for line in contrib_file_lines: m = CONTRIB_FILE_CONTRIBUTOR_RE.search(line) if m: old_contributors.append({"name": m.group(1), "email": m.group(2)}) return old_contributors def get_new_contributors(contributors, old_contributors): """ Find new contributors and any possible alias or email changes Returns: (tuple) list of new contributors, list of new aliases as (contributor, existing_name), list of new emails as (contributor, existing_email) """ old_email_names = {c['email']: c['name'] for c in old_contributors} old_name_emails = {c['name']: c['email'] for c in old_contributors} new_contributors = [] new_alias = [] new_email = [] for contributor in contributors: name, email = contributor['name'], contributor['email'] existing_name, existing_email = old_email_names.get(email), old_name_emails.get(name) if existing_name == name and existing_email == email: # exact combination already in list pass elif existing_name is None and existing_email is None: new_contributors.append(contributor) elif existing_name is not None: new_alias.append((contributor, existing_name)) elif existing_email is not None: new_email.append((contributor, existing_email)) return ( sorted(new_contributors, key=lambda x: x['name'].split()[-1].lower()), new_alias, new_email ) def merge_short_term_contributors(contrib_file_lines, new_contributors): """ Merge new contributors into Short-term Contributions section in alphabetical order. Returns: (list) Lines including new contributors for writing to CONTRIBUTORS.rst """ short_term_found = False for (i, line) in enumerate(contrib_file_lines): if not short_term_found: if "Short-term" in line: short_term_found = True else: if CONTRIB_FILE_CONTRIBUTOR_RE.search(line): break short_term_contributor_lines = [l for l in contrib_file_lines[i:] if l] + \ [format_contributor(c) + "\n" for c in new_contributors] def last_name_sort(contrib_line): m = CONTRIB_FILE_CONTRIBUTOR_RE.search(contrib_line) return m.group(1).split()[-1].lower() return contrib_file_lines[:i] + sorted(short_term_contributor_lines, key=last_name_sort) def main(): contrib_file = Path("CONTRIBUTORS.rst") with contrib_file.open() as f: contrib_file_lines = f.readlines() old_contributors = get_old_contributors(contrib_file_lines) contributors = get_contributors() new_contributors, new_alias, new_email = get_new_contributors(contributors, old_contributors) for contributor, old_name in new_alias: print("new alias {0} for {1} {2} ?".format( contributor['name'], old_name, contributor['email'])) for contributor, old_email in new_email: print("new email {0} for {1} {2} ?".format( contributor['email'], contributor['name'], old_email)) if new_alias or new_email: print("Please update .mailmap") if new_contributors: print("inserting:") print("\n".join([format_contributor(c) for c in new_contributors])) with contrib_file.open("w") as f: f.writelines(merge_short_term_contributors(contrib_file_lines, new_contributors)) if __name__ == "__main__": main()
4,658
Python
.py
108
35.768519
97
0.643284
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,275
playerInspect.py
overviewer_Minecraft-Overviewer/contrib/playerInspect.py
#!/usr/bin/env python3 """ Very basic player.dat inspection script """ import os import sys import argparse from pathlib import Path # incantation to be able to import overviewer_core if not hasattr(sys, "frozen"): sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], '..'))) from overviewer_core.nbt import load from overviewer_core import items def print_player(data, sub_entry=False): indent = "" if sub_entry: indent = "\t" print("%sPosition:\t%i, %i, %i\t(dim: %i)" % (indent, data['Pos'][0], data['Pos'][1], data['Pos'][2], data['Dimension'])) try: print("%sSpawn:\t\t%i, %i, %i" % (indent, data['SpawnX'], data['SpawnY'], data['SpawnZ'])) except KeyError: pass print("%sHealth:\t%i\tLevel:\t\t%i\t\tGameType:\t%i" % (indent, data['Health'], data['XpLevel'], data['playerGameType'])) print("%sFood:\t%i\tTotal XP:\t%i" % (indent, data['foodLevel'], data['XpTotal'])) print("%sInventory: %d items" % (indent, len(data['Inventory']))) if not sub_entry: for item in data['Inventory']: print(" %-3d %s" % (item['Count'], items.id2item(item['id']))) def find_all_player_files(dir_path): for player_file in dir_path.iterdir(): player = player_file.stem yield player_file, player def find_player_file(dir_path, selected_player): for player_file, player in find_all_player_files(dir_path): if selected_player == player: return player_file, player raise FileNotFoundError() def load_and_output_player(player_file_path, player, sub_entry=False): with player_file_path.open('rb') as f: player_data = load(f)[1] print("") print(player) print_player(player_data, sub_entry=sub_entry) def dir_or_file(path): p = Path(path) if not p.is_file() and not p.is_dir(): raise argparse.ArgumentTypeError("Not a valid file or directory path") return p def main(path, selected_player=None): print("Inspecting %s" % args.path) if not path.is_dir(): load_and_output_player(args.path) return if selected_player is None: for player_file, player in find_all_player_files(args.path): load_and_output_player(player_file, player) return try: player_file, player = find_player_file(args.path, args.selected_player) load_and_output_player(player_file, player, sub_entry=True) except FileNotFoundError: print("No %s.dat in %s" % (args.selected_player, args.path)) sys.exit(1) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('path', metavar='<Player.dat or directory>', type=dir_or_file) parser.add_argument('selected_player', nargs='?', default=None) args = parser.parse_args() main(args.path, selected_player=args.selected_player)
2,936
Python
.py
73
34.328767
88
0.646728
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,276
gallery.py
overviewer_Minecraft-Overviewer/contrib/gallery.py
#!/usr/bin/env python3 """ Outputs a huge image with all currently-supported block textures. """ import argparse from PIL import Image import sys import os # incantation to be able to import overviewer_core if not hasattr(sys, "frozen"): sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], '..'))) def main(outfile): from overviewer_core import textures t = textures.Textures() t.generate() blocks = {} for blockid in range(textures.max_blockid): for data in range(textures.max_data): tex = t.blockmap[blockid * textures.max_data + data] if tex: if blockid not in blocks: blocks[blockid] = {} blocks[blockid][data] = tex columns = max(len(v) for v in blocks.values()) rows = len(blocks) texsize = t.texture_size gallery = Image.new("RGBA", (columns * texsize, rows * texsize), t.bgcolor) for row, (blockid, textures) in enumerate(blocks.items()): for column, (data, tex) in enumerate(textures.items()): gallery.paste(tex[0], (column * texsize, row * texsize)) gallery.save(outfile) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('file', metavar='output.png') args = parser.parse_args() main(args.file)
1,361
Python
.py
36
31.777778
87
0.647104
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,277
testRender.py
overviewer_Minecraft-Overviewer/contrib/testRender.py
#!/usr/bin/env python3 "Test Render Script" import argparse import math import os import re import shutil import sys import tempfile import time from shlex import split from subprocess import PIPE, STDOUT, CalledProcessError, run overviewer_scripts = ['./overviewer.py', './gmap.py'] def check_call(args, verbose=False): try: return run( args, check=True, stdout=None if verbose else PIPE, stderr=None if verbose else STDOUT, universal_newlines=True, ) except CalledProcessError as e: if verbose: print(e.output) raise e def check_output(args): p = run( args, check=True, stdout=PIPE, universal_newlines=True ) return p.stdout def clean_render(overviewerargs, verbose=False): tempdir = tempfile.mkdtemp('mc-overviewer-test') overviewer_script = None for script in overviewer_scripts: if os.path.exists(script): overviewer_script = script break if overviewer_script is None: sys.stderr.write("could not find main overviewer script\n") sys.exit(1) try: # check_call raises CalledProcessError when overviewer.py exits badly check_call([sys.executable] + split("setup.py clean build"), verbose=verbose) try: check_call([sys.executable, overviewer_script, '-d'] + overviewerargs, verbose=verbose) except CalledProcessError: pass starttime = time.time() check_call([sys.executable, overviewer_script] + overviewerargs + [tempdir, ], verbose=verbose) endtime = time.time() return endtime - starttime finally: shutil.rmtree(tempdir, True) def get_stats(timelist): average = sum(timelist) / float(len(timelist)) meandiff = [(x - average) ** 2 for x in timelist] sd = math.sqrt(sum(meandiff) / len(meandiff)) return { "count": len(timelist), "minimum": min(timelist), "maximum": max(timelist), "average": average, "standard deviation": sd } def get_current_branch(): gittext = check_output(split('git rev-parse --abbrev-ref HEAD')) return gittext.strip() if gittext != "HEAD" else None def get_current_commit(): gittext = check_output(split('git rev-parse HEAD')) return gittext.strip() if gittext else None def get_current_ref(): branch = get_current_branch() if branch: return branch commit = get_current_commit() if commit: return commit def get_commits(gitrange): gittext = check_output(split('git rev-list --reverse') + [gitrange, ]) return (c for c in gittext.split("\n")) def set_commit(commit): check_call(split('git checkout') + [commit, ]) def main(args): commits = [] for commit in args.commits: if '..' in commit: commits = get_commits(commit) else: commits.append(commit) if not commits: commits = [get_current_ref(), ] log = None if args.log: log = args.log reset_commit = get_current_ref() try: for commit in commits: print("testing commit", commit) set_commit(commit) timelist = [] print(" -- "), try: for i in range(args.number): sys.stdout.write(str(i + 1) + " ") sys.stdout.flush() timelist.append(clean_render(args.overviewer_args, verbose=args.verbose)) print("... done") stats = get_stats(timelist) print(stats) if log: log.write("%s %s\n" % (commit, repr(stats))) except CalledProcessError as e: if args.fatal_errors: print(e) print("Overviewer croaked, exiting...") print("(to avoid this, use --keep-going)") sys.exit(1) finally: set_commit(reset_commit) if log: log.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("overviewer_args", metavar="[overviewer options/world]", nargs="+") parser.add_argument("-n", "--option", metavar="N", type=int, action="store", dest="number", default=3, help="number of renders per commit [default: 3]") parser.add_argument("-c", "--commits", metavar="RANGE", action="append", type=str, dest="commits", default=[], help="the commit (or range of commits) to test [default: current]") parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="don't suppress overviewer output") parser.add_argument("-k", "--keep-going", action="store_false", dest="fatal_errors", default=True, help="don't stop testing when Overviewer croaks") parser.add_argument("-l", "--log", dest="log", type=argparse.FileType('w'), metavar="FILE", help="log all test results to a file") args = parser.parse_args() main(args)
5,290
Python
.py
143
27.951049
99
0.589914
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,278
signals.py
overviewer_Minecraft-Overviewer/overviewer_core/signals.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. """ This module provides a way to create named "signals" that, when emitted, call a set of registered functions. These signals also have the ability to be intercepted, which lets Dispatchers re-route signals back to the main process. """ class Signal(object): """A mechanism for registering functions to be called whenever some specified event happens. This object is designed to work with Dispatcher so that functions can register to always run in the main Python instance.""" # a global list of registered signals, indexed by name # this is used by JobManagers to register and relay signals signals = {} def __init__(self, namespace, name): """Creates a signal. Namespace and name should be the name of the class this signal is for, and the name of the signal. They are used to create a globally-unique name.""" self.namespace = namespace self.name = name self.fullname = namespace + '.' + name self.interceptor = None self.local_functions = [] self.functions = [] # register this signal self.signals[self.fullname] = self def register(self, func): """Register a function to be called when this signal is emitted. Functions registered in this way will always run in the main Python instance.""" self.functions.append(func) return func def register_local(self, func): """Register a function to be called when this signal is emitted. Functions registered in this way will always run in the Python instance in which they were emitted.""" self.local_functions.append(func) return func def set_interceptor(self, func): """Sets an interceptor function. This function is called instead of all the non-locally registered functions if it is present, and should be used by JobManagers to intercept signal emissions.""" self.interceptor = func def emit(self, *args, **kwargs): """Emits the signal with the given arguments. For convenience, you can also call the signal object directly. """ for func in self.local_functions: func(*args, **kwargs) if self.interceptor: self.interceptor(*args, **kwargs) return for func in self.functions: func(*args, **kwargs) def emit_intercepted(self, *args, **kwargs): """Re-emits an intercepted signal, and finishes the work that would have been done during the original emission. This should be used by Dispatchers to re-emit signals intercepted in worker Python instances.""" for func in self.functions: func(*args, **kwargs) # convenience def __call__(self, *args, **kwargs): self.emit(*args, **kwargs) # force pickled signals to redirect to existing signals def __getstate__(self): return self.fullname def __setstate__(self, fullname): for attr in dir(self.signals[fullname]): if attr.startswith('_'): continue setattr(self, attr, getattr(self.signals[fullname], attr))
3,944
Python
.py
87
38.505747
78
0.678032
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,279
config_parser.py
overviewer_Minecraft-Overviewer/overviewer_core/config_parser.py
import sys import os.path import logging import traceback from . import settingsDefinition from . import settingsValidators class MissingConfigException(Exception): """"To be thrown when the config file can't be found""" class MultiWorldParser: """A class that is used to parse a settings.py file. This class's job is to compile and validate the configuration settings for a set of renders. It can read in configuration from the given file with the parse() method, and one can set configuration options directly with the set_config_item() method. get_validated_config() validates and returns the validated config """ def __init__(self): """Initialize this parser object""" # This maps config names to their values self._config_state = {} # Scan the settings definition and build the config state heirarchy. # Also go ahead and set default values for non-required settings. # This maps setting names to their values as given in # settingsDefinition.py self._settings = {} default_conf = settingsDefinition.get_default_config() for settingname in default_conf: setting = default_conf[settingname] if not isinstance(setting, settingsValidators.Setting): continue self._settings[settingname] = setting # Set top level defaults. This is intended to be for container # types, so they can initialize a config file with an empty # container (like a dict) if setting.required and setting.default is not None: self._config_state[settingname] = setting.default def set_config_item(self, itemname, itemvalue): self._config_state[itemname] = itemvalue def set_renders_default(self, settingname, newdefault): """This method sets the default for one of the settings of the "renders" dictionary. This is hard-coded to expect a "renders" setting in the settings definition, and for its validator to be a dictValidator with its valuevalidator to be a configDictValidator """ # If the structure of settingsDefinitions changes, you'll need to change # this to find the proper place to find the settings dictionary render_settings = self._settings['renders'].validator.valuevalidator.config render_settings[settingname].default = newdefault def parse(self, settings_file): """Reads in the named file and parses it, storing the results in an internal state awating to be validated and returned upon call to get_render_settings() Attributes defined in the file that do not match any setting are then matched against the renderdict setting, and if it does match, is used as the default for that setting. """ if not os.path.exists(settings_file) and not os.path.isfile(settings_file): raise MissingConfigException( "The settings file you specified (%r) does not exist, or is not a file." % settings_file) # The global environment should be the rendermode module, so the config # file has access to those resources. from . import rendermodes try: with open(settings_file, "rb") as settings_file_handle: exec(compile(settings_file_handle.read(), settings_file, 'exec'), rendermodes.__dict__, self._config_state) except Exception as ex: if isinstance(ex, SyntaxError): logging.error("Syntax error parsing '%s'.", settings_file) logging.error("The traceback below will tell you which line triggered the " "syntax error.\n") elif isinstance(ex, NameError): logging.error("NameError parsing '%s'.", settings_file) logging.error("The traceback below will tell you which line referenced the " "non-existent variable.\n") else: logging.error("Error parsing '%s'.", settings_file) logging.error("The traceback below will tell you which line triggered the error.\n") # skip the execfile part of the traceback exc_type, exc_value, exc_traceback = sys.exc_info() formatted_lines = traceback.format_exc().splitlines() print_rest = False lines = [] for l in formatted_lines: if print_rest: lines.append(l) else: if "execfile" in l: print_rest = True # on windows, our traceback as no 'execfile'. in this case, print everything if print_rest: logging.error("Partial traceback:\n" + "\n".join(lines)) else: logging.error("Partial traceback:\n" + "\n".join(formatted_lines)) sys.exit(1) # At this point, make a pass through the file to possibly set global # render defaults render_settings = self._settings['renders'].validator.valuevalidator.config for key in self._config_state.keys(): if key not in self._settings: if key in render_settings: setting = render_settings[key] setting.default = self._config_state[key] def get_validated_config(self): """Validate and return the configuration. Raises a ValidationException if there was a problem validating the config. Could also raise a ValueError """ # Okay, this is okay, isn't it? We're going to create the validation # routine right here, right now. I hope this works! validator = settingsValidators.make_configDictValidator(self._settings, ignore_undefined=True) # Woah. What just happened? No. WAIT, WHAT ARE YOU... validated_config = validator(self._config_state) # WHAT HAVE YOU DONE? return validated_config # WHAT HAVE YOU DOOOOOOOOOOONE????
6,209
Python
.py
118
41.025424
100
0.632377
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,280
util.py
overviewer_Minecraft-Overviewer/overviewer_core/util.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. """ Misc utility routines used by multiple files that don't belong anywhere else """ import errno import imp import os.path import platform import sys from itertools import cycle, islice, product from string import hexdigits from subprocess import PIPE, Popen def get_program_path(): if hasattr(sys, "frozen") or imp.is_frozen("__main__"): return os.path.dirname(sys.executable) else: try: # normally, we're in ./overviewer_core/util.py # we want ./ return os.path.dirname(os.path.dirname(__file__)) except NameError: return os.path.dirname(sys.argv[0]) def findGitHash(): try: p = Popen('git rev-parse HEAD', stdout=PIPE, stderr=PIPE, shell=True) p.stderr.close() line = p.stdout.readlines()[0].decode('utf-8').strip() if line and len(line) == 40 and all(c in hexdigits for c in line): return line except Exception: try: from . import overviewer_version return overviewer_version.HASH except Exception: pass return "unknown" def findGitVersion(): try: p = Popen('git describe --tags --match "v*.*.*"', stdout=PIPE, stderr=PIPE, shell=True) p.stderr.close() line = p.stdout.readlines()[0].decode('utf-8') if line.startswith('release-'): line = line.split('-', 1)[1] if line.startswith('v'): line = line[1:] # turn 0.1.0-50-somehash into 0.1.50 # and 0.1.0 into 0.1.0 line = line.strip().replace('-', '.').split('.') if len(line) == 5: del line[4] del line[2] else: assert len(line) == 3 line[2] = '0' line = '.'.join(line) return line except Exception: try: from . import overviewer_version return overviewer_version.VERSION except Exception: return "unknown" def is_bare_console(): """Returns true if Overviewer is running in a bare console in Windows, that is, if overviewer wasn't started in a cmd.exe session. """ if platform.system() == 'Windows': try: import ctypes GetConsoleProcessList = ctypes.windll.kernel32.GetConsoleProcessList num = GetConsoleProcessList(ctypes.byref(ctypes.c_int(0)), ctypes.c_int(1)) if (num == 1): return True except Exception: pass return False def nice_exit(ret=0): """Drop-in replacement for sys.exit that will automatically detect bare consoles and wait for user input before closing. """ if ret and is_bare_console(): print("") print("Press [Enter] to close this window.") input() sys.exit(ret) # http://docs.python.org/library/itertools.html def roundrobin(iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).__next__ for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) def dict_subset(d, keys): "Return a new dictionary that is built from copying select keys from d" n = dict() for key in keys: if key in d: n[key] = d[key] return n def pid_exists(pid): # http://stackoverflow.com/a/6940314/1318435 """Check whether pid exists in the current process table.""" if pid < 0: return False try: os.kill(pid, 0) except OSError as e: return e.errno != errno.ESRCH else: return True
4,510
Python
.py
129
27.984496
95
0.621733
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,281
world.py
overviewer_Minecraft-Overviewer/overviewer_core/world.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import functools import os import os.path import logging import time import random import re import locale import numpy import math from . import nbt from . import cache from .biome import reshape_biome_data """ This module has routines for extracting information about available worlds """ class ChunkDoesntExist(Exception): pass class UnsupportedVersion(Exception): pass def log_other_exceptions(func): """A decorator that prints out any errors that are not ChunkDoesntExist errors. This should decorate any functions or methods called by the C code, such as get_chunk(), because the C code is likely to swallow exceptions. This will at least make them visible. """ functools.wraps(func) def newfunc(*args): try: return func(*args) except ChunkDoesntExist: raise except Exception as e: logging.exception("%s raised this exception", func.func_name) raise return newfunc class World(object): """Encapsulates the concept of a Minecraft "world". A Minecraft world is a level.dat file, a players directory with info about each player, a data directory with info about that world's maps, and one or more "dimension" directories containing a set of region files with the actual world data. This class deals with reading all the metadata about the world. Reading the actual world data for each dimension from the region files is handled by a RegionSet object. Note that vanilla Minecraft servers and single player games have a single world with multiple dimensions: one for the overworld, the nether, etc. On Bukkit enabled servers, to support "multiworld," the server creates multiple Worlds, each with a single dimension. In this file, the World objects act as an interface for RegionSet objects. The RegionSet objects are what's really important and are used for reading block data for rendering. A RegionSet object will always correspond to a set of region files, or what is colloquially referred to as a "world," or more accurately as a dimension. The only thing this class actually stores is a list of RegionSet objects and the parsed level.dat data """ def __init__(self, worlddir): self.worlddir = worlddir # This list, populated below, will hold RegionSet files that are in # this world self.regionsets = [] # The level.dat file defines a minecraft world, so assert that this # object corresponds to a world on disk if not os.path.exists(os.path.join(self.worlddir, "level.dat")): raise ValueError("level.dat not found in %s" % self.worlddir) data = nbt.load(os.path.join(self.worlddir, "level.dat"))[1]['Data'] # it seems that reading a level.dat file is unstable, particularly with respect # to the spawnX,Y,Z variables. So we'll try a few times to get a good reading # empirically, it seems that 0,50,0 is a "bad" reading # update: 0,50,0 is the default spawn, and may be valid is some cases # more info is needed data = nbt.load(os.path.join(self.worlddir, "level.dat"))[1]['Data'] # Hard-code this to only work with format version 19133, "Anvil" if not ('version' in data and data['version'] == 19133): if 'version' in data and data['version'] == 0: logging.debug("Note: Allowing a version of zero in level.dat!") ## XXX temporary fix for #1194 else: raise UnsupportedVersion( ("Sorry, This version of Minecraft-Overviewer only works " "with the 'Anvil' chunk format\n" "World at %s is not compatible with Overviewer") % self.worlddir) # This isn't much data, around 15 keys and values for vanilla worlds. self.leveldat = data # Scan worlddir to try to identify all region sets. Since different # server mods like to arrange regions differently and there does not # seem to be any set standard on what dimensions are in each world, # just scan the directory heirarchy to find a directory with .mca # files. for root, dirs, files in os.walk(self.worlddir, followlinks=True): # any .mcr files in this directory? mcas = [x for x in files if x.endswith(".mca")] if mcas: # construct a regionset object for this rel = os.path.relpath(root, self.worlddir) if os.path.basename(rel) != "poi": rset = RegionSet(root, rel) if root == os.path.join(self.worlddir, "region"): self.regionsets.insert(0, rset) else: self.regionsets.append(rset) # TODO move a lot of the following code into the RegionSet try: # level.dat should have the LevelName attribute so we'll use that self.name = data['LevelName'] except KeyError: # but very old ones might not? so we'll just go with the world dir name if they don't self.name = os.path.basename(os.path.realpath(self.worlddir)) try: # level.dat also has a RandomSeed attribute self.seed = data['RandomSeed'] except KeyError: self.seed = 0 # oh well # TODO figure out where to handle regionlists def get_regionsets(self): return self.regionsets def get_regionset(self, index): if type(index) == int: return self.regionsets[index] else: # assume a get_type() value candids = [x for x in self.regionsets if x.get_type() == index] logging.debug("You asked for %r, and I found the following candids: %r", index, candids) if len(candids) > 0: return candids[0] else: return None def get_level_dat_data(self): # Return a copy return dict(self.data) def find_true_spawn(self): """Returns the spawn point for this world. Since there is one spawn point for a world across all dimensions (RegionSets), this method makes sense as a member of the World class. Returns (x, y, z) """ # The spawn Y coordinate is almost always the default of 64. Find the # first air block above the stored spawn location for the true spawn # location ## read spawn info from level.dat data = self.leveldat disp_spawnX = spawnX = data['SpawnX'] spawnY = data['SpawnY'] disp_spawnZ = spawnZ = data['SpawnZ'] ## clamp spawnY to a sane value, in-chunk value if spawnY < -63: spawnY = -63 if spawnY > 319: spawnY = 319 ## The chunk that holds the spawn location chunkX = spawnX//16 chunkY = spawnY//16 chunkZ = spawnZ//16 ## The block for spawn *within* the chunk inChunkX = spawnX % 16 inChunkZ = spawnZ % 16 inChunkY = spawnY % 16 ## Open up the chunk that the spawn is in regionset = self.get_regionset(None) if not regionset: return None try: chunk = regionset.get_chunk(chunkX, chunkZ) except ChunkDoesntExist: return (spawnX, spawnY, spawnZ) ## Check for first air block (0) above spawn # Get only the spawn section and the ones above, ordered from low to high spawnChunkSections = sorted(chunk['Sections'], key=lambda sec: sec['Y'])[chunkY:] for section in spawnChunkSections: # First section, start at registered local y for y in range(inChunkY, 16): # If air, return absolute coords if section['Blocks'][inChunkX, inChunkZ, y] == 0: return spawnX, spawnY, spawnZ # Keep track of the absolute Y spawnY += 1 # Next section, start at local 0 inChunkY = 0 return spawnX, 320, spawnZ class RegionSet(object): """This object is the gateway to a particular Minecraft dimension within a world. It corresponds to a set of region files containing the actual world data. This object has methods for parsing and returning data from the chunks from its regions. See the docs for the World object for more information on the difference between Worlds and RegionSets. """ def __init__(self, regiondir, rel): """Initialize a new RegionSet to access the region files in the given directory. regiondir is a path to a directory containing region files. rel is the relative path of this directory, with respect to the world directory. cachesize, if specified, is the number of chunks to keep parsed and in-memory. """ self.regiondir = os.path.normpath(regiondir) self.rel = os.path.normpath(rel) logging.debug("regiondir is %r" % self.regiondir) logging.debug("rel is %r" % self.rel) # we want to get rid of /regions, if it exists if self.rel.endswith(os.path.normpath("/region")): self.type = self.rel[0:-len(os.path.normpath("/region"))] elif self.rel == "region": # this is the main world self.type = None elif "entities" in os.path.split(self.rel): self.type = "entities" else: logging.warning("Unknown region type in %r, rel %r", regiondir, self.rel) self.type = "__unknown" logging.debug("Scanning regions. Type is %r" % self.type) # This is populated below. It is a mapping from (x,y) region coords to filename self.regionfiles = {} # This holds a cache of open regionfile objects self.regioncache = cache.LRUCache(size=16, destructor=lambda regionobj: regionobj.close()) for x, y, regionfile in self._iterate_regionfiles(): # regionfile is a pathname if os.path.getsize(regionfile) != 0: self.regionfiles[(x,y)] = (regionfile, os.path.getmtime(regionfile)) else: logging.debug("Skipping zero-size region file {}".format(regionfile)) self.empty_chunk = [None,None] logging.debug("Done scanning regions") self._blockmap = { 'minecraft:air': (0, 0), 'minecraft:cave_air': (0, 0), 'minecraft:void_air': (0, 0), 'minecraft:stone': (1, 0), 'minecraft:granite': (1, 1), 'minecraft:polished_granite': (1, 2), 'minecraft:diorite': (1, 3), 'minecraft:polished_diorite': (1, 4), 'minecraft:andesite': (1, 5), 'minecraft:polished_andesite': (1, 6), 'minecraft:grass_block': (2, 0), 'minecraft:dirt': (3, 0), 'minecraft:coarse_dirt': (3, 1), 'minecraft:podzol': (3, 2), 'minecraft:cobblestone': (4, 0), 'minecraft:infested_cobblestone': (4, 0), 'minecraft:oak_planks': (5, 0), 'minecraft:spruce_planks': (5, 1), 'minecraft:birch_planks': (5, 2), 'minecraft:jungle_planks': (5, 3), 'minecraft:acacia_planks': (5, 4), 'minecraft:dark_oak_planks': (5, 5), 'minecraft:crimson_planks': (5, 6), 'minecraft:warped_planks': (5, 7), 'minecraft:sapling': (6, 0), 'minecraft:bedrock': (7, 0), 'minecraft:water': (8, 0), 'minecraft:lava': (11, 0), 'minecraft:sand': (12, 0), 'minecraft:red_sand': (12, 1), 'minecraft:gravel': (13, 0), 'minecraft:gold_ore': (14, 0), 'minecraft:iron_ore': (15, 0), 'minecraft:coal_ore': (16, 0), 'minecraft:oak_log': (17, 0), 'minecraft:spruce_log': (17, 1), 'minecraft:birch_log': (17, 2), 'minecraft:jungle_log': (17, 3), 'minecraft:oak_leaves': (18, 0), 'minecraft:spruce_leaves': (18, 1), 'minecraft:birch_leaves': (18, 2), 'minecraft:jungle_leaves': (18, 3), 'minecraft:acacia_leaves': (18, 4), 'minecraft:dark_oak_leaves': (18, 5), 'minecraft:flowering_azalea_leaves': (18, 6), 'minecraft:azalea_leaves': (18, 7), 'minecraft:mangrove_leaves': (18, 8), 'minecraft:sponge': (19, 0), 'minecraft:wet_sponge': (19, 1), 'minecraft:glass': (20, 0), 'minecraft:lapis_ore': (21, 0), 'minecraft:lapis_block': (22, 0), 'minecraft:dispenser': (23, 0), 'minecraft:sandstone': (24, 0), 'minecraft:chiseled_sandstone': (24, 1), 'minecraft:cut_sandstone': (24, 2), 'minecraft:note_block': (25, 0), 'minecraft:powered_rail': (27, 0), 'minecraft:detector_rail': (28, 0), 'minecraft:sticky_piston': (29, 0), 'minecraft:cobweb': (30, 0), 'minecraft:dead_bush': (31, 0), 'minecraft:grass': (31, 1), 'minecraft:fern': (31, 2), 'minecraft:piston': (33, 0), 'minecraft:piston_head': (34, 0), 'minecraft:white_wool': (35, 0), 'minecraft:orange_wool': (35, 1), 'minecraft:magenta_wool': (35, 2), 'minecraft:light_blue_wool': (35, 3), 'minecraft:yellow_wool': (35, 4), 'minecraft:lime_wool': (35, 5), 'minecraft:pink_wool': (35, 6), 'minecraft:gray_wool': (35, 7), 'minecraft:light_gray_wool': (35, 8), 'minecraft:cyan_wool': (35, 9), 'minecraft:purple_wool': (35, 10), 'minecraft:blue_wool': (35, 11), 'minecraft:brown_wool': (35, 12), 'minecraft:green_wool': (35, 13), 'minecraft:red_wool': (35, 14), 'minecraft:black_wool': (35, 15), # Flowers 'minecraft:poppy': (38, 0), 'minecraft:blue_orchid': (38, 1), 'minecraft:allium': (38, 2), 'minecraft:azure_bluet': (38, 3), 'minecraft:red_tulip': (38, 4), 'minecraft:orange_tulip': (38, 5), 'minecraft:white_tulip': (38, 6), 'minecraft:pink_tulip': (38, 7), 'minecraft:oxeye_daisy': (38, 8), 'minecraft:dandelion': (38, 9), "minecraft:wither_rose": (38, 10), "minecraft:cornflower": (38, 11), "minecraft:lily_of_the_valley": (38, 12), 'minecraft:brown_mushroom': (39, 0), 'minecraft:red_mushroom': (40, 0), 'minecraft:gold_block': (41, 0), 'minecraft:iron_block': (42, 0), 'minecraft:stone_slab': (44, 0), 'minecraft:sandstone_slab': (44, 1), 'minecraft:oak_slab': (44, 2), 'minecraft:cobblestone_slab': (44, 3), 'minecraft:brick_slab': (44, 4), 'minecraft:stone_brick_slab': (44, 5), 'minecraft:nether_brick_slab': (44, 6), 'minecraft:quartz_slab': (44, 7), 'minecraft:bricks': (45, 0), 'minecraft:tnt': (46, 0), 'minecraft:bookshelf': (47, 0), 'minecraft:mossy_cobblestone': (48, 0), 'minecraft:obsidian': (49, 0), 'minecraft:wall_torch': (50, 0), 'minecraft:torch': (50, 5), 'minecraft:fire': (51, 0), 'minecraft:spawner': (52, 0), 'minecraft:oak_stairs': (53, 0), 'minecraft:crimson_stairs': (509, 0), 'minecraft:warped_stairs': (510, 0), 'minecraft:chest': (54, 0), 'minecraft:redstone_wire': (55, 0), 'minecraft:diamond_ore': (56, 0), 'minecraft:diamond_block': (57, 0), 'minecraft:crafting_table': (58, 0), 'minecraft:wheat': (59, 0), 'minecraft:farmland': (60, 0), 'minecraft:furnace': (61, 0), 'minecraft:sign': (63, 0), 'minecraft:oak_sign': (11401, 0), 'minecraft:spruce_sign': (11402, 0), 'minecraft:birch_sign': (11403, 0), 'minecraft:jungle_sign': (11404, 0), 'minecraft:acacia_sign': (11405, 0), 'minecraft:dark_oak_sign': (11406, 0), 'minecraft:crimson_sign': (12505, 0), 'minecraft:warped_sign': (12506, 0), 'minecraft:oak_door': (64, 0), 'minecraft:ladder': (65, 0), 'minecraft:rail': (66, 0), 'minecraft:cobblestone_stairs': (67, 0), 'minecraft:wall_sign': (68, 0), 'minecraft:oak_wall_sign': (11407, 0), 'minecraft:spruce_wall_sign': (11408, 0), 'minecraft:birch_wall_sign': (11409, 0), 'minecraft:jungle_wall_sign': (11410, 0), 'minecraft:acacia_wall_sign': (11411, 0), 'minecraft:dark_oak_wall_sign': (11412, 0), 'minecraft:crimson_wall_sign': (12507, 0), 'minecraft:warped_wall_sign': (12508, 0), 'minecraft:lever': (69, 0), 'minecraft:stone_pressure_plate': (70, 0), 'minecraft:iron_door': (71, 0), 'minecraft:oak_pressure_plate': (72, 0), 'minecraft:redstone_ore': (73, 0), 'minecraft:redstone_wall_torch': (75, 0), 'minecraft:redstone_torch': (75, 5), 'minecraft:stone_button': (77, 0), 'minecraft:snow': (78, 0), 'minecraft:ice': (79, 0), 'minecraft:snow_block': (80, 0), 'minecraft:cactus': (81, 0), 'minecraft:clay': (82, 0), 'minecraft:sugar_cane': (83, 0), 'minecraft:jukebox': (84, 0), 'minecraft:oak_fence': (85, 0), 'minecraft:pumpkin': (86, 0), 'minecraft:netherrack': (87, 0), 'minecraft:soul_sand': (88, 0), 'minecraft:glowstone': (89, 0), 'minecraft:nether_portal': (90, 0), 'minecraft:jack_o_lantern': (91, 0), 'minecraft:cake': (92, 0), 'minecraft:repeater': (93,0), 'minecraft:oak_trapdoor': (96, 0), 'minecraft:infested_stone': (97, 0), 'minecraft:stone_bricks': (98, 0), 'minecraft:infested_stone_bricks': (98, 0), 'minecraft:mossy_stone_bricks': (98, 1), 'minecraft:infested_mossy_stone_bricks': (98, 1), 'minecraft:cracked_stone_bricks': (98, 2), 'minecraft:infested_cracked_stone_bricks': (98, 2), 'minecraft:chiseled_stone_bricks': (98, 3), 'minecraft:infested_chiseled_stone_bricks': (98, 3), 'minecraft:brown_mushroom_block': (99, 0), 'minecraft:red_mushroom_block': (100, 0), 'minecraft:iron_bars': (101, 0), 'minecraft:glass_pane': (102, 0), 'minecraft:melon': (103,0), 'minecraft:attached_pumpkin_stem': (104, 0), 'minecraft:attached_melon_stem': (104, 0), 'minecraft:pumpkin_stem': (105, 0), 'minecraft:melon_stem': (105, 0), 'minecraft:vine': (106, 0), 'minecraft:oak_fence_gate': (107, 0), 'minecraft:brick_stairs': (108, 0), 'minecraft:stone_brick_stairs': (109, 0), 'minecraft:mycelium': (110, 0), 'minecraft:lily_pad': (111, 0), 'minecraft:nether_bricks': (112, 0), 'minecraft:cracked_nether_bricks': (112, 1), 'minecraft:chiseled_nether_bricks': (112, 2), 'minecraft:nether_brick_fence': (113, 0), 'minecraft:nether_brick_stairs': (114, 0), 'minecraft:nether_wart': (115, 0), 'minecraft:enchanting_table': (116, 0), 'minecraft:brewing_stand': (117, 0), 'minecraft:cauldron': (118, 1 << 2), 'minecraft:water_cauldron': (118, 1 << 2), 'minecraft:lava_cauldron': (118, (2 << 2) | 3), 'minecraft:powder_snow_cauldron': (118, 3 << 2), 'minecraft:end_portal': (119, 0), 'minecraft:end_portal_frame': (120, 0), 'minecraft:end_stone': (121, 0), 'minecraft:dragon_egg': (122, 0), 'minecraft:redstone_lamp': (123, 0), 'minecraft:oak_slab': (126, 0), 'minecraft:spruce_slab': (126, 1), 'minecraft:birch_slab': (126, 2), 'minecraft:jungle_slab': (126, 3), 'minecraft:acacia_slab': (126, 4), 'minecraft:dark_oak_slab': (126, 5), 'minecraft:crimson_slab': (126, 6), 'minecraft:warped_slab': (126, 7), 'minecraft:cocoa': (127, 0), 'minecraft:sandstone_stairs': (128, 0), 'minecraft:emerald_ore': (129, 0), 'minecraft:ender_chest': (130, 0), 'minecraft:tripwire': (131, 0), 'minecraft:tripwire_hook': (132, 0), 'minecraft:emerald_block': (133, 0), 'minecraft:spruce_stairs': (134, 0), 'minecraft:birch_stairs': (135, 0), 'minecraft:jungle_stairs': (136, 0), 'minecraft:command_block': (137, 0), 'minecraft:beacon': (138, 0), 'minecraft:mushroom_stem': (139, 0), 'minecraft:flower_pot': (140, 0), 'minecraft:potted_poppy': (140, 0), # Pots not rendering 'minecraft:potted_blue_orchid': (140, 0), 'minecraft:potted_allium': (140, 0), 'minecraft:potted_azure_bluet': (140, 0), 'minecraft:potted_red_tulip': (140, 0), 'minecraft:potted_orange_tulip': (140, 0), 'minecraft:potted_white_tulip': (140, 0), 'minecraft:potted_pink_tulip': (140, 0), 'minecraft:potted_oxeye_daisy': (140, 0), 'minecraft:potted_oak_sapling': (140, 0), 'minecraft:potted_spruce_sapling': (140, 0), 'minecraft:potted_birch_sapling': (140, 0), 'minecraft:potted_jungle_sapling': (140, 0), 'minecraft:potted_acacia_sapling': (140, 0), 'minecraft:potted_dark_oak_sapling': (140, 0), 'minecraft:potted_red_mushroom': (140, 0), 'minecraft:potted_brown_mushroom': (140, 0), 'minecraft:potted_fern': (140, 0), 'minecraft:potted_dead_bush': (140, 0), 'minecraft:potted_cactus': (140, 0), 'minecraft:potted_bamboo': (140, 0), 'minecraft:carrots': (141, 0), 'minecraft:potatoes': (142, 0), 'minecraft:oak_button': (143, 0), 'minecraft:skeleton_wall_skull': (144, 0), # not rendering 'minecraft:wither_skeleton_wall_skull': (144, 1), # not rendering 'minecraft:zombie_wall_head': (144, 2), # not rendering 'minecraft:player_wall_head': (144, 3), # not rendering 'minecraft:creeper_wall_head': (144, 4), # not rendering 'minecraft:dragon_wall_head': (144, 5), # not rendering 'minecraft:anvil': (145, 0), 'minecraft:chipped_anvil': (145, 4), 'minecraft:damaged_anvil': (145, 8), 'minecraft:trapped_chest': (146, 0), 'minecraft:light_weighted_pressure_plate': (147, 0), 'minecraft:heavy_weighted_pressure_plate': (148, 0), 'minecraft:comparator': (149, 0), 'minecraft:daylight_detector': (151, 0), 'minecraft:redstone_block': (152, 0), 'minecraft:nether_quartz_ore': (153, 0), 'minecraft:hopper': (154, 0), 'minecraft:quartz_block': (155, 0), 'minecraft:smooth_quartz': (155, 0), # Only bottom texture is different 'minecraft:quartz_pillar': (155, 2), 'minecraft:chiseled_quartz_block': (155, 1), 'minecraft:quartz_stairs': (156, 0), 'minecraft:activator_rail': (157, 0), 'minecraft:dropper': (158, 0), 'minecraft:white_terracotta': (159, 0), 'minecraft:orange_terracotta': (159, 1), 'minecraft:magenta_terracotta': (159, 2), 'minecraft:light_blue_terracotta': (159, 3), 'minecraft:yellow_terracotta': (159, 4), 'minecraft:lime_terracotta': (159, 5), 'minecraft:pink_terracotta': (159, 6), 'minecraft:gray_terracotta': (159, 7), 'minecraft:light_gray_terracotta': (159, 8), 'minecraft:cyan_terracotta': (159, 9), 'minecraft:purple_terracotta': (159, 10), 'minecraft:blue_terracotta': (159, 11), 'minecraft:brown_terracotta': (159, 12), 'minecraft:green_terracotta': (159, 13), 'minecraft:red_terracotta': (159, 14), 'minecraft:black_terracotta': (159, 15), 'minecraft:acacia_log': (162, 0), 'minecraft:dark_oak_log': (162, 1), 'minecraft:acacia_stairs': (163, 0), 'minecraft:dark_oak_stairs': (164, 0), 'minecraft:slime_block': (165,0), 'minecraft:iron_trapdoor': (167, 0), 'minecraft:prismarine': (168, 0), 'minecraft:dark_prismarine': (168, 2), 'minecraft:prismarine_bricks': (168, 1), 'minecraft:sea_lantern': (169, 0), 'minecraft:hay_block': (170, 0), 'minecraft:white_carpet': (171, 0), 'minecraft:orange_carpet': (171, 1), 'minecraft:magenta_carpet': (171, 2), 'minecraft:light_blue_carpet': (171, 3), 'minecraft:yellow_carpet': (171, 4), 'minecraft:lime_carpet': (171, 5), 'minecraft:pink_carpet': (171, 6), 'minecraft:gray_carpet': (171, 7), 'minecraft:light_gray_carpet': (171, 8), 'minecraft:cyan_carpet': (171, 9), 'minecraft:purple_carpet': (171, 10), 'minecraft:blue_carpet': (171, 11), 'minecraft:brown_carpet': (171, 12), 'minecraft:green_carpet': (171, 13), 'minecraft:red_carpet': (171, 14), 'minecraft:black_carpet': (171, 15), 'minecraft:moss_carpet': (171, 16), 'minecraft:terracotta': (172, 0), 'minecraft:coal_block': (173, 0), 'minecraft:packed_ice': (174, 0), 'minecraft:sunflower': (175, 0), 'minecraft:lilac': (175, 1), 'minecraft:tall_grass': (175, 2), 'minecraft:large_fern': (175, 3), 'minecraft:rose_bush': (175, 4), 'minecraft:peony': (175, 5), 'minecraft:standing_banner': (176, 0), 'minecraft:wall_banner': (177, 0), 'minecraft:red_sandstone': (179, 0), 'minecraft:chiseled_red_sandstone': (179, 1), 'minecraft:cut_red_sandstone': (179, 2), 'minecraft:red_sandstone_stairs': (180, 0), 'minecraft:red_sandstone_slab': (182,0), 'minecraft:spruce_fence_gate': (183, 0), 'minecraft:birch_fence_gate': (184, 0), 'minecraft:jungle_fence_gate': (185, 0), 'minecraft:dark_oak_fence_gate': (186, 0), 'minecraft:acacia_fence_gate': (187, 0), 'minecraft:crimson_fence_gate': (513, 0), 'minecraft:warped_fence_gate': (514, 0), 'minecraft:spruce_fence': (188, 0), 'minecraft:birch_fence': (189, 0), 'minecraft:jungle_fence': (190, 0), 'minecraft:dark_oak_fence': (191, 0), 'minecraft:acacia_fence': (192, 0), 'minecraft:crimson_fence': (511, 0), 'minecraft:warped_fence': (512, 0), 'minecraft:spruce_door': (193, 0), 'minecraft:birch_door': (194, 0), 'minecraft:jungle_door': (195, 0), 'minecraft:acacia_door': (196, 0), 'minecraft:dark_oak_door': (197, 0), 'minecraft:crimson_door': (499, 0), 'minecraft:warped_door': (500, 0), 'minecraft:end_rod': (198, 0), 'minecraft:chorus_plant': (199, 0), 'minecraft:chorus_flower': (200, 0), 'minecraft:purpur_block': (201, 0), 'minecraft:purpur_pillar': (202, 0), 'minecraft:purpur_stairs': (203, 0), 'minecraft:purpur_slab': (205, 0), 'minecraft:end_stone_bricks': (206, 0), 'minecraft:beetroots': (207, 0), 'minecraft:dirt_path': (208, 0), 'minecraft:grass_path': (208, 0), # compatibility 'minecraft:repeating_command_block': (210, 0), 'minecraft:chain_command_block': (211, 0), 'minecraft:frosted_ice': (212, 0), 'minecraft:magma_block': (213, 0), 'minecraft:nether_wart_block': (214, 0), 'minecraft:red_nether_bricks': (215, 0), 'minecraft:bone_block': (216, 0), 'minecraft:observer': (218, 0), 'minecraft:structure_block': (255, 0), 'minecraft:jigsaw': (256, 0), 'minecraft:shulker_box': (257, 0), 'minecraft:armor_stand': (416, 0), # not rendering # The following blocks are underwater and are not yet rendered. # To avoid spurious warnings, we'll treat them as water for now. 'minecraft:brain_coral': (8, 0), 'minecraft:brain_coral_fan': (8, 0), 'minecraft:brain_coral_wall_fan': (8, 0), 'minecraft:bubble_column': (8, 0), 'minecraft:bubble_coral': (8, 0), 'minecraft:bubble_coral_fan': (8, 0), 'minecraft:bubble_coral_wall_fan': (8, 0), 'minecraft:fire_coral': (8, 0), 'minecraft:fire_coral_fan': (8, 0), 'minecraft:fire_coral_wall_fan': (8, 0), 'minecraft:horn_coral': (8, 0), 'minecraft:horn_coral_fan': (8, 0), 'minecraft:horn_coral_wall_fan': (8, 0), 'minecraft:kelp': (8, 0), 'minecraft:kelp_plant': (8, 0), 'minecraft:sea_pickle': (8, 0), 'minecraft:seagrass': (8, 0), 'minecraft:tall_seagrass': (8, 0), 'minecraft:tube_coral': (8, 0), 'minecraft:tube_coral_fan': (8, 0), 'minecraft:tube_coral_wall_fan': (8, 0), # Some 1.16 stuff that I'll arbitrarily shove in here due to ID bloat 'minecraft:ancient_debris': (1000, 0), 'minecraft:basalt': (1001, 0), 'minecraft:polished_basalt': (1002, 0), 'minecraft:soul_campfire': (1003, 0), 'minecraft:blackstone': (1004, 0), 'minecraft:netherite_block': (1005, 0), 'minecraft:warped_nylium': (1006, 0), 'minecraft:crimson_nylium': (1007, 0), # Nether logs aka stem 'minecraft:warped_stem': (1008, 0), 'minecraft:stripped_warped_stem': (1008, 1), 'minecraft:crimson_stem': (1008, 2), 'minecraft:stripped_crimson_stem': (1008, 3), # hyphae 'minecraft:warped_hyphae': (1009, 0), 'minecraft:stripped_warped_hyphae': (1009, 1), 'minecraft:crimson_hyphae': (1009, 2), 'minecraft:stripped_crimson_hyphae': (1009, 3), # nether biomes 'minecraft:warped_wart_block': (1010, 0), 'minecraft:shroomlight': (1011, 0), 'minecraft:twisting_vines': (1012, 0), 'minecraft:twisting_vines_plant': (1013, 0), 'minecraft:weeping_vines': (1014, 0), 'minecraft:weeping_vines_plant': (1015, 0), 'minecraft:warped_fungus': (1016, 0), 'minecraft:crimson_fungus': (1017, 0), 'minecraft:warped_roots': (1018, 0), 'minecraft:crimson_roots': (1019, 0), 'minecraft:soul_soil': (1020, 0), 'minecraft:nether_gold_ore': (1021, 0), # Solid Nether stone blocks 'minecraft:polished_blackstone': (1022, 0), 'minecraft:chiseled_polished_blackstone': (1023, 0), 'minecraft:gilded_blackstone': (1024, 0), 'minecraft:cracked_polished_blackstone_bricks': (1025, 0), 'minecraft:polished_blackstone_bricks': (1026, 0), # Nether slabs 'minecraft:blackstone_slab': (1027, 0), 'minecraft:polished_blackstone_slab': (1028, 0), 'minecraft:polished_blackstone_brick_slab': (1029, 0), # Nether stairs 'minecraft:blackstone_stairs': (1030, 0), 'minecraft:polished_blackstone_stairs': (1031, 0), 'minecraft:polished_blackstone_brick_stairs': (1032, 0), # nether redstone blocks 'minecraft:polished_blackstone_pressure_plate': (1033, 0), 'minecraft:polished_blackstone_button': (1034, 0), # advanced nether blocks 'minecraft:crying_obsidian': (1035, 0), 'minecraft:lodestone': (1036, 0), 'minecraft:respawn_anchor': (1037, 0), # soul lightning 'minecraft:soul_lantern': (1038, 0), 'minecraft:soul_wall_torch': (1039, 0), 'minecraft:soul_torch': (1039, 5), 'minecraft:soul_fire': (1040, 0), # quartz bricks 'minecraft:quartz_bricks': (1041, 0), # 1.17 blocks go here 'minecraft:amethyst_block': (1042, 0), 'minecraft:raw_iron_block': (1043, 0), 'minecraft:raw_gold_block': (1044, 0), 'minecraft:budding_amethyst': (1045, 0), 'minecraft:copper_block': (1046, 0), 'minecraft:exposed_copper': (1047, 0), 'minecraft:weathered_copper': (1048, 0), 'minecraft:oxidized_copper': (1049, 0), 'minecraft:waxed_copper_block': (1050, 0), 'minecraft:waxed_exposed_copper': (1051, 0), 'minecraft:waxed_weathered_copper': (1052, 0), 'minecraft:waxed_oxidized_copper': (1053, 0), 'minecraft:cut_copper': (1054, 0), 'minecraft:exposed_cut_copper': (1055, 0), 'minecraft:weathered_cut_copper': (1056, 0), 'minecraft:oxidized_cut_copper': (1057, 0), 'minecraft:waxed_cut_copper': (1058, 0), 'minecraft:waxed_exposed_cut_copper': (1059, 0), 'minecraft:waxed_weathered_cut_copper': (1060, 0), 'minecraft:waxed_oxidized_cut_copper': (1061, 0), 'minecraft:raw_copper_block': (1062, 0), 'minecraft:copper_ore': (1063, 0), 'minecraft:cut_copper_stairs': (1064, 0), 'minecraft:exposed_cut_copper_stairs': (1065, 0), 'minecraft:weathered_cut_copper_stairs': (1066, 0), 'minecraft:oxidized_cut_copper_stairs': (1067, 0), 'minecraft:waxed_cut_copper_stairs': (1068, 0), 'minecraft:waxed_exposed_cut_copper_stairs': (1069, 0), 'minecraft:waxed_weathered_cut_copper_stairs': (1070, 0), 'minecraft:waxed_oxidized_cut_copper_stairs': (1071, 0), 'minecraft:cut_copper_slab': (1072, 0), 'minecraft:exposed_cut_copper_slab': (1073, 0), 'minecraft:weathered_cut_copper_slab': (1074, 0), 'minecraft:oxidized_cut_copper_slab': (1075, 0), 'minecraft:waxed_cut_copper_slab': (1076, 0), 'minecraft:waxed_exposed_cut_copper_slab': (1077, 0), 'minecraft:waxed_weathered_cut_copper_slab': (1078, 0), 'minecraft:waxed_oxidized_cut_copper_slab': (1079, 0), 'minecraft:moss_block': (1080, 0), 'minecraft:calcite': (1081, 0), 'minecraft:rooted_dirt': (1082, 0), 'minecraft:deepslate': (1083, 0), 'minecraft:infested_deepslate': (1083, 0), 'minecraft:cobbled_deepslate': (1084, 0), 'minecraft:polished_deepslate': (1085, 0), 'minecraft:deepslate_coal_ore': (1086, 0), 'minecraft:deepslate_iron_ore': (1087, 0), 'minecraft:deepslate_copper_ore': (1088, 0), 'minecraft:deepslate_gold_ore': (1089, 0), 'minecraft:deepslate_emerald_ore': (1090, 0), 'minecraft:deepslate_lapis_ore': (1091, 0), 'minecraft:deepslate_diamond_ore': (1092, 0), 'minecraft:deepslate_redstone_ore': (1093, 0), 'minecraft:deepslate_bricks': (1094, 0), 'minecraft:cracked_deepslate_bricks': (1095, 0), 'minecraft:deepslate_tiles': (1096, 0), 'minecraft:cracked_deepslate_tiles': (1097, 0), 'minecraft:chiseled_deepslate': (1098, 0), 'minecraft:cobbled_deepslate_stairs': (1099, 0), 'minecraft:polished_deepslate_stairs': (1100, 0), 'minecraft:deepslate_brick_stairs': (1101, 0), 'minecraft:deepslate_tile_stairs': (1102, 0), 'minecraft:cobbled_deepslate_slab': (1103, 0), 'minecraft:polished_deepslate_slab': (1104, 0), 'minecraft:deepslate_brick_slab': (1105, 0), 'minecraft:deepslate_tile_slab': (1106, 0), 'minecraft:dripstone_block': (1107, 0), 'minecraft:smooth_basalt': (1108, 0), 'minecraft:tuff': (1109, 0), 'minecraft:pointed_dripstone': (1110, 0), 'minecraft:powder_snow': (1111, 0), 'minecraft:hanging_roots': (1112, 0), 'minecraft:small_amethyst_bud': (1113, 0), 'minecraft:medium_amethyst_bud': (1114, 0), 'minecraft:large_amethyst_bud': (1115, 0), 'minecraft:cave_vines_plant': (1116, 0), 'minecraft:cave_vines': (1117, 0), 'minecraft:lightning_rod': (1118, 0), 'minecraft:glow_lichen': (1119, 0), 'minecraft:spore_blossom': (1120, 0), # 1.19 blocks 'minecraft:mud': (1121, 0), 'minecraft:packed_mud': (1122, 0), 'minecraft:mud_bricks': (1123, 0), 'minecraft:mud_brick_slab': (1124, 0), 'minecraft:mangrove_roots': (1125, 0), 'minecraft:mangrove_log': (1126, 0), 'minecraft:stripped_mangrove_log': (1126, 1), 'minecraft:muddy_mangrove_roots': (1127, 0), # New blocks 'minecraft:carved_pumpkin': (11300, 0), 'minecraft:spruce_pressure_plate': (11301, 0), 'minecraft:birch_pressure_plate': (11302, 0), 'minecraft:jungle_pressure_plate': (11303, 0), 'minecraft:acacia_pressure_plate': (11304, 0), 'minecraft:dark_oak_pressure_plate': (11305, 0), 'minecraft:crimson_pressure_plate': (11517, 0), 'minecraft:warped_pressure_plate': (11518, 0), 'minecraft:stripped_oak_log': (11306, 0), 'minecraft:stripped_spruce_log': (11306, 1), 'minecraft:stripped_birch_log': (11306, 2), 'minecraft:stripped_jungle_log': (11306, 3), 'minecraft:stripped_acacia_log': (11307, 0), 'minecraft:stripped_dark_oak_log': (11307, 1), 'minecraft:oak_wood': (11308, 0), 'minecraft:spruce_wood': (11308, 1), 'minecraft:birch_wood': (11308, 2), 'minecraft:jungle_wood': (11308, 3), 'minecraft:acacia_wood': (11309, 0), 'minecraft:dark_oak_wood': (11309, 1), 'minecraft:stripped_oak_wood': (11310, 0), 'minecraft:stripped_spruce_wood': (11310, 1), 'minecraft:stripped_birch_wood': (11310, 2), 'minecraft:stripped_jungle_wood': (11310, 3), 'minecraft:stripped_acacia_wood': (11311, 0), 'minecraft:stripped_dark_oak_wood': (11311, 1), 'minecraft:blue_ice': (11312, 0), 'minecraft:smooth_stone': (11313, 0), 'minecraft:smooth_sandstone': (11314, 0), 'minecraft:smooth_red_sandstone': (11315, 0), 'minecraft:brain_coral_block': (11316, 0), 'minecraft:bubble_coral_block': (11317, 0), 'minecraft:fire_coral_block': (11318, 0), 'minecraft:horn_coral_block': (11319, 0), 'minecraft:tube_coral_block': (11320, 0), 'minecraft:dead_brain_coral_block': (11321, 0), 'minecraft:dead_bubble_coral_block': (11322, 0), 'minecraft:dead_fire_coral_block': (11323, 0), 'minecraft:dead_horn_coral_block': (11324, 0), 'minecraft:dead_tube_coral_block': (11325, 0), 'minecraft:spruce_button': (11326,0), 'minecraft:birch_button': (11327,0), 'minecraft:jungle_button': (11328,0), 'minecraft:acacia_button': (11329,0), 'minecraft:dark_oak_button': (11330,0), 'minecraft:crimson_button': (11515,0), 'minecraft:warped_button': (11516,0), 'minecraft:dried_kelp_block': (11331,0), 'minecraft:spruce_trapdoor': (11332, 0), 'minecraft:birch_trapdoor': (11333, 0), 'minecraft:jungle_trapdoor': (11334, 0), 'minecraft:acacia_trapdoor': (11335, 0), 'minecraft:dark_oak_trapdoor': (11336, 0), 'minecraft:crimson_trapdoor': (12501, 0), 'minecraft:warped_trapdoor': (12502, 0), 'minecraft:petrified_oak_slab': (126, 0), 'minecraft:prismarine_stairs': (11337, 0), 'minecraft:dark_prismarine_stairs': (11338, 0), 'minecraft:prismarine_brick_stairs': (11339,0), 'minecraft:prismarine_slab': (11340, 0), 'minecraft:dark_prismarine_slab': (11341, 0), 'minecraft:prismarine_brick_slab': (11342, 0), "minecraft:andesite_slab": (11343, 0), "minecraft:diorite_slab": (11344, 0), "minecraft:granite_slab": (11345, 0), "minecraft:polished_andesite_slab": (11346, 0), "minecraft:polished_diorite_slab": (11347, 0), "minecraft:polished_granite_slab": (11348, 0), "minecraft:red_nether_brick_slab": (11349, 0), "minecraft:smooth_sandstone_slab": (11350, 0), "minecraft:cut_sandstone_slab": (11351, 0), "minecraft:smooth_red_sandstone_slab": (11352, 0), "minecraft:cut_red_sandstone_slab": (11353, 0), "minecraft:end_stone_brick_slab": (11354, 0), "minecraft:mossy_cobblestone_slab": (11355, 0), "minecraft:mossy_stone_brick_slab": (11356, 0), "minecraft:smooth_quartz_slab": (11357, 0), "minecraft:smooth_stone_slab": (11358, 0), "minecraft:fletching_table": (11359, 0), "minecraft:cartography_table": (11360, 0), "minecraft:smithing_table": (11361, 0), "minecraft:blast_furnace": (11362, 0), "minecraft:smoker": (11364, 0), "minecraft:lectern": (11366, 0), "minecraft:loom": (11367, 0), "minecraft:stonecutter": (11368, 0), "minecraft:grindstone": (11369, 0), "minecraft:mossy_stone_brick_stairs": (11370, 0), "minecraft:mossy_cobblestone_stairs": (11371, 0), "minecraft:lantern": (11373, 0), "minecraft:smooth_sandstone_stairs": (11374, 0), 'minecraft:smooth_quartz_stairs': (11375, 0), 'minecraft:polished_granite_stairs': (11376, 0), 'minecraft:polished_diorite_stairs': (11377, 0), 'minecraft:polished_andesite_stairs': (11378, 0), 'minecraft:stone_stairs': (11379, 0), 'minecraft:granite_stairs': (11380, 0), 'minecraft:diorite_stairs': (11381, 0), 'minecraft:andesite_stairs': (11382, 0), 'minecraft:end_stone_brick_stairs': (11383, 0), 'minecraft:red_nether_brick_stairs': (11384, 0), 'minecraft:oak_sapling': (11385, 0), 'minecraft:spruce_sapling': (11386, 0), 'minecraft:birch_sapling': (11387, 0), 'minecraft:jungle_sapling': (11388, 0), 'minecraft:acacia_sapling': (11389, 0), 'minecraft:dark_oak_sapling': (11390, 0), 'minecraft:bamboo_sapling': (11413, 0), 'minecraft:scaffolding': (11414, 0), "minecraft:smooth_red_sandstone_stairs": (11415, 0), 'minecraft:bamboo': (11416, 0), "minecraft:composter": (11417, 0), "minecraft:barrel": (11418, 0), "minecraft:chain": (11419, 0), # 1.15 blocks below 'minecraft:beehive': (11501, 0), 'minecraft:bee_nest': (11502, 0), 'minecraft:honeycomb_block': (11503, 0), 'minecraft:honey_block': (11504, 0), 'minecraft:sweet_berry_bush': (11505, 0), 'minecraft:campfire': (11506, 0), 'minecraft:bell': (11507, 0), # adding a gap in the numbering of walls to keep them all # blocks >= 1792 and <= 2047 are considered walls 'minecraft:andesite_wall': (1792, 0), 'minecraft:brick_wall': (1793, 0), 'minecraft:cobblestone_wall': (1794, 0), 'minecraft:diorite_wall': (1795, 0), 'minecraft:end_stone_brick_wall': (1796, 0), 'minecraft:granite_wall': (1797, 0), 'minecraft:mossy_cobblestone_wall': (1798, 0), 'minecraft:mossy_stone_brick_wall': (1799, 0), 'minecraft:nether_brick_wall': (1800, 0), 'minecraft:prismarine_wall': (1801, 0), 'minecraft:red_nether_brick_wall': (1802, 0), 'minecraft:red_sandstone_wall': (1803, 0), 'minecraft:sandstone_wall': (1804, 0), 'minecraft:stone_brick_wall': (1805, 0), 'minecraft:blackstone_wall': (1806, 0), 'minecraft:polished_blackstone_wall': (1807, 0), 'minecraft:polished_blackstone_brick_wall': (1808, 0), 'minecraft:cobbled_deepslate_wall': (1809, 0), 'minecraft:polished_deepslate_wall': (1810, 0), 'minecraft:deepslate_brick_wall': (1811, 0), 'minecraft:deepslate_tile_wall': (1812, 0), } colors = [ 'white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] for i in range(len(colors)): # For beds: bits 1-2 indicate facing, bit 3 occupancy, bit 4 foot (0) or head (1) self._blockmap['minecraft:%s_bed' % colors[i]] = (26, i << 4) self._blockmap['minecraft:%s_stained_glass' % colors[i]] = (95, i) self._blockmap['minecraft:%s_stained_glass_pane' % colors[i]] = (160, i) self._blockmap['minecraft:%s_banner' % colors[i]] = (176, i) # not rendering self._blockmap['minecraft:%s_wall_banner' % colors[i]] = (177, i) # not rendering self._blockmap['minecraft:%s_shulker_box' % colors[i]] = (219 + i, 0) self._blockmap['minecraft:%s_glazed_terracotta' % colors[i]] = (235 + i, 0) self._blockmap['minecraft:%s_concrete' % colors[i]] = (251, i) self._blockmap['minecraft:%s_concrete_powder' % colors[i]] = (252, i) # Re-initialize upon unpickling def __getstate__(self): return (self.regiondir, self.rel) def __setstate__(self, state): return self.__init__(*state) def __repr__(self): return "<RegionSet regiondir=%r>" % self.regiondir def _get_block(self, palette_entry): wood_slabs = ('minecraft:oak_slab','minecraft:spruce_slab','minecraft:birch_slab','minecraft:jungle_slab', 'minecraft:acacia_slab','minecraft:dark_oak_slab','minecraft:petrified_oak_slab', 'minecraft:crimson_slab', 'minecraft:warped_slab') stone_slabs = ('minecraft:stone_slab', 'minecraft:sandstone_slab','minecraft:red_sandstone_slab', 'minecraft:cobblestone_slab', 'minecraft:brick_slab','minecraft:purpur_slab', 'minecraft:stone_brick_slab', 'minecraft:nether_brick_slab', 'minecraft:quartz_slab', "minecraft:andesite_slab", 'minecraft:diorite_slab', 'minecraft:granite_slab', 'minecraft:polished_andesite_slab', 'minecraft:polished_diorite_slab','minecraft:polished_granite_slab', 'minecraft:red_nether_brick_slab','minecraft:smooth_sandstone_slab', 'minecraft:cut_sandstone_slab','minecraft:smooth_red_sandstone_slab', 'minecraft:cut_red_sandstone_slab','minecraft:end_stone_brick_slab', 'minecraft:mossy_cobblestone_slab','minecraft:mossy_stone_brick_slab', 'minecraft:smooth_quartz_slab','minecraft:smooth_stone_slab', 'minecraft:blackstone_slab','minecraft:polished_blackstone_slab', 'minecraft:polished_blackstone_brick_slab', 'minecraft:cobbled_deepslate_slab', 'minecraft:polished_deepslate_slab', 'minecraft:deepslate_brick_slab', 'minecraft:deepslate_tile_slab', 'minecraft:mud_brick_slab' ) prismarine_slabs = ('minecraft:prismarine_slab','minecraft:dark_prismarine_slab','minecraft:prismarine_brick_slab') copper_slabs = ( 'minecraft:cut_copper_slab', 'minecraft:exposed_cut_copper_slab', 'minecraft:weathered_cut_copper_slab', 'minecraft:oxidized_cut_copper_slab', 'minecraft:waxed_cut_copper_slab', 'minecraft:waxed_exposed_cut_copper_slab', 'minecraft:waxed_weathered_cut_copper_slab', 'minecraft:waxed_oxidized_cut_copper_slab' ) # Map from slab to double slab block slab_to_double = { 'minecraft:stone_slab': 'minecraft:stone', 'minecraft:cobblestone_slab': 'minecraft:cobblestone', 'minecraft:sandstone_slab': 'minecraft:sandstone', 'minecraft:red_sandstone_slab': 'minecraft:red_sandstone', 'minecraft:nether_brick_slab': 'minecraft:nether_bricks', 'minecraft:quartz_slab': 'minecraft:quartz_block', 'minecraft:brick_slab': 'minecraft:bricks', 'minecraft:purpur_slab': 'minecraft:purpur_block', 'minecraft:andesite_slab': 'minecraft:andesite', 'minecraft:diorite_slab': 'minecraft:diorite', 'minecraft:granite_slab': 'minecraft:granite', 'minecraft:polished_andesite_slab': 'minecraft:polished_andesite', 'minecraft:polished_diorite_slab': 'minecraft:polished_diorite', 'minecraft:polished_granite_slab': 'minecraft:polished_granite', 'minecraft:red_nether_brick_slab': 'minecraft:red_nether_bricks', 'minecraft:smooth_sandstone_slab': 'minecraft:smooth_sandstone', 'minecraft:cut_sandstone_slab': 'minecraft:cut_sandstone', 'minecraft:smooth_red_standstone_slab': 'minecraft:smooth_red_sandstone', 'minecraft:cut_red_sandstone_slab': 'minecraft:cut_red_sandstone', 'minecraft:end_stone_brick_slab': 'minecraft:end_stone_bricks', 'minecraft:mossy_cobblestone_slab': 'minecraft:mossy_cobblestone', 'minecraft:mossy_stone_brick_slab': 'minecraft:mossy_stone_bricks', 'minecraft:smooth_quartz_slab': 'minecraft:smooth_quartz', 'minecraft:smooth_stone_slab': 'minecraft:smooth_stone', 'minecraft:blackstone_slab': 'minecraft:blackstone', 'minecraft:polished_blackstone_slab': 'minecraft:polished_blackstone', 'minecraft:polished_blackstone_brick_slab': 'minecraft:polished_blackstone_bricks', 'minecraft:cobbled_deepslate_slab': 'minecraft:cobbled_deepslate', 'minecraft:polished_deepslate_slab': 'minecraft:polished_deepslate', 'minecraft:deepslate_brick_slab': 'minecraft:deepslate_bricks', 'minecraft:deepslate_tile_slab': 'minecraft:deepslate_tiles', 'minecraft:mud_brick_slab': 'minecraft:mud_bricks', 'minecraft:cut_copper_slab': 'minecraft:cut_copper', 'minecraft:exposed_cut_copper_slab': 'minecraft:exposed_cut_copper', 'minecraft:weathered_cut_copper_slab': 'minecraft:weathered_cut_copper', 'minecraft:oxidized_cut_copper_slab': 'minecraft:oxidized_cut_copper', 'minecraft:waxed_cut_copper_slab': 'minecraft:waxed_cut_copper', 'minecraft:waxed_exposed_cut_copper_slab': 'minecraft:waxed_exposed_cut_copper', 'minecraft:waxed_weathered_cut_copper_slab': 'minecraft:waxed_weathered_cut_copper', 'minecraft:waxed_oxidized_cut_copper_slab': 'minecraft:waxed_oxidized_cut_copper', 'minecraft:prismarine_slab': 'minecraft:prismarine', 'minecraft:dark_prismarine_slab': 'minecraft:dark_prismarine', 'minecraft:prismarine_brick_slab': 'minecraft:prismarine_bricks', } colors = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] key = palette_entry['Name'] (block, data) = self._blockmap[key] if key in ['minecraft:redstone_ore', 'minecraft:redstone_lamp']: if palette_entry['Properties']['lit'] == 'true': block += 1 elif key.endswith('gate'): facing = palette_entry['Properties']['facing'] data = {'south': 0, 'west': 1, 'north': 2, 'east': 3}[facing] if palette_entry['Properties']['open'] == 'true': data += 4 elif key.endswith('rail'): shape = palette_entry['Properties']['shape'] data = {'north_south':0, 'east_west': 1, 'ascending_east': 2, 'ascending_west': 3, 'ascending_north': 4, 'ascending_south': 5, 'south_east': 6, 'south_west': 7, 'north_west': 8, 'north_east': 9}[shape] if key == 'minecraft:powered_rail' and palette_entry['Properties']['powered'] == 'true': data |= 8 elif key in ['minecraft:comparator', 'minecraft:repeater']: # Bits 1-2 indicates facing, bits 3-4 indicates delay if palette_entry['Properties']['powered'] == 'true': block += 1 facing = palette_entry['Properties']['facing'] data = {'south': 0, 'west': 1, 'north': 2, 'east': 3}[facing] data |= (int(palette_entry['Properties'].get('delay', '1')) - 1) << 2 elif key == 'minecraft:daylight_detector': if palette_entry['Properties']['inverted'] == 'true': block = 178 elif key == 'minecraft:redstone_wire': data = palette_entry['Properties']['power'] elif key == 'minecraft:grass_block': if palette_entry['Properties']['snowy'] == 'true': data |= 0x10 elif key == 'minecraft:snow': data = palette_entry['Properties']['layers'] elif key in ('minecraft:sunflower', 'minecraft:lilac', 'minecraft:tall_grass', 'minecraft:large_fern', 'minecraft:rose_bush', 'minecraft:peony'): if palette_entry['Properties']['half'] == 'upper': data |= 0x08 elif key in wood_slabs + stone_slabs + prismarine_slabs + copper_slabs: # handle double slabs if palette_entry['Properties']['type'] == 'top': data |= 0x08 elif palette_entry['Properties']['type'] == 'double': if key in wood_slabs: block = 125 # block_double_wooden_slab else: (block, data) = self._blockmap[slab_to_double[key]] elif key in ['minecraft:ladder', 'minecraft:chest', 'minecraft:ender_chest', 'minecraft:trapped_chest', 'minecraft:furnace', 'minecraft:blast_furnace', 'minecraft:smoker']: facing = palette_entry['Properties']['facing'] data = {'north': 2, 'south': 3, 'west': 4, 'east': 5}[facing] if key in ['minecraft:chest', 'minecraft:trapped_chest']: # type property should exist, but default to 'single' just in case chest_type = palette_entry['Properties'].get('type', 'single') data |= {'left': 0x8, 'right': 0x10, 'single': 0x0}[chest_type] elif key in ['minecraft:furnace', 'minecraft:blast_furnace', 'minecraft:smoker']: data |= 8 if palette_entry['Properties'].get('lit', 'false') == 'true' else 0 elif key in ['minecraft:beehive', 'minecraft:bee_nest']: facing = palette_entry['Properties']['facing'] honey_level = int(palette_entry['Properties']['honey_level']) data = {'south': 0, 'west': 1, 'north': 2, 'east': 3}[facing] if honey_level == 5: data = {'south': 4, 'west': 5, 'north': 6, 'east': 7}[facing] elif key.endswith('_button'): facing = palette_entry['Properties']['facing'] face = palette_entry['Properties']['face'] if face == 'ceiling': block = 0 data = 0 elif face == 'wall': data = {'east': 1, 'west': 2, 'south': 3, 'north': 4}[facing] elif face == 'floor': data = {'east': 6, 'west': 6, 'south': 5, 'north': 5}[facing] elif key == 'minecraft:nether_wart': data = int(palette_entry['Properties']['age']) elif (key.endswith('shulker_box') or key.endswith('piston') or key in ['minecraft:observer', 'minecraft:dropper', 'minecraft:dispenser', 'minecraft:piston_head', 'minecraft:jigsaw', 'minecraft:end_rod']): p = palette_entry['Properties'] data = {'down': 0, 'up': 1, 'north': 2, 'south': 3, 'west': 4, 'east': 5}[p['facing']] if ((key.endswith('piston') and p.get('extended', 'false') == 'true') or (key == 'minecraft:piston_head' and p.get('type', 'normal') == 'sticky') or (key == 'minecraft:observer' and p.get('powered', 'false') == 'true')): data |= 0x08 elif (key.endswith('_log') or key.endswith('_wood') or key in ['minecraft:bone_block', 'minecraft:warped_stem', 'minecraft:stripped_warped_stem', 'minecraft:crimson_stem', 'minecraft:stripped_crimson_stem']): axis = palette_entry['Properties']['axis'] if axis == 'x': data |= 4 elif axis == 'z': data |= 8 elif key == 'minecraft:quartz_pillar': axis = palette_entry['Properties']['axis'] if axis == 'x': data = 3 if axis == 'z': data = 4 elif key in ['minecraft:basalt', 'minecraft:polished_basalt', 'minecraft:chain', 'minecraft:purpur_pillar', 'minecraft:deepslate']: axis = palette_entry['Properties']['axis'] data = {'y': 0, 'x': 1, 'z': 2}[axis] elif key in ['minecraft:redstone_torch','minecraft:redstone_wall_torch','minecraft:wall_torch', 'minecraft:soul_torch', 'minecraft:soul_wall_torch']: if key.startswith('minecraft:redstone_') and palette_entry['Properties']['lit'] == 'true': block += 1 if key.endswith('wall_torch'): facing = palette_entry['Properties'].get('facing') data = {'east': 1, 'west': 2, 'south': 3, 'north': 4}[facing] else: data = 5 elif (key in ['minecraft:carved_pumpkin', 'minecraft:jack_o_lantern', 'minecraft:stonecutter', 'minecraft:loom'] or key.endswith('glazed_terracotta')): facing = palette_entry['Properties']['facing'] data = {'south': 0, 'west': 1, 'north': 2, 'east': 3}[facing] elif key in ['minecraft:vine', 'minecraft:brown_mushroom_block', 'minecraft:red_mushroom_block', 'minecraft:mushroom_stem']: p = palette_entry['Properties'] if p['south'] == 'true': data |= 1 if p['west'] == 'true': data |= 2 if p['north'] == 'true': data |= 4 if p['east'] == 'true': data |= 8 if p['up'] == 'true': data |= 16 # Not all blocks here have the down property, so use dict.get() to avoid errors if p.get('down', 'false') == 'true': data |= 32 elif key.endswith('anvil'): facing = palette_entry['Properties']['facing'] if facing == 'west': data += 1 if facing == 'north': data += 2 if facing == 'east': data += 3 elif key.endswith('sign'): if key.endswith('wall_sign'): facing = palette_entry['Properties']['facing'] if facing == 'north': data = 2 elif facing == 'west': data = 4 elif facing == 'south': data = 3 elif facing == 'east': data = 5 else: p = palette_entry['Properties'] data = p['rotation'] elif key.endswith('_fence'): p = palette_entry['Properties'] if p['north'] == 'true': data |= 1 if p['east'] == 'true': data |= 2 if p['south'] == 'true': data |= 4 if p['west'] == 'true': data |= 8 elif key.endswith('_stairs'): facing = palette_entry['Properties']['facing'] if facing == 'south': data = 2 elif facing == 'east': data = 0 elif facing == 'north': data = 3 elif facing == 'west': data = 1 if palette_entry['Properties']['half'] == 'top': data |= 0x4 elif key.endswith('_door'): p = palette_entry['Properties'] if p['hinge'] == 'left': data |= 0x10 if p['open'] == 'true': data |= 0x04 if p['half'] == 'upper': data |= 0x08 data |= { 'north': 0x03, 'west': 0x02, 'south': 0x01, 'east': 0x00, }[p['facing']] elif key.endswith('_trapdoor'): p = palette_entry['Properties'] data = {'south': 1, 'north': 0, 'east': 3, 'west': 2}[p['facing']] if p['open'] == 'true': data |= 0x04 if p['half'] == 'top': data |= 0x08 elif key in ['minecraft:beetroots', 'minecraft:melon_stem', 'minecraft:wheat', 'minecraft:pumpkin_stem', 'minecraft:potatoes', 'minecraft:carrots', 'minecraft:sweet_berry_bush', 'minecraft:chorus_flower']: data = palette_entry['Properties']['age'] elif key in ['minecraft:lantern', 'minecraft:soul_lantern']: if palette_entry['Properties']['hanging'] == 'true': data = 1 else: data = 0 elif key == "minecraft:composter": data = palette_entry['Properties']['level'] elif key == "minecraft:barrel": facing_data = {'up': 0, 'down': 1, 'south': 2, 'east': 3, 'north': 4, 'west': 5} data = ( (facing_data[palette_entry['Properties']['facing']] << 1) + (1 if palette_entry['Properties']['open'] == 'true' else 0) ) elif key.endswith('_bed'): facing = palette_entry['Properties']['facing'] data |= {'south': 0, 'west': 1, 'north': 2, 'east': 3}[facing] if palette_entry['Properties'].get('part', 'foot') == 'head': data |= 8 elif key == 'minecraft:end_portal_frame': facing = palette_entry['Properties']['facing'] data |= {'south': 0, 'west': 1, 'north': 2, 'east': 3}[facing] if palette_entry['Properties'].get('eye', 'false') == 'true': data |= 4 elif key == 'minecraft:respawn_anchor': data = int(palette_entry['Properties']['charges']) elif key in ['minecraft:cauldron', 'minecraft:water_cauldron', 'minecraft:lava_cauldron', 'minecraft:powder_snow_cauldron']: data |= int(palette_entry.get('Properties', {}).get('level', '0')) elif key == 'minecraft:structure_block': block_mode = palette_entry['Properties'].get('mode', 'save') data = {'save': 0, 'load': 1, 'corner': 2, 'data': 3}.get(block_mode, 0) elif key == 'minecraft:cake': data = int(palette_entry['Properties'].get('bites', '0')) elif key == 'minecraft:farmland': # A moisture level of 7 has a different texture from other farmland data = 1 if palette_entry['Properties'].get('moisture', '0') == '7' else 0 elif key in ['minecraft:grindstone', 'minecraft:lectern', 'minecraft:campfire', 'minecraft:bell', 'minecraft:soul_campfire']: p = palette_entry['Properties'] data = {'south': 0, 'west': 1, 'north': 2, 'east': 3}[p['facing']] if key == 'minecraft:grindstone': data |= {'floor': 0, 'wall': 4, 'ceiling': 8}[p['face']] elif key == 'minecraft:lectern': if p['has_book'] == 'true': data |= 4 elif key == 'minecraft:campfire' or key == 'minecraft:soul_campfire': if p['lit'] == 'true': data |= 4 elif key == 'minecraft:bell': data |= {'floor': 0, 'ceiling': 4, 'single_wall': 8, 'double_wall': 12}[p['attachment']] elif key in ['minecraft:iron_bars', 'minecraft:glass_pane'] or \ key in ['minecraft:%s_stained_glass_pane' % item for item in colors]: p = palette_entry['Properties'] if p['north'] == 'true': data |= (1 << 4) if p['east'] == 'true': data |= (2 << 4) if p['south'] == 'true': data |= (4 << 4) if p['west'] == 'true': data |= (8 << 4) elif key == 'minecraft:pointed_dripstone': p = palette_entry['Properties'] data = {'tip': 0, 'tip_merge': 1, 'middle': 2, 'frustum': 3, 'base': 4}[p['thickness']] data |= {'up': 0, 'down': 0b1000}[p['vertical_direction']] elif key in ['minecraft:small_amethyst_bud', 'minecraft:medium_amethyst_bud', 'minecraft:large_amethyst_bud', 'minecraft:lightning_rod']: p = palette_entry['Properties'] data = {'down': 0, 'up': 1, 'east': 2, 'south': 3, 'west': 4, 'north': 5}[p['facing']] elif key in ['minecraft:cave_vines_plant', 'minecraft:cave_vines']: p = palette_entry['Properties'] if p['berries'] == 'true': data = 1 elif key == 'minecraft:glow_lichen': p = palette_entry['Properties'] if p['down'] == 'true': data |= 1 << 0 if p['up'] == 'true': data |= 1 << 1 if p['east'] == 'true': data |= 1 << 2 if p['south'] == 'true': data |= 1 << 3 if p['west'] == 'true': data |= 1 << 4 if p['north'] == 'true': data |= 1 << 5 return (block, data) def get_type(self): """Attempts to return a string describing the dimension represented by this regionset. Usually this is the relative path of the regionset within the world, minus the suffix /region, but for the main world it's None. """ # path will be normalized in __init__ return self.type def _get_regionobj(self, regionfilename): # Check the cache first. If it's not there, create the # nbt.MCRFileReader object, cache it, and return it # May raise an nbt.CorruptRegionError try: return self.regioncache[regionfilename] except KeyError: region = nbt.load_region(regionfilename) self.regioncache[regionfilename] = region return region def _packed_longarray_to_shorts(self, long_array, n, num_palette): bits_per_value = (len(long_array) * 64) / n if bits_per_value < 4 or 12 < bits_per_value: raise nbt.CorruptChunkError() b = numpy.frombuffer(numpy.asarray(long_array, dtype=numpy.uint64), dtype=numpy.uint8) # give room for work, later b = b.astype(numpy.uint16) if bits_per_value == 8: return b result = numpy.zeros((n,), dtype=numpy.uint16) if bits_per_value == 4: result[0::2] = b & 0x0f result[1::2] = (b & 0xf0) >> 4 elif bits_per_value == 5: result[0::8] = b[0::5] & 0x1f result[1::8] = ((b[1::5] & 0x03) << 3) | ((b[0::5] & 0xe0) >> 5) result[2::8] = (b[1::5] & 0x7c) >> 2 result[3::8] = ((b[2::5] & 0x0f) << 1) | ((b[1::5] & 0x80) >> 7) result[4::8] = ((b[3::5] & 0x01) << 4) | ((b[2::5] & 0xf0) >> 4) result[5::8] = (b[3::5] & 0x3e) >> 1 result[6::8] = ((b[4::5] & 0x07) << 2) | ((b[3::5] & 0xc0) >> 6) result[7::8] = (b[4::5] & 0xf8) >> 3 elif bits_per_value == 6: result[0::4] = b[0::3] & 0x3f result[1::4] = ((b[1::3] & 0x0f) << 2) | ((b[0::3] & 0xc0) >> 6) result[2::4] = ((b[2::3] & 0x03) << 4) | ((b[1::3] & 0xf0) >> 4) result[3::4] = (b[2::3] & 0xfc) >> 2 elif bits_per_value == 7: result[0::8] = b[0::7] & 0x7f result[1::8] = ((b[1::7] & 0x3f) << 1) | ((b[0::7] & 0x80) >> 7) result[2::8] = ((b[2::7] & 0x1f) << 2) | ((b[1::7] & 0xc0) >> 6) result[3::8] = ((b[3::7] & 0x0f) << 3) | ((b[2::7] & 0xe0) >> 5) result[4::8] = ((b[4::7] & 0x07) << 4) | ((b[3::7] & 0xf0) >> 4) result[5::8] = ((b[5::7] & 0x03) << 5) | ((b[4::7] & 0xf8) >> 3) result[6::8] = ((b[6::7] & 0x01) << 6) | ((b[5::7] & 0xfc) >> 2) result[7::8] = (b[6::7] & 0xfe) >> 1 # bits_per_value == 8 is handled above elif bits_per_value == 9: result[0::8] = ((b[1::9] & 0x01) << 8) | b[0::9] result[1::8] = ((b[2::9] & 0x03) << 7) | ((b[1::9] & 0xfe) >> 1) result[2::8] = ((b[3::9] & 0x07) << 6) | ((b[2::9] & 0xfc) >> 2) result[3::8] = ((b[4::9] & 0x0f) << 5) | ((b[3::9] & 0xf8) >> 3) result[4::8] = ((b[5::9] & 0x1f) << 4) | ((b[4::9] & 0xf0) >> 4) result[5::8] = ((b[6::9] & 0x3f) << 3) | ((b[5::9] & 0xe0) >> 5) result[6::8] = ((b[7::9] & 0x7f) << 2) | ((b[6::9] & 0xc0) >> 6) result[7::8] = ( b[8::9] << 1) | ((b[7::9] & 0x80) >> 7) elif bits_per_value == 10: result[0::4] = ((b[1::5] & 0x03) << 8) | b[0::5] result[1::4] = ((b[2::5] & 0x0f) << 6) | ((b[1::5] & 0xfc) >> 2) result[2::4] = ((b[3::5] & 0x3f) << 4) | ((b[2::5] & 0xf0) >> 4) result[3::4] = ( b[4::5] << 2) | ((b[3::5] & 0xc0) >> 6) elif bits_per_value == 11: result[0::8] = ((b[ 1::11] & 0x07) << 8 ) | b[ 0::11] result[1::8] = ((b[ 2::11] & 0x3f) << 5 ) | ((b[ 1::11] & 0xf8) >> 3 ) result[2::8] = ((b[ 4::11] & 0x01) << 10) | ( b[ 3::11] << 2 ) | ((b[ 2::11] & 0xc0) >> 6 ) result[3::8] = ((b[ 5::11] & 0x0f) << 7 ) | ((b[ 4::11] & 0xfe) >> 1 ) result[4::8] = ((b[ 6::11] & 0x7f) << 4 ) | ((b[ 5::11] & 0xf0) >> 4 ) result[5::8] = ((b[ 8::11] & 0x03) << 9 ) | ( b[ 7::11] << 1 ) | ((b[ 6::11] & 0x80) >> 7 ) result[6::8] = ((b[ 9::11] & 0x1f) << 2 ) | ((b[ 8::11] & 0xfc) >> 2 ) result[7::8] = ( b[10::11] << 3 ) | ((b[ 9::11] & 0xe0) >> 5 ) elif bits_per_value == 12: result[0::2] = ((b[1::3] & 0x0f) << 8) | b[0::3] result[1::2] = ( b[2::3] << 4) | ((b[1::3] & 0xf0) >> 4) return result def _packed_longarray_to_shorts_v116(self, long_array, n, num_palette): bits_per_value = max(4, (len(long_array) * 64) // n) b = numpy.asarray(long_array, dtype=numpy.uint64) result = numpy.zeros((n,), dtype=numpy.uint16) shorts_per_long = 64 // bits_per_value mask = (1 << bits_per_value) - 1 for i in range(shorts_per_long): j = (n + shorts_per_long - 1 - i) // shorts_per_long result[i::shorts_per_long] = (b[:j] >> (bits_per_value * i)) & mask return result def _get_blockdata_v118(self, section, unrecognized_block_types, longarray_unpacker): block_states = section['block_states'] palette = block_states.get('palette') block_states_data = block_states.get('data') if not block_states_data: # This chunk is missing its block data, skip it block_states_data = numpy.zeros((256,), dtype=numpy.uint16) # Translate each entry in the palette to a 1.2-era (block, data) int pair. num_palette_entries = len(palette) translated_blocks = numpy.zeros((num_palette_entries,), dtype=numpy.uint16) # block IDs translated_data = numpy.zeros((num_palette_entries,), dtype=numpy.uint8) # block data for i in range(num_palette_entries): key = palette[i] try: translated_blocks[i], translated_data[i] = self._get_block(key) except KeyError: pass # We already have initialised arrays with 0 (= air) # Turn the BlockStates array into a 16x16x16 numpy matrix of shorts. blocks = numpy.empty((4096,), dtype=numpy.uint16) data = numpy.empty((4096,), dtype=numpy.uint8) block_states = longarray_unpacker(block_states_data, 4096, num_palette_entries) blocks[:] = translated_blocks[block_states] data[:] = translated_data[block_states] # Turn the Data array into a 16x16x16 matrix, same as SkyLight blocks = blocks.reshape((16, 16, 16)) data = data.reshape((16, 16, 16)) return (blocks, data) def _get_blockdata_v113(self, section, unrecognized_block_types, longarray_unpacker): # Translate each entry in the palette to a 1.2-era (block, data) int pair. num_palette_entries = len(section['Palette']) translated_blocks = numpy.zeros((num_palette_entries,), dtype=numpy.uint16) # block IDs translated_data = numpy.zeros((num_palette_entries,), dtype=numpy.uint8) # block data for i in range(num_palette_entries): key = section['Palette'][i] try: translated_blocks[i], translated_data[i] = self._get_block(key) except KeyError: pass # We already have initialised arrays with 0 (= air) # Turn the BlockStates array into a 16x16x16 numpy matrix of shorts. blocks = numpy.empty((4096,), dtype=numpy.uint16) data = numpy.empty((4096,), dtype=numpy.uint8) block_states = longarray_unpacker(section['BlockStates'], 4096, num_palette_entries) blocks[:] = translated_blocks[block_states] data[:] = translated_data[block_states] # Turn the Data array into a 16x16x16 matrix, same as SkyLight blocks = blocks.reshape((16, 16, 16)) data = data.reshape((16, 16, 16)) return (blocks, data) def _get_blockdata_v112(self, section): # Turn the Data array into a 16x16x16 matrix, same as SkyLight data = numpy.frombuffer(section['Data'], dtype=numpy.uint8) data = data.reshape((16,16,8)) data_expanded = numpy.empty((16,16,16), dtype=numpy.uint8) data_expanded[:,:,::2] = data & 0x0F data_expanded[:,:,1::2] = (data & 0xF0) >> 4 # Turn the Blocks array into a 16x16x16 numpy matrix of shorts, # adding in the additional block array if included. blocks = numpy.frombuffer(section['Blocks'], dtype=numpy.uint8) # Cast up to uint16, blocks can have up to 12 bits of data blocks = blocks.astype(numpy.uint16) blocks = blocks.reshape((16,16,16)) if "Add" in section: # This section has additional bits to tack on to the blocks # array. Add is a packed array with 4 bits per slot, so # it needs expanding additional = numpy.frombuffer(section['Add'], dtype=numpy.uint8) additional = additional.astype(numpy.uint16).reshape((16,16,8)) additional_expanded = numpy.empty((16,16,16), dtype=numpy.uint16) additional_expanded[:,:,::2] = (additional & 0x0F) << 8 additional_expanded[:,:,1::2] = (additional & 0xF0) << 4 blocks += additional_expanded del additional del additional_expanded del section['Add'] # Save some memory return (blocks, data_expanded) #@log_other_exceptions def get_chunk(self, x, z): """Returns a dictionary object representing the "Level" NBT Compound structure for a chunk given its x, z coordinates. The coordinates given are chunk coordinates. Raises ChunkDoesntExist exception if the given chunk does not exist. The returned dictionary corresponds to the "Level" structure in the chunk file, with a few changes: * The Biomes array is transformed into a 16x16 numpy array * For each chunk section: * The "Blocks" byte string is transformed into a 16x16x16 numpy array * The Add array, if it exists, is bitshifted left 8 bits and added into the Blocks array * The "SkyLight" byte string is transformed into a 16x16x128 numpy array * The "BlockLight" byte string is transformed into a 16x16x128 numpy array * The "Data" byte string is transformed into a 16x16x128 numpy array Warning: the returned data may be cached and thus should not be modified, lest it affect the return values of future calls for the same chunk. """ regionfile = self._get_region_path(x, z) if regionfile is None: raise ChunkDoesntExist("Chunk %s,%s doesn't exist (and neither does its region)" % (x,z)) # Try a few times to load and parse this chunk before giving up and # raising an error tries = 5 while True: try: region = self._get_regionobj(regionfile) data = region.load_chunk(x, z) except nbt.CorruptionError as e: tries -= 1 if tries > 0: # Flush the region cache to possibly read a new region file header logging.debug("Encountered a corrupt chunk or read error at %s,%s. " "Flushing cache and retrying", x, z) del self.regioncache[regionfile] time.sleep(0.25) continue else: logging.warning("The following was encountered while reading from %s:", self.regiondir) if isinstance(e, nbt.CorruptRegionError): logging.warning("Tried several times to read chunk %d,%d. Its region (%d,%d) may be corrupt. Giving up.", x, z,x//32,z//32) elif isinstance(e, nbt.CorruptChunkError): logging.warning("Tried several times to read chunk %d,%d. It may be corrupt. Giving up.", x, z) else: logging.warning("Tried several times to read chunk %d,%d. Unknown error. Giving up.", x, z) logging.debug("Full traceback:", exc_info=1) # Let this exception propagate out through the C code into # tileset.py, where it is caught and gracefully continues # with the next chunk raise else: # no exception raised: break out of the loop break if data is None: raise ChunkDoesntExist("Chunk %s,%s doesn't exist" % (x,z)) chunk_data = data[1] if chunk_data.get('DataVersion', 0) <= 2840 and 'Level' in chunk_data: # This world was generated pre 21w43a and thus most chunk data is contained # in the "Level" key chunk_data = chunk_data['Level'] else: # This world was (probably) generated post 21w43a chunk_data['Sections'] = chunk_data.get('sections', []) longarray_unpacker = self._packed_longarray_to_shorts if data[1].get('DataVersion', 0) >= 2529: # starting with 1.16 snapshot 20w17a, block states are packed differently longarray_unpacker = self._packed_longarray_to_shorts_v116 # From the interior of a map to the edge, a chunk's status may be one of: # - postprocessed (interior, or next to fullchunk) # - fullchunk (next to decorated) # - decorated (next to liquid_carved) # - liquid_carved (next to carved) # - carved (edge of world) # - empty # Empty is self-explanatory, and liquid_carved and carved seem to correspond # to SkyLight not being calculated, which results in mostly-black chunks, # so we'll just pretend they aren't there. if chunk_data.get("Status", "") not in ("full", "postprocessed", "fullchunk", "mobs_spawned", "spawn", ""): raise ChunkDoesntExist("Chunk %s,%s doesn't exist" % (x,z)) # Turn the Biomes array into a 16x16 numpy array if 'Biomes' in chunk_data and len(chunk_data['Biomes']) > 0: biomes = chunk_data['Biomes'] if isinstance(biomes, bytes): biomes = numpy.frombuffer(biomes, dtype=numpy.uint8) else: biomes = numpy.asarray(biomes) biomes = reshape_biome_data(biomes) else: # Worlds converted by Jeb's program may be missing the Biomes key. # Additionally, 19w09a worlds have an empty array as biomes key # in some cases. # TODO: Implement paletted biomes for >21w39a biomes = numpy.zeros((16, 16), dtype=numpy.uint8) chunk_data['Biomes'] = biomes chunk_data['NewBiomes'] = (len(biomes.shape) == 3) unrecognized_block_types = {} for section in chunk_data['Sections']: # Turn the skylight array into a 16x16x16 matrix. The array comes # packed 2 elements per byte, so we need to expand it. try: # Sometimes, Minecraft loves generating chunks with no light info. # These mostly appear to have those two properties, and in this case # we default to full-bright as it's less jarring to look at than all-black. if chunk_data.get("Status", "") == "spawn" and 'Lights' in chunk_data: section['SkyLight'] = numpy.full((16,16,16), 255, dtype=numpy.uint8) else: if 'SkyLight' in section: skylight = numpy.frombuffer(section['SkyLight'], dtype=numpy.uint8) skylight = skylight.reshape((16,16,8)) else: # Special case introduced with 1.14 skylight = numpy.zeros((16,16,8), dtype=numpy.uint8) skylight_expanded = numpy.empty((16,16,16), dtype=numpy.uint8) skylight_expanded[:,:,::2] = skylight & 0x0F skylight_expanded[:,:,1::2] = (skylight & 0xF0) >> 4 del skylight section['SkyLight'] = skylight_expanded # Turn the BlockLight array into a 16x16x16 matrix, same as SkyLight if 'BlockLight' in section: blocklight = numpy.frombuffer(section['BlockLight'], dtype=numpy.uint8) blocklight = blocklight.reshape((16,16,8)) else: # Special case introduced with 1.14 blocklight = numpy.zeros((16,16,8), dtype=numpy.uint8) blocklight_expanded = numpy.empty((16,16,16), dtype=numpy.uint8) blocklight_expanded[:,:,::2] = blocklight & 0x0F blocklight_expanded[:,:,1::2] = (blocklight & 0xF0) >> 4 del blocklight section['BlockLight'] = blocklight_expanded if 'block_states' in section: (blocks, data) = self._get_blockdata_v118(section, unrecognized_block_types, longarray_unpacker) elif 'Palette' in section: (blocks, data) = self._get_blockdata_v113(section, unrecognized_block_types, longarray_unpacker) elif 'Data' in section: (blocks, data) = self._get_blockdata_v112(section) else: # Special case introduced with 1.14 blocks = numpy.zeros((16,16,16), dtype=numpy.uint16) data = numpy.zeros((16,16,16), dtype=numpy.uint8) (section['Blocks'], section['Data']) = (blocks, data) except ValueError: # iv'e seen at least 1 case where numpy raises a value error during the reshapes. i'm not # sure what's going on here, but let's treat this as a corrupt chunk error logging.warning("There was a problem reading chunk %d,%d. It might be corrupt. I am giving up and will not render this particular chunk.", x, z) logging.debug("Full traceback:", exc_info=1) raise nbt.CorruptChunkError() for k in unrecognized_block_types: logging.debug("Found %d blocks of unknown type %s" % (unrecognized_block_types[k], k)) return chunk_data def iterate_chunks(self): """Returns an iterator over all chunk metadata in this world. Iterates over tuples of integers (x,z,mtime) for each chunk. Other chunk data is not returned here. """ for (regionx, regiony), (regionfile, filemtime) in self.regionfiles.items(): try: mcr = self._get_regionobj(regionfile) except nbt.CorruptRegionError: logging.warning("Found a corrupt region file at %s,%s in %s, Skipping it.", regionx, regiony, self.regiondir) continue for chunkx, chunky in mcr.get_chunks(): yield chunkx+32*regionx, chunky+32*regiony, mcr.get_chunk_timestamp(chunkx, chunky) def iterate_newer_chunks(self, mtime): """Returns an iterator over all chunk metadata in this world. Iterates over tuples of integers (x,z,mtime) for each chunk. Other chunk data is not returned here. """ for (regionx, regiony), (regionfile, filemtime) in self.regionfiles.items(): """ SKIP LOADING A REGION WHICH HAS NOT BEEN MODIFIED! """ if (filemtime < mtime): continue try: mcr = self._get_regionobj(regionfile) except nbt.CorruptRegionError: logging.warning("Found a corrupt region file at %s,%s in %s, Skipping it.", regionx, regiony, self.regiondir) continue for chunkx, chunky in mcr.get_chunks(): yield chunkx+32*regionx, chunky+32*regiony, mcr.get_chunk_timestamp(chunkx, chunky) def get_chunk_mtime(self, x, z): """Returns a chunk's mtime, or False if the chunk does not exist. This is therefore a dual purpose method. It corrects for the given north direction as described in the docs for get_chunk() """ regionfile = self._get_region_path(x,z) if regionfile is None: return None try: data = self._get_regionobj(regionfile) except nbt.CorruptRegionError: logging.warning("Ignoring request for chunk %s,%s; region %s,%s seems to be corrupt", x,z, x//32,z//32) return None if data.chunk_exists(x,z): return data.get_chunk_timestamp(x,z) return None def _get_region_path(self, chunkX, chunkY): """Returns the path to the region that contains chunk (chunkX, chunkY) Coords can be either be global chunk coords, or local to a region """ (regionfile,filemtime) = self.regionfiles.get((chunkX//32, chunkY//32),(None, None)) return regionfile def _iterate_regionfiles(self): """Returns an iterator of all of the region files, along with their coordinates Returns (regionx, regiony, filename)""" logging.debug("regiondir is %s, has type %r", self.regiondir, self.type) for f in os.listdir(self.regiondir): if re.match(r"^r\.-?\d+\.-?\d+\.mca$", f): p = f.split(".") x = int(p[1]) y = int(p[2]) if abs(x) > 500000 or abs(y) > 500000: logging.warning("Holy shit what is up with region file %s in %s !?" % (f, self.regiondir)) yield (x, y, os.path.join(self.regiondir, f)) class RegionSetWrapper(object): """This is the base class for all "wrappers" of RegionSet objects. A wrapper is an object that acts similarly to a subclass: some methods are overridden and functionality is changed, others may not be. The difference here is that these wrappers may wrap each other, forming chains. In fact, subclasses of this object may act exactly as if they've subclassed the original RegionSet object, except the first parameter of the constructor is a regionset object, not a regiondir. This class must implement the full public interface of RegionSet objects """ def __init__(self, rsetobj): self._r = rsetobj @property def regiondir(self): """ RegionSetWrapper are wrappers around a RegionSet and thus should have all variables the RegionSet has. Reason for addition: Issue #1706 The __lt__ check in RegionSet did not check if it is a RegionSetWrapper Instance """ return self._r.regiondir @regiondir.setter def regiondir(self, value): """ For completeness adding the setter to the property """ self._r.regiondir = value def get_type(self): return self._r.get_type() def get_biome_data(self, x, z): return self._r.get_biome_data(x,z) def get_chunk(self, x, z): return self._r.get_chunk(x,z) def iterate_chunks(self): return self._r.iterate_chunks() def iterate_newer_chunks(self,filemtime): return self._r.iterate_newer_chunks(filemtime) def get_chunk_mtime(self, x, z): return self._r.get_chunk_mtime(x,z) # see RegionSet.rotate. These values are chosen so that they can be # passed directly to rot90; this means that they're the number of # times to rotate by 90 degrees CCW UPPER_LEFT = 0 ## - Return the world such that north is down the -Z axis (no rotation) UPPER_RIGHT = 1 ## - Return the world such that north is down the +X axis (rotate 90 degrees counterclockwise) LOWER_RIGHT = 2 ## - Return the world such that north is down the +Z axis (rotate 180 degrees) LOWER_LEFT = 3 ## - Return the world such that north is down the -X axis (rotate 90 degrees clockwise) class RotatedRegionSet(RegionSetWrapper): """A regionset, only rotated such that north points in the given direction """ # some class-level rotation constants _NO_ROTATION = lambda x,z: (x,z) _ROTATE_CLOCKWISE = lambda x,z: (-z,x) _ROTATE_COUNTERCLOCKWISE = lambda x,z: (z,-x) _ROTATE_180 = lambda x,z: (-x,-z) # These take rotated coords and translate into un-rotated coords _unrotation_funcs = [ _NO_ROTATION, _ROTATE_COUNTERCLOCKWISE, _ROTATE_180, _ROTATE_CLOCKWISE, ] # These translate un-rotated coordinates into rotated coordinates _rotation_funcs = [ _NO_ROTATION, _ROTATE_CLOCKWISE, _ROTATE_180, _ROTATE_COUNTERCLOCKWISE, ] def __init__(self, rsetobj, north_dir): self.north_dir = north_dir self.unrotate = self._unrotation_funcs[north_dir] self.rotate = self._rotation_funcs[north_dir] super(RotatedRegionSet, self).__init__(rsetobj) # Re-initialize upon unpickling. This is needed because we store a couple # lambda functions as instance variables def __getstate__(self): return (self._r, self.north_dir) def __setstate__(self, args): self.__init__(args[0], args[1]) def get_chunk(self, x, z): x,z = self.unrotate(x,z) chunk_data = dict(super(RotatedRegionSet, self).get_chunk(x,z)) newsections = [] for section in chunk_data['Sections']: section = dict(section) newsections.append(section) for arrayname in ['Blocks', 'Data', 'SkyLight', 'BlockLight']: array = section[arrayname] # Since the anvil change, arrays are arranged with axes Y,Z,X # numpy.rot90 always rotates the first two axes, so for it to # work, we need to temporarily move the X axis to the 0th axis. array = numpy.swapaxes(array, 0,2) array = numpy.rot90(array, self.north_dir) array = numpy.swapaxes(array, 0,2) section[arrayname] = array chunk_data['Sections'] = newsections if chunk_data['NewBiomes']: array = numpy.swapaxes(chunk_data['Biomes'], 0, 2) array = numpy.rot90(array, self.north_dir) chunk_data['Biomes'] = numpy.swapaxes(array, 0, 2) else: # same as above, for biomes (Z/X indexed) biomes = numpy.swapaxes(chunk_data['Biomes'], 0, 1) biomes = numpy.rot90(biomes, self.north_dir) chunk_data['Biomes'] = numpy.swapaxes(biomes, 0, 1) return chunk_data def get_chunk_mtime(self, x, z): x,z = self.unrotate(x,z) return super(RotatedRegionSet, self).get_chunk_mtime(x, z) def iterate_chunks(self): for x,z,mtime in super(RotatedRegionSet, self).iterate_chunks(): x,z = self.rotate(x,z) yield x,z,mtime def iterate_newer_chunks(self, filemtime): for x,z,mtime in super(RotatedRegionSet, self).iterate_newer_chunks(filemtime): x,z = self.rotate(x,z) yield x,z,mtime class CroppedRegionSet(RegionSetWrapper): def __init__(self, rsetobj, xmin, zmin, xmax, zmax): super(CroppedRegionSet, self).__init__(rsetobj) self.xmin = xmin//16 self.xmax = xmax//16 self.zmin = zmin//16 self.zmax = zmax//16 def get_chunk(self,x,z): if ( self.xmin <= x <= self.xmax and self.zmin <= z <= self.zmax ): return super(CroppedRegionSet, self).get_chunk(x,z) else: raise ChunkDoesntExist("This chunk is out of the requested bounds") def iterate_chunks(self): return ((x,z,mtime) for (x,z,mtime) in super(CroppedRegionSet,self).iterate_chunks() if self.xmin <= x <= self.xmax and self.zmin <= z <= self.zmax ) def iterate_newer_chunks(self, filemtime): return ((x,z,mtime) for (x,z,mtime) in super(CroppedRegionSet,self).iterate_newer_chunks(filemtime) if self.xmin <= x <= self.xmax and self.zmin <= z <= self.zmax ) def get_chunk_mtime(self,x,z): if ( self.xmin <= x <= self.xmax and self.zmin <= z <= self.zmax ): return super(CroppedRegionSet, self).get_chunk_mtime(x,z) else: return None class CachedRegionSet(RegionSetWrapper): """A regionset wrapper that implements caching of the results from get_chunk() """ def __init__(self, rsetobj, cacheobjects): """Initialize this wrapper around the given regionset object and with the given list of cache objects. The cache objects may be shared among other CachedRegionSet objects. """ super(CachedRegionSet, self).__init__(rsetobj) self.caches = cacheobjects # Construct a key from the sequence of transformations and the real # RegionSet object, so that items we place in the cache don't conflict # with other worlds/transformation combinations. obj = self._r s = "" while isinstance(obj, RegionSetWrapper): s += obj.__class__.__name__ + "." obj = obj._r # obj should now be the actual RegionSet object try: s += obj.regiondir except AttributeError: s += repr(obj) logging.debug("Initializing a cache with key '%s'", s) self.key = s def get_chunk(self, x, z): key = (self.key, x, z) for i, cache in enumerate(self.caches): try: retval = cache[key] # This did have it, no need to re-add it to this cache, just # the ones before it i -= 1 break except KeyError: pass else: retval = super(CachedRegionSet, self).get_chunk(x,z) # Now add retval to all the caches that didn't have it, all the caches # up to and including index i for cache in self.caches[:i+1]: cache[key] = retval return retval def get_save_dir(): """Returns the path to the local saves directory * On Windows, at %APPDATA%/.minecraft/saves/ * On Darwin, at $HOME/Library/Application Support/minecraft/saves/ * at $HOME/.minecraft/saves/ """ savepaths = [] if "APPDATA" in os.environ: savepaths += [os.path.join(os.environ['APPDATA'], ".minecraft", "saves")] if "HOME" in os.environ: savepaths += [os.path.join(os.environ['HOME'], "Library", "Application Support", "minecraft", "saves")] savepaths += [os.path.join(os.environ['HOME'], ".minecraft", "saves")] for path in savepaths: if os.path.exists(path): return path def get_worlds(): "Returns {world # or name : level.dat information}" ret = {} save_dir = get_save_dir() # No dirs found - most likely not running from inside minecraft-dir if not save_dir is None: for dir in os.listdir(save_dir): world_path = os.path.join(save_dir, dir) world_dat = os.path.join(world_path, "level.dat") if not os.path.exists(world_dat): continue try: info = nbt.load(world_dat)[1] info['Data']['path'] = os.path.join(save_dir, dir) if 'LevelName' in info['Data'].keys(): ret[info['Data']['LevelName']] = info['Data'] except nbt.CorruptNBTError: ret[os.path.basename(world_path) + " (corrupt)"] = { 'path': world_path, 'LastPlayed': 0, 'Time': 0, 'IsCorrupt': True} for dir in os.listdir("."): world_dat = os.path.join(dir, "level.dat") if not os.path.exists(world_dat): continue world_path = os.path.join(".", dir) try: info = nbt.load(world_dat)[1] info['Data']['path'] = world_path if 'LevelName' in info['Data'].keys(): ret[info['Data']['LevelName']] = info['Data'] except nbt.CorruptNBTError: ret[os.path.basename(world_path) + " (corrupt)"] = {'path': world_path, 'LastPlayed': 0, 'Time': 0, 'IsCorrupt': True} return ret
102,107
Python
.py
1,956
39.867076
213
0.555549
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,282
tileset.py
overviewer_Minecraft-Overviewer/overviewer_core/tileset.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import errno import functools import itertools import logging import os import os.path import platform import random import shutil import stat import sys import time from collections import namedtuple from itertools import chain, product from PIL import Image from . import c_overviewer from . import rendermodes from .c_overviewer import resize_half from . import nbt, world from .files import FileReplacer, get_fs_caps from .optimizeimages import optimize_image from .util import roundrobin """ tileset.py contains the TileSet class, and in general, routines that manage a set of output tiles corresponding to a requested rendermode for a world. In general, there will be one TileSet object per world per rendermode requested by the user. The TileSet class implements the Worker interface. This interface has the following methods: do_preprocessing() This method is called before iterate_work_items(). It should do any work that needs to be done prior to iterate_work_items(). It is not called for instances that will not have iterate_work_items() called. get_num_phases() This method returns an integer indicating how many phases of work this worker has to perform. Each phase of work is completed serially with the other phases... all work done by one phase is done before the next phase is started. get_phase_length(phase) This method returns an integer indicating how many work items there are in this phase. This number is used for purely informational purposes. It can be exact, or an estimate. If there is no useful information on the size of a phase, return None. iterate_work_items(phase) Takes a phase number (a non-negative integer). This method should return an iterator over work items and a list of dependencies i.e. (work_item, [d1, d2, ...]). The work items and dependencies can be any pickelable object; they are treated as opaque by the Dispatcher. The work item objects are passed back in to the do_work() method (perhaps in a different, identically configured instance). The dependency items are other work items that are compared for equality with work items that are already in the queue. The dispatcher guarantees that dependent items which are currently in the queue or in progress finish before the corresponding work item is started. Note that dependencies must have already been yielded as work items before they can be used as dependencies; the dispatcher requires this ordering or it cannot guarantee the dependencies are met. do_work(workobj) Does the work for a given work object. This method is not expected to return anything, so the results of its work should be reflected on the filesystem or by sending signals. """ TILESET_VERSION = 2 # Update this whenever there is a breaking change with tile renders # small but useful def iterate_base4(d): """Iterates over a base 4 number with d digits""" return product(range(4), repeat=d) # A named tuple class storing the row and column bounds for the to-be-rendered # world Bounds = namedtuple("Bounds", ("mincol", "maxcol", "minrow", "maxrow")) # A note about the implementation of the different rendercheck modes: # # For reference, here's what the rendercheck modes are: # 0 # Only render tiles that have chunks with a greater mtime than the last # render timestamp, and their ancestors. # # In other words, only renders parts of the map that have changed since # last render, nothing more, nothing less. # # This is the fastest option, but will not detect tiles that have e.g. # been deleted from the directory tree, or pick up where a partial # interrupted render left off. # 1 # For render-tiles, render all whose chunks have an mtime greater than # the mtime of the tile on disk, and their composite-tile ancestors. # # Also rerender any tiles rendered before forcerendertime. It is nonzero # whenever a mode=2 render has been interrupted. # # Also check all other composite-tiles and render any that have children # with more rencent mtimes than itself. # # This is slower due to stat calls to determine tile mtimes, but safe if # the last render was interrupted. # 2 # Render all tiles unconditionally. This is a "forcerender" and is the # slowest, but SHOULD be specified if this is the first render because # the scan will forgo tile stat calls. It's also useful for changing # texture packs or other options that effect the output. # 3 # A very special mode. Using this will not actually render # anything, but will leave this tileset in the resulting # map. Useful for renders that you want to keep, but not # update. Since this mode is so simple, it's left out of the # rest of this discussion. # # For 0 our caller has explicitly requested not to check mtimes on disk to # speed things up. So the mode 0 chunk scan only looks at chunk mtimes and the # last render mtime from the asset manager, and marks only the tiles that need # rendering based on that. Mode 0 then iterates over all dirty render-tiles # and composite-tiles that depend on them. It does not check mtimes of any # tiles on disk, so this is only a good option if the last render was not # interrupted. # For mode 2, this is a forcerender, the caller has requested we render # everything. The mode 2 chunk scan marks every tile as needing rendering, and # disregards mtimes completely. Mode 2 then iterates over all render-tiles and # composite-tiles that depend on them, which is every tile. It therefore # renders everything. # In both 0 and 2 the render iteration is the same: the dirtytile tree built is # authoritive on every tile that needs rendering. # In mode 1, things are most complicated. Mode 1 chunk scan is identical to a # forcerender, or mode 2 scan: every render tile that should exist is marked in # the dirtytile tree. But instead of iterating over that tree directly, a # special recursive algorithm goes through and checks every tile that should # exist and determines whether it needs rendering. This routine works in such a # way so that every tile is stat()'d at most once, so it shouldn't be too bad. # This logic happens in the iterate_work_items() method, and therefore in the # master process, not the worker processes. # In all three rendercheck modes, the results out of iterate_work_items() is # authoritive on what needs rendering. The do_work() method does not need to do # any additional checks. __all__ = ["TileSet"] class TileSet(object): """The TileSet object manages the work required to produce a set of tiles on disk. It calculates the work that needs to be done and tells the dipatcher (through the Worker interface) this information. The Dispatcher then tells this object when and where to do the work of rendering the tiles. """ def __init__(self, worldobj, regionsetobj, assetmanagerobj, texturesobj, options, outputdir): """Construct a new TileSet object with the given configuration options dictionary. options is a dictionary of configuration parameters (strings mapping to values) that are interpreted by the rendering engine. worldobj is the World object that regionsetobj is from. regionsetobj is the RegionSet object that is used to render the tiles. assetmanagerobj is the AssetManager object that represents the destination directory where we'll put our tiles. texturesobj is the Textures object to pass into the rendering routine. This class does nothing with it except pass it through. outputdir is the absolute path to the tile output directory where the tiles are saved. It is created if it doesn't exist Current valid options for the options dictionary are shown below. All the options must be specified unless they are not relevant. If the given options do not conform to the specifications, behavior is undefined (this class does not do any error checking and assumes items are given in the correct form). bgcolor A hex string specifying the background color for jpeg output. e.g.: "#1A1A1A". Not relevant unless rendering jpeg. renderchecks An integer indicating how to determine which tiles need updating and which don't. This key is optional; if not specified, an appropriate mode is determined from the persistent config obtained from the asset manager. This is one of three levels: 0 Only render tiles that have chunks with a greater mtime than the last render timestamp, and their ancestors. In other words, only renders parts of the map that have changed since last render, nothing more, nothing less. This is the fastest option, but will not detect tiles that have e.g. been deleted from the directory tree, or pick up where a partial interrupted render left off. 1 "check-tiles" mode. For render-tiles, render all whose chunks have an mtime greater than the mtime of the tile on disk, and their upper-tile ancestors. Also check all other upper-tiles and render any that have children with more rencent mtimes than itself. Also remove tiles and directory trees that do exist but shouldn't. This is slower due to stat calls to determine tile mtimes, but safe if the last render was interrupted. 2 Render all tiles unconditionally. This is a "forcerender" and is the slowest, but SHOULD be specified if this is the first render because the scan will forgo tile stat calls. It's also useful for changing texture packs or other options that effect the output. 3 A very special mode. Using this will not actually render anything, but will leave this tileset in the resulting map. Useful for renders that you want to keep, but not update. Since this mode is so simple, it's left out of the rest of this discussion. imgformat A string indicating the output format. Must be one of 'png', 'jpeg' or 'webp' imgquality An integer 1-100 indicating the quality of the jpeg output. Only relevant in jpeg and webp mode. imglossless A boolean indicating whether to save a webp image in lossless mode. optimizeimg A list of optimizer instances to use. rendermode Perhaps the most important/relevant option: a string indicating the render mode to render. This rendermode must have already been registered with the C extension module. rerenderprob A floating point number between 0 and 1 indicating the probability that a tile which is not marked for render by any mtime checks will be rendered anyways. 0 disables this option. changelist Optional: A file descriptor which will be opened and used as the changelist output: each tile written will get outputted to the specified fd. Other options that must be specified but aren't really documented (oops. consider it a TODO): * worldname_orig * dimension * title * name """ self.options = options self.world = worldobj self.regionset = regionsetobj self.am = assetmanagerobj self.textures = texturesobj self.outputdir = os.path.abspath(outputdir) config = self.am.get_tileset_config(self.options.get("name")) self.config = config self.last_rendertime = config.get('last_rendertime', 0) self.forcerendertime = config.get('forcerendertime', 0) self.lastrenderversion = config.get('lastrenderversion', 0) if "renderchecks" not in self.options: # renderchecks was not given, this indicates it was not specified # in either the config file or the command line. The following code # attempts to detect the most appropriate mode if not config: # No persistent config? if os.path.exists(self.outputdir): # Somehow there's no config but the output dir DOES exist. # That's strange! Run forcerender in case of breaking OV version change logging.warning( "For render '%s' I couldn't find any persistent config, " "but I did find my tile directory already exists. This " "shouldn't normally happen, something may be up, but I " "think I can continue...", self.options['name']) logging.info("Switching to --forcerender mode") self.options['renderchecks'] = 2 else: # This is the typical code path for an initial render, make # this a "forcerender" self.options['renderchecks'] = 2 logging.debug("This is the first time rendering %s. Doing " "a full-render", self.options['name']) elif self.lastrenderversion != TILESET_VERSION: # Force render in case there is a version change that is breaking logging.warning("Re-rendering world due to version change." "This will avoid any bad rendering between incompatible versions") self.options['renderchecks'] = 2 elif not os.path.exists(self.outputdir): # Somehow the outputdir got erased but the metadata file is # still there. That's strange! logging.warning( "This is strange. There is metadata for render '%s' but " "the output directory is missing. This shouldn't " "normally happen. I guess we have no choice but to do a " "--forcerender", self.options['name']) self.options['renderchecks'] = 2 elif config.get("render_in_progress", False): # The last render must have been interrupted. The default should be # a check-tiles render then logging.warning( "The last render for '%s' didn't finish. I'll be " "scanning all the tiles to make sure everything's up " "to date.", self.options['name']) logging.warning( "The total tile count will be (possibly " "wildly) inaccurate, because I don't know how many " "tiles need rendering. I'll be checking them as I go.") if self.forcerendertime != 0: logging.info( "The unfinished render was a --forcerender. " "Rerendering any tiles older than %s.", time.strftime("%x %X", time.localtime(self.forcerendertime))) self.options['renderchecks'] = 1 else: logging.debug( "No rendercheck mode specified for %s. " "Rendering tile whose chunks have changed since %s.", self.options['name'], time.strftime("%x %X", time.localtime(self.last_rendertime))) self.options['renderchecks'] = 0 if not os.path.exists(self.outputdir): if self.options['renderchecks'] != 2: logging.warning( "The tile directory didn't exist, but you have specified " "explicitly not to do a --fullrender (which is the default for " "this situation). I'm overriding your decision and setting " "--fullrender for just this run.") self.options['renderchecks'] = 2 os.mkdir(self.outputdir) if self.lastrenderversion != TILESET_VERSION and self.options['renderchecks'] not in [2, 3]: logging.warning("Normally renders from different versions should be" "overridden or ignored to prevent incompatibilities," "but we will honor your decision.") # must wait until outputdir exists self.fs_caps = get_fs_caps(self.outputdir) if self.options['renderchecks'] == 2: # Set forcerendertime so that upon an interruption the next render # will continue where we left off. self.forcerendertime = int(time.time()) # Set the image format according to the options if self.options['imgformat'] == 'png': self.imgextension = 'png' elif self.options['imgformat'] in ('jpeg', 'jpg'): self.imgextension = 'jpg' elif self.options['imgformat'] == 'webp': self.imgextension = 'webp' else: raise ValueError("imgformat must be one of: 'png', 'jpg' or 'webp'") # This sets self.treedepth, self.xradius, and self.yradius self._set_map_size() # Only pickle the initial state. Don't pickle anything resulting from the # do_preprocessing step def __getstate__(self): return self.world, self.regionset, self.am, self.textures, self.options, self.outputdir def __setstate__(self, state): self.__init__(*state) def do_preprocessing(self): """For the preprocessing step of the Worker interface, this does the chunk scan and stores the resulting tree as a private instance attribute for later use in iterate_work_items() """ # skip if we're told to if self.options['renderchecks'] == 3: return # REMEMBER THAT ATTRIBUTES ASSIGNED IN THIS METHOD ARE NOT AVAILABLE IN # THE do_work() METHOD (because this is only called in the main process # not the workers) # This warning goes here so it's only shown once if self.treedepth >= 15: logging.warning( "Just letting you know, your map requires %s " "zoom levels. This is REALLY big!", self.treedepth) # Do any tile re-arranging if necessary. Skip if there was no config # from the asset-manager, which typically indicates this is a new # render if self.config: self._rearrange_tiles() # Do the chunk scan here self.dirtytree = self._chunk_scan() def get_num_phases(self): """Returns the number of levels in the quadtree, which is equal to the number of phases of work that need to be done. """ return 1 def get_phase_length(self, phase): """Returns the number of work items in a given phase. """ # Yeah functional programming! # and by functional we mean a bastardized python switch statement return { 0: lambda: self.dirtytree.count_all(), # there is no good way to guess this so just give total count 1: lambda: (4**(self.treedepth + 1) - 1) / 3, 2: lambda: self.dirtytree.count_all(), 3: lambda: 0, }[self.options['renderchecks']]() def iterate_work_items(self, phase): """Iterates over the dirty tiles in the tree and return them in the appropriate order with the appropriate dependencies. This method returns an iterator over (obj, [dependencies, ...]) """ # skip if asked to if self.options['renderchecks'] == 3: return # The following block of code implementes the changelist functionality. fd = self.options.get("changelist", None) if fd: logging.debug("Changelist activated for %s (fileno %s)", self, fd) # This re-implements some of the logic from do_work() def write_out(tilepath): if len(tilepath) == self.treedepth: rt = RenderTile.from_path(tilepath) imgpath = rt.get_filepath(self.outputdir, self.imgextension) elif len(tilepath) == 0: imgpath = os.path.join(self.outputdir, "base." + self.imgextension) else: dest = os.path.join(self.outputdir, *(str(x) for x in tilepath[:-1])) name = str(tilepath[-1]) imgpath = os.path.join(dest, name) + "." + self.imgextension # We use low-level file output because we don't want open file # handles being passed to subprocesses. fd is just an integer. # This method is only called from the master process anyways. # We don't use os.fdopen() because this fd may be shared by # many tileset objects, and as soon as this method exists the # file object may be garbage collected, closing the file. os.write(fd, (imgpath + "\n").encode()) # See note at the top of this file about the rendercheck modes for an # explanation of what this method does in different situations. # # For modes 0 and 2, self.dirtytree holds exactly the tiles we need to # render. Iterate over the tiles in using the posttraversal() method. # Yield each item. Easy. if self.options['renderchecks'] in (0, 2): for tilepath in self.dirtytree.posttraversal(robin=True): dependencies = [] # These tiles may or may not exist, but the dispatcher won't # care according to the worker interface protocol It will only # wait for the items that do exist and are in the queue. for i in range(4): dependencies.append(tilepath + (i,)) if fd: write_out(tilepath) yield tilepath, dependencies else: # For mode 1, self.dirtytree holds every tile that should exist, # but invoke _iterate_and_check_tiles() to determine which tiles # need rendering. for tilepath, mtime, needs_rendering in self._iterate_and_check_tiles(()): if needs_rendering: dependencies = [] for i in range(4): dependencies.append(tilepath + (i,)) if fd: write_out(tilepath) yield tilepath, dependencies def do_work(self, tilepath): """Renders the given tile. tilepath is yielded by iterate_work_items and is an iterable of integers representing the path of the tile to render. """ if len(tilepath) == self.treedepth: # A render-tile self._render_rendertile(RenderTile.from_path(tilepath)) else: # A composite-tile if len(tilepath) == 0: # The base tile dest = self.outputdir name = "base" else: # All others dest = os.path.join(self.outputdir, *(str(x) for x in tilepath[:-1])) name = str(tilepath[-1]) self._render_compositetile(dest, name) def get_initial_data(self): """This is called similarly to get_persistent_data, but is called after do_preprocessing but before any work is acutally done. """ d = self.get_persistent_data() # This is basically the same as get_persistent_data() with the # following exceptions: # * last_rendertime is not changed # * A key "render_in_progress" is set to True # * forcerendertime is set so that an interrupted mode=2 render will # finish properly. d['last_rendertime'] = self.last_rendertime d['render_in_progress'] = True d['forcerendertime'] = self.forcerendertime return d def get_persistent_data(self): """Returns a dictionary representing the persistent data of this TileSet. Typically this is called by AssetManager """ def bgcolorformat(color): return "#%02x%02x%02x" % color[0:3] isOverlay = self.options.get("overlay") or \ (not any(isinstance(x, rendermodes.Base) for x in self.options.get("rendermode"))) # don't update last render time if we're leaving this alone last_rendertime = self.last_rendertime if self.options['renderchecks'] != 3: last_rendertime = self.max_chunk_mtime d = dict( name=self.options.get('title'), zoomLevels=self.treedepth, defaultZoom=self.options.get('defaultzoom'), maxZoom=None, path=self.options.get('name'), base=self.options.get('base'), bgcolor=bgcolorformat(self.options.get('bgcolor')), world=None, last_rendertime=last_rendertime, imgextension=self.imgextension, isOverlay=isOverlay, poititle=self.options.get("poititle"), showlocationmarker=self.options.get("showlocationmarker"), center=(self.options.get("center") or self.options.get("spawn") or [0, 64, 0]), lastrenderversion=TILESET_VERSION ) d['maxZoom'] = self.options.get('maxzoom', self.treedepth) if d['maxZoom'] < 0: d['maxZoom'] = self.treedepth + self.options.get('maxzoom') d['world'] = self.options.get('worldname_orig') if self.options.get('dimension')[1] != 0: d['world'] += " - " + self.options.get('dimension')[0] d['maxZoom'] = min(self.treedepth, d['maxZoom']) d['minZoom'] = min(max(0, self.options.get("minzoom", 0)), d['maxZoom']) d['defaultZoom'] = max(d['minZoom'], min(d['defaultZoom'], d['maxZoom'])) if isOverlay: d.update({"tilesets": self.options.get("overlay")}) # None means overworld if (self.regionset.get_type() is None and self.options.get("showspawn", True)): d.update({"spawn": self.options.get("spawn")}) else: d.update({"spawn": False}) try: d['north_direction'] = self.regionset.north_dir except AttributeError: d['north_direction'] = 0 return d def _find_chunk_range(self): """Finds the chunk range in rows/columns and stores them in self.minrow, self.maxrow, self.mincol, self.maxcol """ minrow = mincol = maxrow = maxcol = 0 for c_x, c_z, _ in self.regionset.iterate_chunks(): # Convert these coordinates to row/col col, row = convert_coords(c_x, c_z) minrow = min(minrow, row) maxrow = max(maxrow, row) mincol = min(mincol, col) maxcol = max(maxcol, col) return Bounds(mincol, maxcol, minrow, maxrow) def _set_map_size(self): """Finds and sets the depth of the map's quadtree, as well as the xradius and yradius of the resulting tiles. Sets self.treedepth, self.xradius, self.yradius """ # Calculate the min and max column over all the chunks. # This returns a Bounds namedtuple bounds = self._find_chunk_range() # Calculate the depth of the tree for p in range(2, 33): # max 32 # Will 2^p tiles wide and high suffice? # X has twice as many chunks as tiles, then halved since this is a # radius xradius = 2**p # Y has 4 times as many chunks as tiles, then halved since this is # a radius yradius = 2 * 2**p # The +32 on the y bounds is because chunks are very tall, and in # rare cases when the bottom of the map is close to a border, it # could get cut off if xradius >= bounds.maxcol and -xradius <= bounds.mincol and \ yradius >= bounds.maxrow + 32 and -yradius <= bounds.minrow: break self.treedepth = p self.xradius = xradius self.yradius = yradius def _rearrange_tiles(self): """If the target size of the tree is not the same as the existing size on disk, do some re-arranging """ try: curdepth = self.config['zoomLevels'] except KeyError: return if curdepth == 1: # Skip a depth 1 tree. A depth 1 tree pretty much can't happen, so # when we detect this it usually means the tree is actually empty return logging.debug( "Current tree depth for %s is reportedly %s. Target tree depth is %s.", self.options['name'], curdepth, self.treedepth) if self.treedepth != curdepth: if self.treedepth > curdepth: logging.warning("Your map seems to have expanded beyond its previous bounds.") logging.warning("Doing some tile re-arrangements... just a sec...") for _ in range(self.treedepth - curdepth): self._increase_depth() elif self.treedepth < curdepth: logging.warning( "Your map seems to have shrunk. Did you delete some " "chunks? No problem. Re-arranging tiles, just a sec...") for _ in range(curdepth - self.treedepth): self._decrease_depth() logging.info( "There, done. I'm switching to --check-tiles mode for " "this one render. This will make sure any old tiles that " "should no longer exist are deleted.") self.options['renderchecks'] = 1 def _increase_depth(self): """Moves existing tiles into place for a larger tree""" getpath = functools.partial(os.path.join, self.outputdir) # At top level of the tree: # quadrant 0 is now 0/3 # 1 is now 1/2 # 2 is now 2/1 # 3 is now 3/0 # then all that needs to be done is to regenerate the new top level def rollback_mkdir(dnum): p = getpath("new" + str(dnum)) if os.path.exists(p): os.rmdir(p) def rollback_filerename(dnum): newnum = (3, 2, 1, 0)[dnum] qimg = getpath("new%d/%d.%s" % (dnum, newnum, self.imgextension)) qdir = getpath("new%d/%d" % (dnum, newnum)) if os.path.exists(qimg): os.rename(qimg, getpath("%d.%s" % (dnum, self.imgextension))) if os.path.exists(qdir): os.rename(qdir, getpath(str(dnum))) def rollback_dirrename(dnum): os.rename(getpath(str(dnum)), getpath("new" + str(dnum))) for dirnum in range(4): newnum = (3, 2, 1, 0)[dirnum] newdir = "new" + str(dirnum) newdirpath = getpath(newdir) files = [str(dirnum) + "." + self.imgextension, str(dirnum)] newfiles = [str(newnum) + "." + self.imgextension, str(newnum)] try: try: os.mkdir(newdirpath) try: for f, newf in zip(files, newfiles): p = getpath(f) if os.path.exists(p): os.rename(p, getpath(newdir, newf)) # We're catching BaseException here since we'll also want to do this on # exit. except BaseException: rollback_filerename(dirnum) raise except BaseException: rollback_mkdir(dirnum) raise os.rename(newdirpath, getpath(str(dirnum))) except BaseException: logging.warning("Overviewer was interrupted during tile " "re-arrangement.") logging.warning("Rolling back changes...") # Moonwalk the fuck out of here for lastdir in range(dirnum - 1, -1, -1): rollback_dirrename(lastdir) rollback_filerename(lastdir) rollback_mkdir(lastdir) raise def _decrease_depth(self): """If the map size decreases, or perhaps the user has a depth override in effect, re-arrange existing tiles for a smaller tree""" getpath = functools.partial(os.path.join, self.outputdir) # quadrant 0/3 goes to 0 # 1/2 goes to 1 # 2/1 goes to 2 # 3/0 goes to 3 # Just worry about the directories here, the files at the top two # levels are cheap enough to replace if os.path.exists(getpath("0", "3")): os.rename(getpath("0", "3"), getpath("new0")) shutil.rmtree(getpath("0")) os.rename(getpath("new0"), getpath("0")) if os.path.exists(getpath("1", "2")): os.rename(getpath("1", "2"), getpath("new1")) shutil.rmtree(getpath("1")) os.rename(getpath("new1"), getpath("1")) if os.path.exists(getpath("2", "1")): os.rename(getpath("2", "1"), getpath("new2")) shutil.rmtree(getpath("2")) os.rename(getpath("new2"), getpath("2")) if os.path.exists(getpath("3", "0")): os.rename(getpath("3", "0"), getpath("new3")) shutil.rmtree(getpath("3")) os.rename(getpath("new3"), getpath("3")) # Delete the files in the top directory to make sure they get re-created. files = [str(num) + "." + self.imgextension for num in range(4)] + \ ["base." + self.imgextension] for f in files: try: os.unlink(getpath(f)) except OSError as e: # Ignore file doesn't exist errors if e.errno != errno.ENOENT: raise def _chunk_scan(self): """Scans the chunks of this TileSet's world to determine which render-tiles need rendering. Returns a RendertileSet object. For rendercheck mode 0: only compares chunk mtimes against last render time of the map, and marks tiles as dirty if any chunk has a greater mtime than the last render time. For rendercheck modes 1 and 2: marks every tile in the tileset unconditionally, does not check any mtimes. As a side-effect, the scan sets self.max_chunk_mtime to the max of all the chunks' mtimes """ # See note at the top of this file about the rendercheck modes for an # explanation of what this method does in different situations. # Local vars for slightly faster lookups depth = self.treedepth xradius = self.xradius yradius = self.yradius dirty = RendertileSet(depth) chunkcount = 0 stime = time.time() rendercheck = self.options['renderchecks'] markall = rendercheck in (1, 2) rerender_prob = self.options['rerenderprob'] last_rendertime = self.last_rendertime max_chunk_mtime = 0 # For each chunk, do this: # For each tile that the chunk touches, do this: # Compare the last modified time of the chunk and tile. If the # tile is older, mark it in a RendertileSet object as dirty. for chunkx, chunkz, chunkmtime in self.regionset.iterate_chunks() \ if (markall or platform.system() == 'Windows') \ else self.regionset.iterate_newer_chunks(last_rendertime): chunkcount += 1 if chunkmtime > max_chunk_mtime: max_chunk_mtime = chunkmtime # Convert to diagonal coordinates chunkcol, chunkrow = convert_coords(chunkx, chunkz) for c, r in get_tiles_by_chunk(chunkcol, chunkrow): # Make sure the tile is in the boundary we're rendering. # This can happen when rendering at lower treedepth than # can contain the entire map, but shouldn't happen if the # treedepth is correctly calculated. if ( c < -xradius or c >= xradius or r < -yradius or r >= yradius): continue # Computes the path in the quadtree from the col,row coordinates tile = RenderTile.compute_path(c, r, depth) if markall: # markall mode: Skip all other checks, mark tiles # as dirty unconditionally dirty.add(tile.path) continue # Check if this tile has already been marked dirty. If so, # no need to do any of the below. if dirty.query_path(tile.path): continue # Stochastic check. Since we're scanning by chunks and not # by tiles, and the tiles get checked multiple times for # each chunk, this is only an approximation. The given # probability is for a particular tile that needs # rendering, but since a tile gets touched up to 32 times # (once for each chunk in it), divide the probability by # 32. if rerender_prob and rerender_prob / 32 > random.random(): dirty.add(tile.path) continue # Check mtimes and conditionally add tile to the set if chunkmtime > last_rendertime: dirty.add(tile.path) t = int(time.time() - stime) logging.debug( "Finished chunk scan for %s. %s chunks scanned in %s second%s.", self.options['name'], chunkcount, t, "s" if t != 1 else "") self.max_chunk_mtime = max_chunk_mtime return dirty def __str__(self): return "<TileSet for %s>" % os.path.basename(self.outputdir) def _render_compositetile(self, dest, name): """ Renders a tile at os.path.join(dest, name)+".ext" by taking tiles from os.path.join(dest, name, "{0,1,2,3}.png") If name is "base" then render tile at os.path.join(dest, "base.png") by taking tiles from os.path.join(dest, "{0,1,2,3}.png") """ imgformat = self.imgextension imgpath = os.path.join(dest, name) + "." + imgformat if name == "base": # Special case for the base tile. Its children are in the same # directory instead of in a sub-directory quadPath = [ ((0, 0), os.path.join(dest, "0." + imgformat)), ((192, 0), os.path.join(dest, "1." + imgformat)), ((0, 192), os.path.join(dest, "2." + imgformat)), ((192, 192), os.path.join(dest, "3." + imgformat)), ] else: quadPath = [ ((0, 0), os.path.join(dest, name, "0." + imgformat)), ((192, 0), os.path.join(dest, name, "1." + imgformat)), ((0, 192), os.path.join(dest, name, "2." + imgformat)), ((192, 192), os.path.join(dest, name, "3." + imgformat)), ] # Check each of the 4 child tiles, getting their existance and mtime # infomation. Also keep track of the max mtime of all children max_mtime = 0 quadPath_filtered = [] for path in quadPath: try: quad_mtime = os.stat(path[1])[stat.ST_MTIME] except OSError: # This tile doesn't exist or some other error with the stat # call. Move on. continue # The tile exists, so we need to use it in our rendering of this # composite tile quadPath_filtered.append(path) if quad_mtime > max_mtime: max_mtime = quad_mtime # If no children exist, delete this tile if not quadPath_filtered: try: os.unlink(imgpath) except OSError as e: # Ignore errors if it's "file doesn't exist" if e.errno != errno.ENOENT: raise logging.warning( "Tile %s was requested for render, but no children were found! " "This is probably a bug.", imgpath) return # Create the actual image now img = Image.new("RGBA", (384, 384), self.options['bgcolor']) # We'll use paste (NOT alpha_over) for quadtree generation because # this is just straight image stitching, not alpha blending for path in quadPath_filtered: try: src = Image.open(path[1]) # optimizeimg may have converted them to a palette image in the meantime if src.mode != "RGB" and src.mode != "RGBA": src = src.convert("RGBA") src.load() quad = Image.new("RGBA", (192, 192), self.options['bgcolor']) resize_half(quad, src) img.paste(quad, path[0]) except Exception as e: logging.warning("Couldn't open %s. It may be corrupt. Error was '%s'.", path[1], e) logging.warning( "I'm going to try and delete it. You will need to run " "the render again and with --check-tiles.") try: os.unlink(path[1]) except Exception as e: logging.error( "While attempting to delete corrupt image %s, an error was encountered. " "You will need to delete it yourself. Error was '%s'", path[1], e) # Save it with FileReplacer(imgpath, capabilities=self.fs_caps) as tmppath: if imgformat == 'jpg': img.convert('RGB').save(tmppath, "jpeg", quality=self.options['imgquality'], subsampling=0) elif imgformat == 'png': # PNG img.save(tmppath, "png") elif imgformat == 'webp': img.save(tmppath, "webp", quality=self.options['imgquality'], lossless=self.options['imglossless']) if self.options['optimizeimg']: optimize_image(tmppath, imgformat, self.options['optimizeimg']) try: os.utime(tmppath, (max_mtime, max_mtime)) except OSError as e: # Ignore errno ENOENT: file does not exist. Due to a race # condition, two processes could conceivably try and update # the same temp file at the same time if e.errno != errno.ENOENT: raise def _render_rendertile(self, tile): """Renders the given render-tile. This function is called from the public do_work() method in the child process. The tile is assumed to need rendering and is rendered unconditionally. The argument is a RenderTile object The image is rendered and saved to disk in the place this tileset is configured to save images. """ imgpath = tile.get_filepath(self.outputdir, self.imgextension) # Calculate which chunks are relevant to this tile # This is a list of (col, row, chunkx, chunkz, chunk_mtime) chunks = list(get_chunks_by_tile(tile, self.regionset)) if not chunks: # No chunks were found in this tile logging.warning("%s was requested for render, but no chunks found! " "This may be a bug.", tile) try: os.unlink(imgpath) except OSError as e: # ignore only if the error was "file not found" if e.errno != errno.ENOENT: raise else: logging.debug("%s deleted", tile) return # Create the directory if not exists dirdest = os.path.dirname(imgpath) if not os.path.exists(dirdest): try: os.makedirs(dirdest) except OSError as e: # Ignore errno EEXIST: file exists. Due to a race condition, # two processes could conceivably try and create the same # directory at the same time if e.errno != errno.EEXIST: raise # Compile this image tileimg = Image.new("RGBA", (384, 384), self.options['bgcolor']) colstart = tile.col rowstart = tile.row # col colstart will get drawn on the image starting at x coordinates -(384/2) # row rowstart will get drawn on the image starting at y coordinates -(192/2) max_chunk_mtime = 0 for col, row, chunkx, chunky, chunkz, chunk_mtime in chunks: xpos = -192 + (col - colstart) * 192 ypos = -96 + (row - rowstart) * 96 + (24 - 1 - chunky) * 192 if chunk_mtime > max_chunk_mtime: max_chunk_mtime = chunk_mtime # draw the chunk! try: c_overviewer.render_loop( self.world, self.regionset, chunkx, chunky, chunkz, tileimg, xpos, ypos, self.options['rendermode'], self.textures) except nbt.CorruptionError: # A warning and traceback was already printed by world.py's # get_chunk() logging.debug("Skipping the render of corrupt chunk at %s,%s " "and moving on.", chunkx, chunkz) except world.ChunkDoesntExist: # Some chunks are present on disk but not fully initialized. # This is okay. pass except Exception as e: logging.error("Could not render chunk %s,%s for some reason. " "This is likely a render primitive option error.", chunkx, chunkz) logging.error("Full error was:", exc_info=1) sys.exit(1) # Save them with FileReplacer(imgpath, capabilities=self.fs_caps) as tmppath: if self.imgextension == 'jpg': tileimg.convert('RGB').save(tmppath, "jpeg", quality=self.options['imgquality'], subsampling=0) elif self.imgextension == 'png': # PNG tileimg.save(tmppath, "png") elif self.imgextension == 'webp': tileimg.save(tmppath, "webp", quality=self.options['imgquality'], lossless=self.options['imglossless']) if self.options['optimizeimg']: optimize_image(tmppath, self.imgextension, self.options['optimizeimg']) os.utime(tmppath, (max_chunk_mtime, max_chunk_mtime)) def _iterate_and_check_tiles(self, path): """A generator function over all tiles that should exist in the subtree identified by path. This yields, in order, all tiles that need rendering in a post-traversal order, including this node itself. This method takes one parameter: path The path of a tile that should exist This method yields tuples in this form: (path, mtime, needs_rendering) path is the path tuple of the tile that needs rendering mtime if the tile does not need rendering, the parent call determines if it should render itself by comparing its own mtime to the child mtimes. This should be set to the tile's mtime in the event that the tile does not need rendering, or None otherwise. needs_rendering is a boolean indicating this tile does in fact need rendering. (Since this is a recursive generator, tiles that don't need rendering are not propagated all the way out of the recursive stack, but are still yielded to the immediate parent because it needs to know its childs' mtimes) """ if len(path) == self.treedepth: # Base case: a render-tile. # Render this tile if any of its chunks are greater than its mtime tileobj = RenderTile.from_path(path) imgpath = tileobj.get_filepath(self.outputdir, self.imgextension) try: tile_mtime = os.stat(imgpath)[stat.ST_MTIME] except OSError as e: if e.errno != errno.ENOENT: raise tile_mtime = 0 try: max_chunk_mtime = max(c[5] for c in get_chunks_by_tile(tileobj, self.regionset)) except ValueError: # max got an empty sequence! something went horribly wrong logging.warning("tile %s expected contains no chunks! this may be a bug", path) max_chunk_mtime = 0 if tile_mtime > 120 + max_chunk_mtime: # If a tile has been modified more recently than any of its # chunks, then this could indicate a potential issue with # this or future renders. logging.warning( "I found a tile with a more recent modification time " "than any of its chunks. This can happen when a tile has " "been modified with an outside program, or by a copy " "utility that doesn't preserve mtimes. Overviewer uses " "the filesystem's mtimes to determine which tiles need " "rendering and which don't, so it's important to " "preserve the mtimes Overviewer sets. Please see our FAQ " "page on docs.overviewer.org or ask us in IRC for more " "information.") logging.warning("Tile was: %s", imgpath) if max_chunk_mtime > tile_mtime or tile_mtime < self.forcerendertime: # chunks have a more recent mtime than the tile or the tile has # an older mtime than the forcerendertime from an interrupted # render. Render the tile. yield (path, None, True) else: # This doesn't need rendering. Return mtime to parent in case # its mtime is less, indicating the parent DOES need a render yield path, max_chunk_mtime, False else: # A composite-tile. render_me = False max_child_mtime = 0 # First, recurse to each of our children for childnum in range(4): childpath = path + (childnum,) # Check if this sub-tree should actually exist, so that we only # end up checking tiles that actually exist if not self.dirtytree.query_path(childpath): # Here check if it *does* exist, and if so, nuke it. self._nuke_path(childpath) continue for child_path, child_mtime, child_needs_rendering in \ self._iterate_and_check_tiles(childpath): if len(child_path) == len(path) + 1: # Do these checks for our immediate children if child_needs_rendering: render_me = True elif child_mtime > max_child_mtime: max_child_mtime = child_mtime # Pass this on up and out. # Optimization: if it does not need rendering, we don't # need to pass it any further. A tile that doesn't need # rendering is only relevant to its immediate parent, and # only for its mtime information. if child_needs_rendering: yield child_path, child_mtime, child_needs_rendering # Now that we're done with our children and descendents, see if # this tile needs rendering if render_me: # yes. yes we do. This is set when one of our children needs # rendering yield path, None, True else: # Check this tile's mtime imgpath = os.path.join(self.outputdir, *(str(x) for x in path)) imgpath += "." + self.imgextension logging.debug("Testing mtime for composite-tile %s", imgpath) try: tile_mtime = os.stat(imgpath)[stat.ST_MTIME] except OSError as e: if e.errno != errno.ENOENT: raise tile_mtime = 0 if tile_mtime < max_child_mtime: # If any child was updated more recently than ourself, then # we need rendering yield path, None, True else: # Nope. yield path, max_child_mtime, False def _nuke_path(self, path): """Given a quadtree path, erase it from disk. This is called by _iterate_and_check_tiles() as a helper-method. """ if len(path) == self.treedepth: # path referrs to a single tile tileobj = RenderTile.from_path(path) imgpath = tileobj.get_filepath(self.outputdir, self.imgextension) if os.path.exists(imgpath): # No need to catch ENOENT since this is only called from the # master process logging.debug("Found an image that shouldn't exist. Deleting it: %s", imgpath) os.remove(imgpath) else: # path referrs to a composite tile, and by extension a directory dirpath = os.path.join(self.outputdir, *(str(x) for x in path)) imgpath = dirpath + "." + self.imgextension if os.path.exists(imgpath): logging.debug("Found an image that shouldn't exist. Deleting it: %s", imgpath) os.remove(imgpath) if os.path.exists(dirpath): logging.debug("Found a subtree that shouldn't exist. Deleting it: %s", dirpath) shutil.rmtree(dirpath) # # Functions for converting (x, z) to (col, row) and back # def convert_coords(chunkx, chunkz): """Takes a coordinate (chunkx, chunkz) where chunkx and chunkz are in the chunk coordinate system, and figures out the row and column in the image each one should be. Returns (col, row).""" # columns are determined by the sum of the chunk coords, rows are the # difference # change this function, and you MUST change unconvert_coords return (chunkx + chunkz, chunkz - chunkx) def unconvert_coords(col, row): """Undoes what convert_coords does. Returns (chunkx, chunkz).""" # col + row = chunkz + chunkz => (col + row)/2 = chunkz # col - row = chunkx + chunkx => (col - row)/2 = chunkx return ((col - row) // 2, (col + row) // 2) ###################### # The following two functions define the mapping from chunks to tiles and back. # The mapping from chunks to tiles (get_tiles_by_chunk()) is used during the # chunk scan to determine which tiles need updating, while the mapping from a # tile to chunks (get_chunks_by_tile()) is used by the tile rendering routines # to get which chunks are needed. def get_tiles_by_chunk(chunkcol, chunkrow): """For the given chunk, returns an iterator over Render Tiles that this chunk touches. Iterates over (tilecol, tilerow) """ # find tile coordinates. Remember tiles are identified by the # address of the chunk in their upper left corner. tilecol = chunkcol - chunkcol % 2 tilerow = chunkrow - chunkrow % 4 # If this chunk is in an /even/ column, then it spans two tiles. if chunkcol % 2 == 0: colrange = (tilecol - 2, tilecol) else: colrange = (tilecol,) # If this chunk is in a row divisible by 4, then it touches the # tile above it as well. Also touches the next 6 tiles down (24 # rows) if chunkrow % 4 == 0: rowrange = range(tilerow - 4, tilerow + 48 + 1, 4) else: rowrange = range(tilerow, tilerow + 48 + 1, 4) return product(colrange, rowrange) def get_chunks_by_tile(tile, regionset): """Get chunk sections that are relevant to the given render-tile. Only returns chunk sections that are in chunks that actually exist according to the given regionset object. (Does not check to see if the chunk section itself within the chunk exists) This function is expected to return the chunk sections in the correct order for rendering, i.e. back to front. Returns an iterator over chunks tuples where each item is (col, row, chunkx, chunky, chunkz, mtime) """ # This is not a documented usage of this function and is used only for # debugging if regionset is None: def get_mtime(x, y): return True else: get_mtime = regionset.get_chunk_mtime # Each tile has two even columns and an odd column of chunks. # First do the odd. For each chunk in the tile's odd column the tile # "passes through" three chunk sections. oddcol_sections = [] for i, y in enumerate(reversed(range(24))): for row in range(tile.row + 3 - i * 2, tile.row - 2 - i * 2, -2): oddcol_sections.append((tile.col + 1, row, y)) evencol_sections = [] for i, y in enumerate(reversed(range(24))): for row in range(tile.row + 4 - i * 2, tile.row - 3 - i * 2, -2): evencol_sections.append((tile.col + 2, row, y)) evencol_sections.append((tile.col, row, y)) eveniter = reversed(evencol_sections) odditer = reversed(oddcol_sections) # There are 4 rows of chunk sections per Y value on even columns, but 3 # rows on odd columns. This iteration order yields them in back-to-front # order appropriate for rendering for col, row, y in roundrobin(( eveniter, eveniter, odditer, eveniter, eveniter, odditer, eveniter, eveniter, odditer, eveniter, eveniter,)): chunkx, chunkz = unconvert_coords(col, row) mtime = get_mtime(chunkx, chunkz) if mtime: yield (col, row, chunkx, y, chunkz, mtime) class RendertileSet(object): """This object holds a set of render-tiles using a quadtree data structure. It is typically used to hold tiles that need rendering. This implementation collapses subtrees that are completely in or out of the set to save memory. An instance of this class holds a full tree. The instance knows its "level", which corresponds to the zoom level where 1 is the inner-most (most zoomed in) tiles. Instances hold the state of their children (in or out of the set). Leaf nodes are images and do not physically exist in the tree as objects, but are represented as booleans held by the objects at the second-to-last level; level 1 nodes keep track of leaf image state. Level 2 nodes keep track of level 1 state, and so forth. """ __slots__ = ("depth", "children", "num_tiles", "num_tiles_all") def __init__(self, depth): """Initialize a new tree with the specified depth. This actually initializes a node, which is the root of a subtree, with `depth` levels beneath it. """ # Stores the depth of the tree according to this node. This is not the # depth of this node, but rather the number of levels below this node # (including this node). self.depth = depth # the self.children array holds the 4 children of this node. This # follows the same quadtree convention as elsewhere: children 0, 1, 2, # 3 are the upper-left, upper-right, lower-left, and lower-right # respectively # Values are: # False # All children down this subtree are not in the set # True # All children down this subtree are in the set # An array of the same format # The array defines which children down that subtree are in the set # A node with depth=1 cannot have a RendertileSet instance in its # children since its children are leaves, representing images, not more # tree self.children = [False] * 4 self.num_tiles = 0 self.num_tiles_all = 0 def add(self, path): """Marks the requested leaf node as in this set Path is an iterable of integers representing the path to the leaf node that is to be added to the set """ path = list(path) assert len(path) == self.depth if self.num_tiles == 0: # The first child is being added. A root composite tile will be # rendered. self.num_tiles_all += 1 self._add_helper(self.children, list(reversed(path))) def _add_helper(self, children, path): """Recursive helper for add() """ childnum = path.pop() if path: # We are not at the leaf, recurse. # Don't try to make this "prettier" by getting rid of is True and replacing # the elif with not children[childnum], Python 2 thinks that's semantically different # and you suddenly have no tiles being rendered anymore. # No, I don't know either. if children[childnum] is True: # The child is already in the tree. return elif children[childnum] is False: # Expand all-false. children[childnum] = [False] * 4 # This also means an additional composite tile. self.num_tiles_all += 1 self._add_helper(children[childnum], path) if children[childnum] == [True] * 4: # Collapse all-true. children[childnum] = True else: # We are at the leaf. if not children[childnum]: self.num_tiles += 1 self.num_tiles_all += 1 children[childnum] = True def __iter__(self): return self.iterate() def iterate(self, level=None, robin=False, offset=(0, 0)): """Returns an iterator over every tile in this set. Each item yielded is a sequence of integers representing the quadtree path to the tiles in the set. Yielded sequences are of length self.depth. If level is None, iterates over tiles of the highest level, i.e. worldtiles. If level is a value between 1 and the depth of this tree, this method iterates over tiles at that level. Zoom level 1 is zoomed all the way out, zoom level `depth` is all the way in. In other words, specifying level causes the tree to be iterated as if it was only that depth. If the `robin` parameter is True, recurses to the four top-level subtrees simultaneously in a round-robin manner. """ if level is None: todepth = 1 else: if not (level > 0 and level <= self.depth): raise ValueError("Level parameter must be between 1 and %s" % self.depth) todepth = self.depth - level + 1 return (tuple(path) for path in self._iterate_helper([], self.children, self.depth, onlydepth=todepth, robin=robin, offset=offset)) def posttraversal(self, robin=False, offset=(0, 0)): """Returns an iterator over tile paths for every tile in the set, including the explictly marked render-tiles, as well as the implicitly marked ancestors of those render-tiles. Returns in post-traversal order, so that tiles with dependencies will always be yielded after their dependencies. If the `robin` parameter is True, recurses to the four top-level subtrees simultaneously in a round-robin manner. """ return (tuple(path) for path in self._iterate_helper([], self.children, self.depth, robin=robin, offset=offset)) def _iterate_helper(self, path, children, depth, onlydepth=None, robin=False, offset=(0, 0)): """Returns an iterator over tile paths for every tile in the set.""" # A variant of children with a collapsed False/True expanded to a list. children_list = [children] * 4 if isinstance(children, bool) else children targetdepth = 1 if onlydepth is None else onlydepth if depth == targetdepth: # Base case for (childnum, child), _ in distance_sort(enumerate(children_list), offset): if child: yield path + [childnum] else: gens = [] for (childnum_, child), childoffset_ in distance_sort(enumerate(children_list), offset): if child: def go(childnum, childoffset): for p in self._iterate_helper(path + [childnum], children_list[childnum], depth - 1, onlydepth=onlydepth, offset=childoffset): yield p gens.append(go(childnum_, childoffset_)) for p in roundrobin(gens) if robin else chain(*gens): yield p if onlydepth is None and any(children_list): yield path def query_path(self, path): """Queries for the state of the given tile in the tree. Returns True for items in the set, False otherwise. Works for rendertiles as well as upper tiles (which are True if they have a descendent that is in the set) """ # Traverse the tree down the given path. If the tree has been # collapsed, then just return the stored boolean. Otherwise, if we find # the specific tree node requested, return its state using the # __nonzero__ call. treenode = self.children for pathelement in path: treenode = treenode[pathelement] if isinstance(treenode, bool): return treenode # If the method has not returned at this point, treenode is the # requested node, but it is an inner node. That will only happen if one # or more of the children down the tree are True. return True def __bool__(self): """Returns the boolean context of this particular node. If any descendent of this node is True return True. Otherwise, False. """ # Any children that are True or are a list evaluate to True. return any(self.children) def count(self): """Returns the total number of render-tiles in this set. """ # XXX There seems to be something wrong with the num_tiles calculation. # Calculate the number of tiles by iteration and emit a warning if it # does not match. num = sum(map(lambda _: 1, self.iterate())) if num != self.num_tiles: logging.error("Please report this to the developers: RendertileSet num_tiles=%r, " "count=%r, children=%r", self.num_tiles, num, self.children) return num def count_all(self): """Returns the total number of render-tiles plus implicitly marked upper-tiles in this set """ # XXX There seems to be something wrong with the num_tiles calculation. # Calculate the number of tiles by iteration and emit a warning if it # does not match. num = sum(map(lambda _: 1, self.posttraversal())) if num != self.num_tiles_all: logging.error("Please report this to the developers: RendertileSet num_tiles_all=%r, " "count_all=%r, children=%r", self.num_tiles, num, self.children) return num def distance_sort(children, xxx_todo_changeme): (off_x, off_y) = xxx_todo_changeme order = [] for child, (dx, dy) in zip(children, [(-1, -1), (1, -1), (-1, 1), (1, 1)]): x = off_x * 2 + dx y = off_y * 2 + dy order.append((child, (x, y))) return sorted(order, key=lambda __x_y: __x_y[1][0] * __x_y[1][0] + __x_y[1][1] * __x_y[1][1]) class RenderTile(object): """A simple container class that represents a single render-tile. A render-tile is a tile that is rendered, not a tile composed of other tiles (composite-tile). """ __slots__ = ("col", "row", "path") def __init__(self, col, row, path): """Initialize the tile obj with the given parameters. It's probably better to use one of the other constructors though """ self.col = col self.row = row self.path = tuple(path) def __repr__(self): return "%s(%r,%r,%r)" % (self.__class__.__name__, self.col, self.row, self.path) def __eq__(self, other): return(self.col == other.col and self.row == other.row and tuple(self.path) == tuple(other.path)) def __ne__(self, other): return not self == other # To support pickling def __getstate__(self): return self.col, self.row, self.path def __setstate__(self, state): self.__init__(*state) def get_filepath(self, tiledir, imgformat): """Returns the path to this file given the directory to the tiles """ # os.path.join would be the proper way to do this path concatenation, # but it is surprisingly slow, probably because it checks each path # element if it begins with a slash. Since we know these components are # all relative, just concatinate with os.path.sep pathcomponents = [tiledir] pathcomponents.extend(str(x) for x in self.path) path = os.path.sep.join(pathcomponents) imgpath = ".".join((path, imgformat)) return imgpath @classmethod def from_path(cls, path): """Constructor that takes a path and computes the col,row address of the tile and constructs a new tile object. """ path = tuple(path) depth = len(path) # Radius of the world in chunk cols/rows # (Diameter in X is 2**depth, divided by 2 for a radius, multiplied by # 2 for 2 chunks per tile. Similarly for Y) xradius = 2**depth yradius = 2 * 2**depth col = -xradius row = -yradius xsize = xradius ysize = yradius for p in path: if p in (1, 3): col += xsize if p in (2, 3): row += ysize xsize //= 2 ysize //= 2 return cls(col, row, path) @classmethod def compute_path(cls, col, row, depth): """Constructor that takes a col,row of a tile and computes the path. """ assert col % 2 == 0 assert row % 4 == 0 xradius = 2**depth yradius = 2 * 2**depth colbounds = [-xradius, xradius] rowbounds = [-yradius, yradius] path = [] for level in range(depth): # Strategy: Find the midpoint of this level, and determine which # quadrant this row/col is in. Then set the bounds to that level # and repeat xmid = (colbounds[1] + colbounds[0]) // 2 ymid = (rowbounds[1] + rowbounds[0]) // 2 if col < xmid: if row < ymid: path.append(0) colbounds[1] = xmid rowbounds[1] = ymid else: path.append(2) colbounds[1] = xmid rowbounds[0] = ymid else: if row < ymid: path.append(1) colbounds[0] = xmid rowbounds[1] = ymid else: path.append(3) colbounds[0] = xmid rowbounds[0] = ymid return cls(col, row, path)
74,104
Python
.py
1,473
38.380177
100
0.596006
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,283
nbt.py
overviewer_Minecraft-Overviewer/overviewer_core/nbt.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import functools import gzip from io import BytesIO import struct import zlib # decorator that turns the first argument from a string into an open file # handle def _file_loader(func): @functools.wraps(func) def wrapper(fileobj, *args): if type(fileobj) == str: # Is actually a filename fileobj = open(fileobj, 'rb', 4096) return func(fileobj, *args) return wrapper @_file_loader def load(fileobj): """Reads in the given file as NBT format, parses it, and returns the result as a (name, data) tuple. """ return NBTFileReader(fileobj).read_all() @_file_loader def load_region(fileobj): """Reads in the given file as a MCR region, and returns an object for accessing the chunks inside.""" return MCRFileReader(fileobj) class CorruptionError(Exception): pass class CorruptRegionError(CorruptionError): """An exception raised when the MCRFileReader class encounters an error during region file parsing. """ pass class CorruptChunkError(CorruptionError): pass class CorruptNBTError(CorruptionError): """An exception raised when the NBTFileReader class encounters something unexpected in an NBT file.""" pass class NBTFileReader(object): """Low level class that reads the Named Binary Tag format used by Minecraft """ # compile the unpacker's into a classes _byte = struct.Struct("b") _short = struct.Struct(">h") _ushort = struct.Struct(">H") _int = struct.Struct(">i") _uint = struct.Struct(">I") _long = struct.Struct(">q") _float = struct.Struct(">f") _double = struct.Struct(">d") def __init__(self, fileobj, is_gzip=True): """Create a NBT parsing object with the given file-like object. Setting is_gzip to False parses the file as a zlib stream instead.""" if is_gzip: self._file = gzip.GzipFile(fileobj=fileobj, mode='rb') else: # pure zlib stream -- maybe later replace this with # a custom zlib file object? data = zlib.decompress(fileobj.read()) self._file = BytesIO(data) # mapping of NBT type ids to functions to read them out self._read_tagmap = { 0: self._read_tag_end, 1: self._read_tag_byte, 2: self._read_tag_short, 3: self._read_tag_int, 4: self._read_tag_long, 5: self._read_tag_float, 6: self._read_tag_double, 7: self._read_tag_byte_array, 8: self._read_tag_string, 9: self._read_tag_list, 10: self._read_tag_compound, 11: self._read_tag_int_array, 12: self._read_tag_long_array, } # These private methods read the payload only of the following types def _read_tag_end(self): # Nothing to read return 0 def _read_tag_byte(self): byte = self._file.read(1) return self._byte.unpack(byte)[0] def _read_tag_short(self): bytes = self._file.read(2) return self._short.unpack(bytes)[0] def _read_tag_int(self): bytes = self._file.read(4) return self._int.unpack(bytes)[0] def _read_tag_long(self): bytes = self._file.read(8) return self._long.unpack(bytes)[0] def _read_tag_float(self): bytes = self._file.read(4) return self._float.unpack(bytes)[0] def _read_tag_double(self): bytes = self._file.read(8) return self._double.unpack(bytes)[0] def _read_tag_byte_array(self): length = self._uint.unpack(self._file.read(4))[0] bytes = self._file.read(length) return bytes def _read_tag_int_array(self): length = self._uint.unpack(self._file.read(4))[0] int_bytes = self._file.read(length * 4) return struct.unpack(">%ii" % length, int_bytes) def _read_tag_long_array(self): length = self._uint.unpack(self._file.read(4))[0] long_bytes = self._file.read(length * 8) return struct.unpack(">%iq" % length, long_bytes) def _read_tag_string(self): length = self._ushort.unpack(self._file.read(2))[0] # Read the string string = self._file.read(length) # decode it and return return string.decode("UTF-8", 'replace') def _read_tag_list(self): tagid = self._read_tag_byte() length = self._uint.unpack(self._file.read(4))[0] read_method = self._read_tagmap[tagid] l = [None] * length for i in range(length): l[i] = read_method() return l def _read_tag_compound(self): # Build a dictionary of all the tag names mapping to their payloads tags = {} while True: # Read a tag tagtype = ord(self._file.read(1)) if tagtype == 0: break name = self._read_tag_string() payload = self._read_tagmap[tagtype]() tags[name] = payload return tags def read_all(self): """Reads the entire file and returns (name, payload) name is the name of the root tag, and payload is a dictionary mapping names to their payloads """ # Read tag type try: tagtype = ord(self._file.read(1)) if tagtype != 10: raise Exception("Expected a tag compound") # Read the tag name name = self._read_tag_string() payload = self._read_tag_compound() return (name, payload) except (struct.error, ValueError, TypeError, EOFError) as e: raise CorruptNBTError("could not parse nbt: %s" % (str(e),)) # For reference, the MCR format is outlined at # <http://www.minecraftwiki.net/wiki/Beta_Level_Format> class MCRFileReader(object): """A class for reading chunk region files, as introduced in the Beta 1.3 update. It provides functions for opening individual chunks (as (name, data) tuples), getting chunk timestamps, and for listing chunks contained in the file. """ _location_table_format = struct.Struct(">1024I") _timestamp_table_format = struct.Struct(">1024i") _chunk_header_format = struct.Struct(">I B") _preloaded = False def __init__(self, fileobj): """This creates a region object from the given file-like object. Chances are you want to use load_region instead.""" self._file = fileobj self.load_pre_data() def load_pre_data(self): self._file.seek(0) # read in the location table location_data = self._file.read(4096) if not len(location_data) == 4096: raise CorruptRegionError("invalid location table") # read in the timestamp table timestamp_data = self._file.read(4096) if not len(timestamp_data) == 4096: raise CorruptRegionError("invalid timestamp table") # turn this data into a useful list self._locations = self._location_table_format.unpack(location_data) self._timestamps = self._timestamp_table_format.unpack(timestamp_data) def close(self): """Close the region file and free any resources associated with keeping it open. Using this object after closing it results in undefined behaviour. """ self._file.close() del self._file self._file = None def get_chunks(self): """Return an iterator of all chunks contained in this region file, as (x, z) coordinate tuples. To load these chunks, provide these coordinates to load_chunk().""" for x in range(32): for z in range(32): if self._locations[int(x + z * 32)] >> 8 != 0: yield (x, z) def get_chunk_timestamp(self, x, z): """Return the given chunk's modification time. If the given chunk doesn't exist, this number may be nonsense. Like load_chunk(), this will wrap x and z into the range [0, 31]. """ x = x % 32 z = z % 32 return self._timestamps[int(x + z * 32)] def chunk_exists(self, x, z): """Determines if a chunk exists.""" x = x % 32 z = z % 32 return self._locations[int(x + z * 32)] >> 8 != 0 def preload_chunks(self): if not self._preloaded: self._file.seek(0) pl_data = BytesIO(self._file.read()) self._file.close() self._file = pl_data # re-read location, timestamps self.load_pre_data() self._preloaded = True def load_chunk(self, x, z): """Return a (name, data) tuple for the given chunk, or None if the given chunk doesn't exist in this region file. If you provide an x or z not between 0 and 31, it will be modulo'd into this range (x % 32, etc.) This is so you can provide chunk coordinates in global coordinates, and still have the chunks load out of regions properly.""" self.preload_chunks() x = x % 32 z = z % 32 location = self._locations[int(x + z * 32)] offset = (location >> 8) * 4096 sectors = location & 0xff if offset == 0: return None # seek to the data self._file.seek(offset) # read in the chunk data header try: header = self._file.read(5) except OSError as e: raise CorruptChunkError("An OSError occurred: {}".format(e.strerror)) if len(header) != 5: raise CorruptChunkError("chunk header is invalid") data_length, compression = self._chunk_header_format.unpack(header) # figure out the compression is_gzip = True if compression == 1: # gzip -- not used by the official client, but trivial to # support here so... is_gzip = True elif compression == 2: # deflate -- pure zlib stream is_gzip = False else: # unsupported! raise CorruptRegionError("unsupported chunk compression type: %i " "(should be 1 or 2)" % (compression,)) # turn the rest of the data into a BytesIO object # (using data_length - 1, as we already read 1 byte for compression) data = self._file.read(data_length - 1) if len(data) != data_length - 1: raise CorruptRegionError("chunk length is invalid") data = BytesIO(data) try: return NBTFileReader(data, is_gzip=is_gzip).read_all() except CorruptionError: raise except Exception as e: raise CorruptChunkError("Misc error parsing chunk: " + str(e))
11,586
Python
.py
286
32.083916
81
0.610711
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,284
rcon.py
overviewer_Minecraft-Overviewer/overviewer_core/rcon.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import socket import struct import select class RConException(Exception): def __init__(self, request_id, reason): self.request_id = request_id self.reason = reason def __str__(self): return ("Failed RCon request with request ID %d, reason %s" % (self.request_id, self.reason)) class RConConnection(): rid = 0 def __init__(self, target, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((target, port)) def send(self, t, payload): self.rid = self.rid + 1 pld_enc = payload.encode("utf-8") header = struct.pack("<iii", len(pld_enc) + 4 + 4 + 2, # rid, type and padding self.rid, t) data = header + pld_enc + b'\x00\x00' self.sock.send(data) toread = select.select([self.sock], [], [], 30) if not toread: raise RConException(self.rid, "Request timed out.") try: res_len, res_id, res_type = \ struct.unpack("<iii", self.sock.recv(12, socket.MSG_WAITALL)) if res_len < 0: raise Exception("Response length is {}.".format(res_len)) except Exception as e: raise RConException(self.rid, "RCon protocol error. Are you sure you're " "talking to the RCon port? Error: %s" % e) res_data = self.sock.recv(res_len - 4 - 4) res_data = res_data[:-2] if res_id == -1: if t == 3: raise RConException(self.rid, "Login failed.") else: raise RConException(self.rid, "Request failed due to invalid login.") elif res_id != self.rid: raise RConException(self.rid, "Received unexpected response " "number: %d" % res_id) return res_data def login(self, password): self.send(3, password) def command(self, com, args): self.send(2, com + " " + args) def close(self): self.sock.close()
2,908
Python
.py
67
33.776119
79
0.585133
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,285
optimizeimages.py
overviewer_Minecraft-Overviewer/overviewer_core/optimizeimages.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import os import subprocess class Optimizer: binaryname = "" binarynames = [] def __init__(self): raise NotImplementedError("I can't let you do that, Dave.") def optimize(self, img): raise NotImplementedError("I can't let you do that, Dave.") def fire_and_forget(self, args): subprocess.check_call(args) def check_availability(self): path = os.environ.get("PATH").split(os.pathsep) def exists_in_path(prog): result = [x for x in path if os.path.exists(os.path.join(x, prog))] return len(result) != 0 binaries = self.binarynames + [x + ".exe" for x in self.binarynames] for b in binaries: if (exists_in_path(b)): self.binaryname = b break else: raise Exception("Optimization programs '%s' were not found!" % binaries) def is_crusher(self): """Should return True if the optimization is lossless, i.e. none of the actual image data will be changed.""" raise NotImplementedError("I'm so abstract I can't even say whether " "I'm a crusher.") class NonAtomicOptimizer(Optimizer): def cleanup(self, img): os.remove(img) os.rename(img + ".tmp", img) def fire_and_forget(self, args, img): subprocess.check_call(args) self.cleanup(img) class PNGOptimizer: def __init__(self): raise NotImplementedError("I can't let you do that, Dave.") class JPEGOptimizer: def __init__(self): raise NotImplementedError("I can't let you do that, Dave.") class pngnq(NonAtomicOptimizer, PNGOptimizer): binarynames = ["pngnq-s9", "pngnq"] def __init__(self, sampling=3, dither="n"): if sampling < 1 or sampling > 10: raise Exception("Invalid sampling value '%d' for pngnq!" % sampling) if dither not in ["n", "f"]: raise Exception("Invalid dither method '%s' for pngnq!" % dither) self.sampling = sampling self.dither = dither def optimize(self, img): if img.endswith(".tmp"): extension = ".tmp" else: extension = ".png.tmp" args = [self.binaryname, "-s", str(self.sampling), "-f", "-e", extension, img] # Workaround for poopbuntu 12.04 which ships an old broken pngnq if self.dither != "n": args.insert(1, "-Q") args.insert(2, self.dither) NonAtomicOptimizer.fire_and_forget(self, args, img) def is_crusher(self): return False class pngcrush(NonAtomicOptimizer, PNGOptimizer): binarynames = ["pngcrush"] # really can't be bothered to add some interface for all # the pngcrush options, it sucks anyway def __init__(self, brute=False): self.brute = brute def optimize(self, img): args = [self.binaryname, img, img + ".tmp"] if self.brute: # Was the user an idiot? args.insert(1, "-brute") NonAtomicOptimizer.fire_and_forget(self, args, img) def is_crusher(self): return True class optipng(Optimizer, PNGOptimizer): binarynames = ["optipng"] def __init__(self, olevel=2): self.olevel = olevel def optimize(self, img): Optimizer.fire_and_forget(self, [self.binaryname, "-o" + str(self.olevel), "-quiet", img]) def is_crusher(self): return True class advpng(Optimizer, PNGOptimizer): binarynames = ["advpng"] crusher = True def __init__(self, olevel=3): self.olevel = olevel def optimize(self, img): Optimizer.fire_and_forget(self, [self.binaryname, "-z" + str(self.olevel), "-q", img]) def is_crusher(self): return True class jpegoptim(Optimizer, JPEGOptimizer): binarynames = ["jpegoptim"] crusher = True quality = None target_size = None def __init__(self, quality=None, target_size=None): if quality is not None: if quality < 0 or quality > 100: raise Exception("Invalid target quality %d for jpegoptim" % quality) self.quality = quality if target_size is not None: self.target_size = target_size def optimize(self, img): args = [self.binaryname, "-q", "-p"] if self.quality is not None: args.append("-m" + str(self.quality)) if self.target_size is not None: args.append("-S" + str(self.target_size)) args.append(img) Optimizer.fire_and_forget(self, args) def is_crusher(self): # Technically, optimisation is lossless if input image quality # is below target quality, but this is irrelevant in this case if (self.quality is not None) or (self.target_size is not None): return False else: return True class oxipng(Optimizer, PNGOptimizer): binarynames = ["oxipng"] def __init__(self, olevel=2, threads=1): if olevel > 6: raise Exception("olevel should be between 0 and 6 inclusive") if threads < 1: raise Exception("threads needs to be at least 1") self.olevel = olevel self.threads = threads def optimize(self, img): Optimizer.fire_and_forget(self, [self.binaryname, "-o" + str(self.olevel), "-q", "-t" + str(self.threads), img]) def is_crusher(self): return True def optimize_image(imgpath, imgformat, optimizers): for opt in optimizers: if imgformat == 'png': if isinstance(opt, PNGOptimizer): opt.optimize(imgpath) elif imgformat == 'jpg': if isinstance(opt, JPEGOptimizer): opt.optimize(imgpath)
6,742
Python
.py
163
32.177914
79
0.604017
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,286
biome.py
overviewer_Minecraft-Overviewer/overviewer_core/biome.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details, and note that Jeffrey Epstein didn't kill # himself. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. class BiomeException(Exception): def __init__(self, msg): self.msg = msg def reshape_biome_data(biome_array): biome_len = len(biome_array) if biome_len == 256: return biome_array.reshape((16, 16)) elif biome_len == 1024: # Ok here's the big brain explanation: # Minecraft's new biomes have a resolution of 4x4x4 blocks. # This means for a 16x256x16 chunk column we get 64 times for the vertical, # and 4x4 values for the horizontals. # Minecraft Wiki says some dumb thing about how "oh it's ordered by Z, then X, then Y", # but they appear to either be wrong or have explained it with the eloquence of a # caveman. return biome_array.reshape((4, 64, 4)) elif biome_len == 1536: return biome_array.reshape((4, 96, 4)) else: raise BiomeException("Can't reshape a biome of length {}".format(biome_len))
1,714
Python
.py
35
44.485714
95
0.698271
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,287
cache.py
overviewer_Minecraft-Overviewer/overviewer_core/cache.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. """This module has supporting functions for the caching logic used in world.py. Each cache class should implement the standard container type interface (__getitem__ and __setitem__), as well as provide a "hits" and "misses" attribute. """ class LRUCache(object): """A simple, generic, in-memory LRU cache that implements the standard python container interface. An ordered dict type would simplify this implementation a bit, but we want Python 2.6 compatibility and the standard library ordereddict was added in 2.7. It's probably okay because this implementation can be tuned for exactly what we need and nothing more. This implementation keeps a linked-list of cache keys and values, ordered in least-recently-used order. A dictionary maps keys to linked-list nodes. On cache hit, the link is moved to the end of the list. On cache miss, the first item of the list is evicted. All operations have constant time complexity (dict lookups are worst case O(n) time) """ class _LinkNode(object): __slots__ = ['left', 'right', 'key', 'value'] def __init__(self, l=None, r=None, k=None, v=None): self.left = l self.right = r self.key = k self.value = v def __init__(self, size=100, destructor=None): """Initialize a new LRU cache with the given size. destructor, if given, is a callable that is called upon an item being evicted from the cache. It takes one argument, the value stored in the cache. """ self.cache = {} # Two sentinel nodes at the ends of the linked list simplify boundary # conditions in the code below. self.listhead = LRUCache._LinkNode() self.listtail = LRUCache._LinkNode() self.listhead.right = self.listtail self.listtail.left = self.listhead self.hits = 0 self.misses = 0 self.size = size self.destructor = destructor # Initialize an empty cache of the same size for worker processes def __getstate__(self): return self.size def __setstate__(self, size): self.__init__(size) def __getitem__(self, key): try: link = self.cache[key] except KeyError: self.misses += 1 raise # Disconnect the link from where it is link.left.right = link.right link.right.left = link.left # Insert the link at the end of the list tail = self.listtail link.left = tail.left link.right = tail tail.left.right = link tail.left = link self.hits += 1 return link.value def __setitem__(self, key, value): cache = self.cache if key in cache: # Shortcut this case cache[key].value = value return if len(cache) >= self.size: # Evict a node link = self.listhead.right del cache[link.key] link.left.right = link.right link.right.left = link.left d = self.destructor if d: d(link.value) del link # The node doesn't exist already, and we have room for it. Let's do this. tail = self.listtail link = LRUCache._LinkNode(tail.left, tail, key, value) tail.left.right = link tail.left = link cache[key] = link def __delitem__(self, key): # Used to flush the cache of this key cache = self.cache link = cache[key] del cache[key] link.left.right = link.right link.right.left = link.left # Call the destructor d = self.destructor if d: d(link.value)
4,522
Python
.py
111
32.891892
81
0.635181
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,288
__init__.py
overviewer_Minecraft-Overviewer/overviewer_core/__init__.py
# # Code to check to make sure c_overviewer is built and working # import os.path import os import platform import traceback import sys from . import util def check_c_overviewer(): """Check to make sure c_overviewer works and is up-to-date. Prints out a helpful error and returns 1 if something's wrong, returns 0 otherwise. """ root_dir = util.get_program_path() # make sure the c_overviewer extension is available try: from . import c_overviewer except ImportError: if os.environ.get("OVERVIEWER_DEBUG_IMPORT") == "1": traceback.print_exc() # if this is a frozen windows package, the following error messages about # building the c_overviewer extension are not appropriate if hasattr(sys, "frozen") and platform.system() == 'Windows': print("Something has gone wrong importing the c_overviewer extension. Please make sure " "the 2008 and 2010 redistributable packages from Microsoft are installed.") return 1 # try to find the build extension ext = os.path.join(root_dir, "overviewer_core", "c_overviewer.{}" .format("pyd" if platform.system() == "Windows" else "so")) if os.path.exists(ext): traceback.print_exc() print() print("Something has gone wrong importing the c_overviewer extension. Please make sure " "it is up-to-date. (clean and rebuild)") return 1 print("You need to compile the c_overviewer module to run Minecraft Overviewer.") print("Run `python setup.py build`, or see the README for details.") return 1 # # make sure it's up-to-date # if hasattr(sys, "frozen"): pass # we don't bother with a compat test since it should always be in sync elif "extension_version" in dir(c_overviewer): # check to make sure the binary matches the headers if os.path.exists(os.path.join(root_dir, "overviewer_core", "src", "overviewer.h")): with open(os.path.join(root_dir, "overviewer_core", "src", "overviewer.h")) as f: lines = f.readlines() lines = list(filter(lambda x: x.startswith("#define OVERVIEWER_EXTENSION_VERSION"), lines)) if lines: l = lines[0] if int(l.split()[2].strip()) != c_overviewer.extension_version(): print("Please rebuild your c_overviewer module. It is out of date!") return 1 else: print("Please rebuild your c_overviewer module. It is out of date!") return 1 # all good! return 0 # only check the module if we're not setup.py if not sys.argv[0].endswith("setup.py"): ret = check_c_overviewer() if ret > 0: util.nice_exit(ret)
2,910
Python
.py
66
34.757576
100
0.616308
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,289
dispatcher.py
overviewer_Minecraft-Overviewer/overviewer_core/dispatcher.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import multiprocessing import multiprocessing.managers import queue import time from . import util from .signals import Signal class Dispatcher: """This class coordinates the work of all the TileSet objects among one worker process. By subclassing this class and implementing setup_tilesets(), dispatch(), and close(), it is possible to create a Dispatcher that distributes this work to many worker processes. """ def __init__(self): super(Dispatcher, self).__init__() # list of (tileset, workitem) tuples # keeps track of dispatched but unfinished jobs self._running_jobs = [] # list of (tileset, workitem, dependencies) tuples # keeps track of jobs waiting to run after dependencies finish self._pending_jobs = [] def render_all(self, tilesetlist, observer): """Render all of the tilesets in the given tilesetlist. status_callback is called periodically to update status. The callback should take the following arguments: (phase, items_completed, total_items), where total_items may be none if there is no useful estimate. """ # TODO use status callback # setup tilesetlist self.setup_tilesets(tilesetlist) # iterate through all possible phases num_phases = [tileset.get_num_phases() for tileset in tilesetlist] for phase in range(max(num_phases)): # construct a list of iterators to use for this phase work_iterators = [] for i, tileset in enumerate(tilesetlist): if phase < num_phases[i]: def make_work_iterator(tset, p): return ((tset, workitem) for workitem in tset.iterate_work_items(p)) work_iterators.append(make_work_iterator(tileset, phase)) # keep track of total jobs, and how many jobs are done total_jobs = 0 for tileset, phases in zip(tilesetlist, num_phases): if phase < phases: jobs_for_tileset = tileset.get_phase_length(phase) # if one is unknown, the total is unknown if jobs_for_tileset is None: total_jobs = None break else: total_jobs += jobs_for_tileset observer.start(total_jobs) # go through these iterators round-robin style for tileset, (workitem, deps) in util.roundrobin(work_iterators): self._pending_jobs.append((tileset, workitem, deps)) observer.add(self._dispatch_jobs()) # after each phase, wait for the work to finish while self._pending_jobs or self._running_jobs: observer.add(self._dispatch_jobs()) observer.finish() def _dispatch_jobs(self): # helper function to dispatch pending jobs when their # dependencies are met, and to manage self._running_jobs dispatched_jobs = [] finished_jobs = [] pending_jobs_nodeps = [(j[0], j[1]) for j in self._pending_jobs] for pending_job in self._pending_jobs: tileset, workitem, deps = pending_job # see if any of the deps are in _running_jobs or _pending_jobs for dep in deps: if (tileset, dep) in self._running_jobs or (tileset, dep) in pending_jobs_nodeps: # it is! don't dispatch this item yet break else: # it isn't! all dependencies are finished finished_jobs += self.dispatch(tileset, workitem) self._running_jobs.append((tileset, workitem)) dispatched_jobs.append(pending_job) # make sure to at least get finished jobs, even if we don't # submit any new ones... if not dispatched_jobs: finished_jobs += self.dispatch(None, None) # clean out the appropriate lists for job in finished_jobs: self._running_jobs.remove(job) for job in dispatched_jobs: self._pending_jobs.remove(job) return len(finished_jobs) def close(self): """Close the Dispatcher. This should be called when you are done with the dispatcher, to ensure that it cleans up any processes or connections it may still have around. """ pass def setup_tilesets(self, tilesetlist): """Called whenever a new list of tilesets are being used. This lets subclasses distribute the whole list at once, instead of for each work item.""" pass def dispatch(self, tileset, workitem): """Dispatch the given work item. The end result of this call should be running tileset.do_work(workitem) somewhere. This function should return a list of (tileset, workitem) tuples that have completed since the last call. If tileset is None, then returning completed jobs is all this function should do. """ if tileset is not None: tileset.do_work(workitem) return [(tileset, workitem)] return [] class MultiprocessingDispatcherManager(multiprocessing.managers.BaseManager): """This multiprocessing manager is responsible for giving worker processes access to the communication Queues, and also gives workers access to the current tileset list. """ def _get_job_queue(self): return self.job_queue def _get_results_queue(self): return self.result_queue def _get_signal_queue(self): return self.signal_queue def _get_tileset_data(self): return self.tileset_data def __init__(self, address=None, authkey=None): self.job_queue = multiprocessing.Queue() self.result_queue = multiprocessing.Queue() self.signal_queue = multiprocessing.Queue() self.tilesets = [] self.tileset_version = 0 self.tileset_data = [[], 0] self.register("get_job_queue", callable=self._get_job_queue) self.register("get_result_queue", callable=self._get_results_queue) self.register("get_signal_queue", callable=self._get_signal_queue) self.register("get_tileset_data", callable=self._get_tileset_data, proxytype=multiprocessing.managers.ListProxy) super(MultiprocessingDispatcherManager, self).__init__(address=address, authkey=authkey) @classmethod def from_address(cls, address, authkey, serializer): "Required to be implemented to make multiprocessing happy" c = cls(address=address, authkey=authkey) return c def set_tilesets(self, tilesets): """This is used in MultiprocessingDispatcher.setup_tilesets to update the tilesets each worker has access to. It also increments a `tileset_version` which is an easy way for workers to see if their tileset list is out-of-date without pickling and copying over the entire list. """ self.tilesets = tilesets self.tileset_version += 1 data = self.get_tileset_data() data[0] = self.tilesets data[1] = self.tileset_version class MultiprocessingDispatcherProcess(multiprocessing.Process): """This class represents a single worker process. It is created automatically by MultiprocessingDispatcher, but it can even be used manually to spawn processes on different machines on the same network. """ def __init__(self, manager): """Creates the process object. manager should be an instance of MultiprocessingDispatcherManager connected to the one created in MultiprocessingDispatcher. """ super(MultiprocessingDispatcherProcess, self).__init__() self.job_queue = manager.get_job_queue() self.result_queue = manager.get_result_queue() self.signal_queue = manager.get_signal_queue() self.tileset_proxy = manager.get_tileset_data() def update_tilesets(self): """A convenience function to update our local tilesets to the current version in use by the MultiprocessingDispatcher. """ self.tilesets, self.tileset_version = self.tileset_proxy._getvalue() def run(self): """The main work loop. Jobs are pulled from the job queue and executed, then the result is pushed onto the result queue. Updates to the tilesetlist are recognized and handled automatically. This is the method that actually runs in the new worker process. """ # per-process job get() timeout timeout = 1.0 # update our tilesets self.update_tilesets() # register for all available signals def register_signal(name, sig): def handler(*args, **kwargs): self.signal_queue.put((name, args, kwargs), False) sig.set_interceptor(handler) for name, sig in Signal.signals.items(): register_signal(name, sig) # notify that we're starting up self.result_queue.put(None, False) while True: try: job = self.job_queue.get(True, timeout) if job is None: # this is a end-of-jobs sentinel return # unpack job tv, ti, workitem = job if tv != self.tileset_version: # our tilesets changed! self.update_tilesets() assert tv == self.tileset_version # do job ret = self.tilesets[ti].do_work(workitem) result = (ti, workitem, ret,) self.result_queue.put(result, False) except queue.Empty: pass except KeyboardInterrupt: return class MultiprocessingDispatcher(Dispatcher): """A subclass of Dispatcher that spawns worker processes and distributes jobs to them to speed up processing. """ def __init__(self, local_procs=-1, address=None, authkey=None): """Creates the dispatcher. local_procs should be the number of worker processes to spawn. If it's omitted (or negative) the number of available CPUs is used instead. """ super(MultiprocessingDispatcher, self).__init__() # automatic local_procs handling if local_procs < 0: local_procs = multiprocessing.cpu_count() self.local_procs = local_procs self.outstanding_jobs = 0 self.num_workers = 0 self.manager = MultiprocessingDispatcherManager(address=address, authkey=authkey) self.manager.start() self.job_queue = self.manager.get_job_queue() self.result_queue = self.manager.get_result_queue() self.signal_queue = self.manager.get_signal_queue() # create and fill the pool self.pool = [] for i in range(self.local_procs): proc = MultiprocessingDispatcherProcess(self.manager) proc.start() self.pool.append(proc) def close(self): # empty the queue self._handle_messages(timeout=0.0) while self.outstanding_jobs > 0: self._handle_messages() # send of the end-of-jobs sentinel for p in range(self.num_workers): self.job_queue.put(None, False) # TODO better way to be sure worker processes get the message time.sleep(1) # and close the manager self.manager.shutdown() self.manager = None self.pool = None def setup_tilesets(self, tilesets): self.manager.set_tilesets(tilesets) def dispatch(self, tileset, workitem): # handle the no-new-work case if tileset is None: return self._handle_messages() # create and submit the job tileset_index = self.manager.tilesets.index(tileset) self.job_queue.put((self.manager.tileset_version, tileset_index, workitem), False) self.outstanding_jobs += 1 # make sure the queue doesn't fill up too much finished_jobs = self._handle_messages(timeout=0.0) while self.outstanding_jobs > self.num_workers * 10: finished_jobs += self._handle_messages() return finished_jobs def _handle_messages(self, timeout=0.01): # work function: takes results out of the result queue and # keeps track of how many outstanding jobs remain finished_jobs = [] result_empty = False signal_empty = False while not (result_empty and signal_empty): if not result_empty: try: result = self.result_queue.get(False) if result is not None: # completed job ti, workitem, ret = result finished_jobs.append((self.manager.tilesets[ti], workitem)) self.outstanding_jobs -= 1 else: # new worker self.num_workers += 1 except queue.Empty: result_empty = True if not signal_empty: try: if timeout > 0.0: name, args, kwargs = self.signal_queue.get(True, timeout) else: name, args, kwargs = self.signal_queue.get(False) # timeout should only apply once timeout = 0.0 sig = Signal.signals[name] sig.emit_intercepted(*args, **kwargs) except queue.Empty: signal_empty = True return finished_jobs @classmethod def start_manual_process(cls, address, authkey): """A convenience method to start up a manual process, possibly on another machine. Address is a (hostname, port) tuple, and authkey must be the same as that provided to the MultiprocessingDispatcher constructor. """ m = MultiprocessingDispatcherManager(address=address, authkey=authkey) m.connect() p = MultiprocessingDispatcherProcess(m) p.run()
15,121
Python
.py
329
35.282675
97
0.622607
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,290
rendermodes.py
overviewer_Minecraft-Overviewer/overviewer_core/rendermodes.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime, timedelta from PIL import Image from . import textures """The contents of this file are imported into the namespace of config files. It also defines the render primitive objects, which are used by the C code. Each render primitive has a corresponding section of C code, so both places must be changed simultaneously if you want to make any changes. """ class RenderPrimitive(object): options = {} name = None def __init__(self, **kwargs): if self.name is None: raise RuntimeError("RenderPrimitive cannot be used directly") self.option_values = {} for key, val in kwargs.items(): if not key in self.options: raise ValueError("primitive `{0}' has no option `{1}'".format(self.name, key)) self.option_values[key] = val # set up defaults for name, (description, default) in self.options.items(): if not name in self.option_values: self.option_values[name] = default class Base(RenderPrimitive): name = "base" options = { "biomes": ("whether or not to use biomes", True), } class NetherOld(RenderPrimitive): name = "netherold" class Nether(RenderPrimitive): name = "nether" class HeightFading(RenderPrimitive): name = "height-fading" options = { # 128 is *WRONG*, it should be 64. but we're grandfathered in for now "sealevel": ("target sea level", 128), } black_color = Image.new("RGB", (24,24), (0,0,0)) white_color = Image.new("RGB", (24,24), (255,255,255)) class Depth(RenderPrimitive): name = "depth" options = { "min": ("lowest level of blocks to render", -64), "max": ("highest level of blocks to render", 319), } class Exposed(RenderPrimitive): name = "exposed" options = { "mode": ("0 = exposed blocks only, 1 = unexposed blocks only", 0), } class NoFluids(RenderPrimitive): name = "no-fluids" class EdgeLines(RenderPrimitive): name = "edge-lines" options = { "opacity": ("darkness of the edge lines, from 0.0 to 1.0", 0.15), } class Cave(RenderPrimitive): name = "cave" options = { "only_lit": ("only render lit caves", False), } class DepthTinting(RenderPrimitive): name = "depth-tinting" @property def depth_colors(self): depth_colors = getattr(self, "_depth_colors", []) if depth_colors: return depth_colors r = 255 g = 0 b = 0 for z in range(128): depth_colors.append(r) depth_colors.append(g) depth_colors.append(b) if z < 32: g += 7 elif z < 64: r -= 7 elif z < 96: b += 7 else: g -= 7 self._depth_colors = depth_colors return depth_colors class Lighting(RenderPrimitive): name = "lighting" options = { "strength": ("how dark to make the shadows, from 0.0 to 1.0", 1.0), "night": ("whether to use nighttime skylight settings", False), "color": ("whether to use colored light", False), } @property def facemasks(self): facemasks = getattr(self, "_facemasks", None) if facemasks: return facemasks white = Image.new("L", (24,24), 255) top = Image.new("L", (24,24), 0) left = Image.new("L", (24,24), 0) whole = Image.new("L", (24,24), 0) toppart = textures.Textures.transform_image_top(white) leftpart = textures.Textures.transform_image_side(white) # using the real PIL paste here (not alpha_over) because there is # no alpha channel (and it's mode "L") top.paste(toppart, (0,0)) left.paste(leftpart, (0,6)) right = left.transpose(Image.FLIP_LEFT_RIGHT) # Manually touch up 6 pixels that leave a gap, like in # textures._build_block() for x,y in [(13,23), (17,21), (21,19)]: right.putpixel((x,y), 255) for x,y in [(3,4), (7,2), (11,0)]: top.putpixel((x,y), 255) # special fix for chunk boundary stipple for x,y in [(13,11), (17,9), (21,7)]: right.putpixel((x,y), 0) self._facemasks = (top, left, right) return self._facemasks class SmoothLighting(Lighting): name = "smooth-lighting" class ClearBase(RenderPrimitive): name = "clear-base" class Overlay(RenderPrimitive): name = "overlay" options = { 'overlay_color' : ('a tuple of (r, g, b, a) for coloring the overlay', None), } @property def whitecolor(self): whitecolor = getattr(self, "_whitecolor", None) if whitecolor: return whitecolor white = Image.new("RGBA", (24,24), (255, 255, 255, 255)) self._whitecolor = white return white @property def facemask_top(self): facemask_top = getattr(self, "_facemask_top", None) if facemask_top: return facemask_top white = Image.new("L", (24,24), 255) top = Image.new("L", (24,24), 0) toppart = textures.Textures.transform_image_top(white) top.paste(toppart, (0,0)) for x,y in [(3,4), (7,2), (11,0)]: top.putpixel((x,y), 255) self._facemask_top = top return top class SpawnOverlay(Overlay): name = "overlay-spawn" class SlimeOverlay(Overlay): name = "overlay-slime" class StructureOverlay(Overlay): name = "overlay-structure" options = { 'structures': ('a list of ((((relx, rely, relz), blockid), ...), (r, g, b, a)) tuples for coloring minerals', [(((0, 0, 0, 66), (0, -1, 0, 4)), (255, 0, 0, 255)), (((0, 0, 0, 27), (0, -1, 0, 4)), (0, 255, 0, 255)), (((0, 0, 0, 28), (0, -1, 0, 4)), (255, 255, 0, 255)), (((0, 0, 0, 157), (0, -1, 0, 4)), (255, 100, 0, 255)), ]), } class MineralOverlay(Overlay): name = "overlay-mineral" options = { 'minerals' : ('a list of (blockid, (r, g, b)) tuples for coloring minerals', None), } class BiomeOverlay(Overlay): name = "overlay-biomes" options = { 'biomes' : ('a list of (biome, (r, g, b)) tuples for coloring biomes', None), 'alpha' : ('an integer value between 0 (transparent) and 255 (opaque)', None), } class HeatmapOverlay(Overlay): t_now = datetime.now() name = "overlay-heatmap" options = { 't_invisible': ( 'the timestamp when the overlay will get invisible (e.g. 1 month go)', int((t_now - timedelta(days=30)).timestamp()) ), 't_full': ('the timestamp when the overlay will be fully visible (e.g. now)', int(t_now.timestamp())), } class Hide(RenderPrimitive): name = "hide" options = { 'blocks' : ('a list of blockids or (blockid, data) tuples of blocks to hide', []), } # Built-in rendermodes for your convenience! normal = [Base(), EdgeLines()] lighting = [Base(), EdgeLines(), Lighting()] smooth_lighting = [Base(), EdgeLines(), SmoothLighting()] night = [Base(), EdgeLines(), Lighting(night=True)] smooth_night = [Base(), EdgeLines(), SmoothLighting(night=True)] netherold = [Base(), EdgeLines(), NetherOld()] netherold_lighting = [Base(), EdgeLines(), NetherOld(), Lighting()] netherold_smooth_lighting = [Base(), EdgeLines(), NetherOld(), SmoothLighting()] nether = [Base(), EdgeLines(), Nether()] nether_lighting = [Base(), EdgeLines(), Nether(), Lighting()] nether_smooth_lighting = [Base(), EdgeLines(), Nether(), SmoothLighting()] cave = [Base(), EdgeLines(), Cave(), DepthTinting()]
8,627
Python
.py
218
32.114679
117
0.602665
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,291
logger.py
overviewer_Minecraft-Overviewer/overviewer_core/logger.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import ctypes import logging import os import platform import sys from io import StringIO # Some cool code for colored logging: # For background, add 40. For foreground, add 30 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" # Windows colors, taken from WinCon.h FOREGROUND_BLUE = 0x01 FOREGROUND_GREEN = 0x02 FOREGROUND_RED = 0x04 FOREGROUND_BOLD = 0x08 FOREGROUND_WHITE = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED BACKGROUND_BLACK = 0x00 BACKGROUND_BLUE = 0x10 BACKGROUND_GREEN = 0x20 BACKGROUND_RED = 0x40 COLORIZE = { 'DEBUG': CYAN, } HIGHLIGHT = { 'CRITICAL': RED, 'ERROR': RED, 'WARNING': YELLOW, } class WindowsOutputStream(object): """A file-like object that proxies sys.stderr and interprets simple ANSI escape codes for color, translating them to the appropriate Windows calls. """ def __init__(self, stream=None): assert platform.system() == 'Windows' self.stream = stream or sys.stderr # go go gadget ctypes self.GetStdHandle = ctypes.windll.kernel32.GetStdHandle self.SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute self.STD_OUTPUT_HANDLE = ctypes.c_int(0xFFFFFFF5) self.output_handle = self.GetStdHandle(self.STD_OUTPUT_HANDLE) if self.output_handle == 0xFFFFFFFF: raise Exception("Something failed in WindowsColorFormatter") # default is white text on a black background self.currentForeground = FOREGROUND_WHITE self.currentBackground = BACKGROUND_BLACK self.currentBold = 0 def updateWinColor(self, Fore=None, Back=None, Bold=False): if Fore is not None: self.currentForeground = Fore if Back is not None: self.currentBackground = Back if Bold: self.currentBold = FOREGROUND_BOLD else: self.currentBold = 0 self.SetConsoleTextAttribute( self.output_handle, ctypes.c_int(self.currentForeground | self.currentBackground | self.currentBold)) def write(self, s): msg_strm = StringIO(s) while (True): c = msg_strm.read(1) if c == '': break if c == '\033': c1 = msg_strm.read(1) if c1 != '[': sys.stream.write(c + c1) continue c2 = msg_strm.read(2) if c2 == "0m": # RESET_SEQ self.updateWinColor(Fore=FOREGROUND_WHITE, Back=BACKGROUND_BLACK) elif c2 == "1;": color = "" while(True): nc = msg_strm.read(1) if nc == 'm': break color += nc color = int(color) if (color >= 40): # background color = color - 40 if color == BLACK: self.updateWinColor(Back=BACKGROUND_BLACK) if color == RED: self.updateWinColor(Back=BACKGROUND_RED) elif color == GREEN: self.updateWinColor(Back=BACKGROUND_GREEN) elif color == YELLOW: self.updateWinColor(Back=BACKGROUND_RED | BACKGROUND_GREEN) elif color == BLUE: self.updateWinColor(Back=BACKGROUND_BLUE) elif color == MAGENTA: self.updateWinColor(Back=BACKGROUND_RED | BACKGROUND_BLUE) elif color == CYAN: self.updateWinColor(Back=BACKGROUND_GREEN | BACKGROUND_BLUE) elif color == WHITE: self.updateWinColor(Back=BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE) elif (color >= 30): # foreground color = color - 30 if color == BLACK: self.updateWinColor(Fore=FOREGROUND_BLACK) if color == RED: self.updateWinColor(Fore=FOREGROUND_RED) elif color == GREEN: self.updateWinColor(Fore=FOREGROUND_GREEN) elif color == YELLOW: self.updateWinColor(Fore=FOREGROUND_RED | FOREGROUND_GREEN) elif color == BLUE: self.updateWinColor(Fore=FOREGROUND_BLUE) elif color == MAGENTA: self.updateWinColor(Fore=FOREGROUND_RED | FOREGROUND_BLUE) elif color == CYAN: self.updateWinColor(Fore=FOREGROUND_GREEN | FOREGROUND_BLUE) elif color == WHITE: self.updateWinColor(Fore=FOREGROUND_WHITE) elif c2 == "1m": # BOLD_SEQ pass else: self.stream.write(c) def flush(self): self.stream.flush() class HighlightingFormatter(logging.Formatter): """Base class of our custom formatter""" datefmt = "%Y-%m-%d %H:%M:%S" funcName_len = 15 def __init__(self, verbose=False): if verbose: fmtstr = '%(fileandlineno)-18s %(pid)s %(asctime)s %(levelname)-8s %(message)s' else: fmtstr = '%(asctime)s %(shortlevelname)-1s%(message)s' logging.Formatter.__init__(self, fmtstr, self.datefmt) def format(self, record): """Add a few extra options to the record pid The process ID fileandlineno A combination filename:linenumber string, so it can be justified as one entry in a format string. funcName The function name truncated/padded to a fixed width characters shortlevelname The level name truncated to 1 character """ record.shortlevelname = record.levelname[0] + ' ' if record.levelname == 'INFO': record.shortlevelname = '' record.pid = os.getpid() record.fileandlineno = "%s:%s" % (record.filename, record.lineno) # Set the max length for the funcName field, and left justify l = self.funcName_len record.funcName = ("%-" + str(l) + 's') % record.funcName[:l] return self.highlight(record) def highlight(self, record): """This method applies any special effects such as colorization. It should modify the records in the record object, and should return the *formatted line*. This probably involves calling logging.Formatter.format() Override this in subclasses """ return logging.Formatter.format(self, record) class DumbFormatter(HighlightingFormatter): """Formatter for dumb terminals that don't support color, or log files. Prints a bunch of stars before a highlighted line. """ def highlight(self, record): if record.levelname in HIGHLIGHT: line = logging.Formatter.format(self, record) line = "*" * min(79, len(line)) + "\n" + line return line else: return HighlightingFormatter.highlight(self, record) class ANSIColorFormatter(HighlightingFormatter): """Uses ANSI escape sequences to enable GLORIOUS EXTRA-COLOR! """ def highlight(self, record): if record.levelname in COLORIZE: # Colorize just the levelname # left justify again because the color sequence bumps the length up # above 8 chars levelname_color = (COLOR_SEQ % (30 + COLORIZE[record.levelname]) + "%-8s" % record.levelname + RESET_SEQ) record.levelname = levelname_color return logging.Formatter.format(self, record) elif record.levelname in HIGHLIGHT: # Colorize the entire line line = logging.Formatter.format(self, record) line = COLOR_SEQ % (40 + HIGHLIGHT[record.levelname]) + line + RESET_SEQ return line else: # No coloring if it's not to be highlighted or colored return logging.Formatter.format(self, record) def configure(loglevel=logging.INFO, verbose=False, simple=False): """Configures the root logger to our liking For a non-standard loglevel, pass in the level with which to configure the handler. For a more verbose options line, pass in verbose=True This function may be called more than once. """ logger = logging.getLogger() outstream = sys.stdout if simple: formatter = DumbFormatter(verbose) elif platform.system() == 'Windows': # Our custom output stream processor knows how to deal with select ANSI # color escape sequences outstream = WindowsOutputStream(outstream) formatter = ANSIColorFormatter(verbose) elif outstream.isatty(): # terminal logging with ANSI color formatter = ANSIColorFormatter(verbose) else: # Let's not assume anything. Just text. formatter = DumbFormatter(verbose) if hasattr(logger, 'overviewerHandler'): # we have already set up logging so just replace the formatter # this time with the new values logger.overviewerHandler.setFormatter(formatter) logger.setLevel(loglevel) else: # Save our handler here so we can tell which handler was ours if the # function is called again logger.overviewerHandler = logging.StreamHandler(outstream) logger.overviewerHandler.setFormatter(formatter) logger.addHandler(logger.overviewerHandler) logger.setLevel(loglevel) # Make sure Pillow doesn't spam us in verbose mode logging.getLogger("PIL").setLevel(logging.WARNING)
10,915
Python
.py
244
33.307377
93
0.599209
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,292
observer.py
overviewer_Minecraft-Overviewer/overviewer_core/observer.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import json import logging import os import sys import time from . import progressbar from . import rcon class Observer(object): """Base class that defines the observer interface. """ def __init__(self): self._current_value = None self._max_value = None self.start_time = None self.end_time = None def start(self, max_value): """Signals the start of whatever process. Must be called before update """ self._set_max_value(max_value) self.start_time = time.time() self.update(0) return self def is_started(self): return self.start_time is not None def finish(self): """Signals the end of the processes, should be called after the process is done. """ self.end_time = time.time() def is_finished(self): return self.end_time is not None def is_running(self): return self.is_started() and not self.is_finished() def add(self, amount): """Shortcut to update by increments instead of absolute values. Zero amounts are ignored. """ if amount: self.update(self.get_current_value() + amount) def update(self, current_value): """Set the progress value. Should be between 0 and max_value. Returns whether this update is actually displayed. """ self._current_value = current_value return False def get_percentage(self): """Get the current progress percentage. Assumes 100% if max_value is 0 """ if self.get_max_value() == 0: return 100.0 else: return self.get_current_value() * 100.0 / self.get_max_value() def get_current_value(self): return self._current_value def get_max_value(self): return self._max_value def _set_max_value(self, max_value): self._max_value = max_value class LoggingObserver(Observer): """Simple observer that just outputs status through logging. """ def __init__(self): super(Observer, self).__init__() # this is an easy way to make the first update() call print a line self.last_update = -101 # a fake ProgressBar, for the sake of ETA class FakePBar(object): def __init__(self): self.maxval = None self.currval = 0 self.finished = False self.start_time = None self.seconds_elapsed = 0 def finish(self): self.update(self.maxval) def update(self, value): assert 0 <= value <= self.maxval self.currval = value if self.finished: return False if not self.start_time: self.start_time = time.time() self.seconds_elapsed = time.time() - self.start_time if value == self.maxval: self.finished = True self.fake = FakePBar() self.eta = progressbar.ETA() def start(self, max_value): self.fake.maxval = max_value super(LoggingObserver, self).start(max_value) def finish(self): self.fake.finish() logging.info("Rendered %d of %d. %d%% complete. %s", self.get_max_value(), self.get_max_value(), 100.0, self.eta.update(self.fake)) super(LoggingObserver, self).finish() def update(self, current_value): super(LoggingObserver, self).update(current_value) self.fake.update(current_value) if self._need_update(): logging.info("Rendered %d of %d. %d%% complete. %s", self.get_current_value(), self.get_max_value(), self.get_percentage(), self.eta.update(self.fake)) self.last_update = current_value return True return False def _need_update(self): cur_val = self.get_current_value() if cur_val <= 100: return cur_val - self.last_update >= 10 elif cur_val <= 500: return cur_val - self.last_update >= 50 else: return cur_val - self.last_update >= 100 default_widgets = [ progressbar.Percentage(), ' ', progressbar.Bar(marker='=', left='[', right=']'), ' ', progressbar.CounterWidget(), ' ', progressbar.GenericSpeed(format='%.2ft/s'), ' ', progressbar.ETA(prefix='eta ') ] class ProgressBarObserver(progressbar.ProgressBar, Observer): """Display progress through a progressbar. """ # the progress bar is only updated in increments of this for performance UPDATE_INTERVAL = 25 def __init__(self, widgets=default_widgets, term_width=None, fd=sys.stderr): super(ProgressBarObserver, self).__init__(widgets=widgets, term_width=term_width, fd=fd) self.last_update = 0 - (self.UPDATE_INTERVAL + 1) def start(self, max_value): self._set_max_value(max_value) logging.info("Rendering %d total tiles." % max_value) super(ProgressBarObserver, self).start() def is_started(self): return self.start_time is not None def finish(self): self._end_time = time.time() super(ProgressBarObserver, self).finish() self.fd.write('\n') logging.info("Rendering complete!") def update(self, current_value): # maxval is an estimate, and progressbar barfs if currval > maxval # so... current_value = min(current_value, self.maxval) if super(ProgressBarObserver, self).update(current_value): self.last_update = self.get_current_value() percentage = Observer.get_percentage def get_current_value(self): return self.currval def get_max_value(self): return self.maxval def _set_max_value(self, max_value): self.maxval = max_value def _need_update(self): return (self.get_current_value() - self.last_update > self.UPDATE_INTERVAL) class JSObserver(Observer): """Display progress on index.html using JavaScript """ def __init__(self, outputdir, minrefresh=5, messages=False): """Initialise observer :outputdir: must be set to the map output directory path :minrefresh: specifies the minimum gap between requests, in seconds [optional] :messages: is a dictionary which allows the displayed messages to be customised [optional] """ self.last_update = -11 self.last_update_time = -1 self._current_value = -1 self.minrefresh = 1000 * minrefresh self.json = dict() # function to print formatted eta self.format = lambda seconds: '%02ih %02im %02is' % \ (seconds // 3600, (seconds % 3600) // 60, seconds % 60) if (not messages): self.messages = dict( totalTiles="Rendering %d tiles", renderCompleted="Render completed in %02d:%02d:%02d", renderProgress="Rendered %d of %d tiles (%d%% ETA:%s)") elif (isinstance(messages, dict)): if ('totalTiles' in messages and 'renderCompleted' in messages and 'renderProgress' in messages): self.messages = messages else: raise Exception("JSObserver: messages parameter must be a " "dictionary with three entries: totalTiles, " "renderCompleted and renderProgress") else: raise Exception("JSObserver: messages parameter must be a " "dictionary with three entries: totalTiles, " "renderCompleted and renderProgress") # On the initial render, the outputdir hasn't been created until after the observer is # initialised, so let's just do it here if necessary. if not os.path.exists(outputdir): os.mkdir(outputdir) self.logfile = open(os.path.join(outputdir, "progress.json"), "wb+", 0) self.json["message"] = "Render starting..." self.json["update"] = self.minrefresh self.json["messageTime"] = time.time() self.logfile.write(json.dumps(self.json).encode()) self.logfile.flush() def start(self, max_value): self.logfile.seek(0) self.logfile.truncate() self.json["message"] = self.messages["totalTiles"] % (max_value) self.json["update"] = self.minrefresh self.json["messageTime"] = time.time() self.logfile.write(json.dumps(self.json).encode()) self.logfile.flush() self.start_time = time.time() self._set_max_value(max_value) def is_started(self): return self.start_time is not None def finish(self): """Signals the end of the processes, should be called after the process is done. """ self.end_time = time.time() duration = self.end_time - self.start_time self.logfile.seek(0) self.logfile.truncate() hours = duration // 3600 duration = duration % 3600 minutes = duration // 60 seconds = duration % 60 self.json["message"] = self.messages["renderCompleted"] \ % (hours, minutes, seconds) # The 'renderCompleted' message will always be visible # (until the next render) self.json["update"] = 60000 self.json["messageTime"] = time.time() self.logfile.write(json.dumps(self.json).encode()) self.logfile.close() def is_finished(self): return self.end_time is not None def is_running(self): return self.is_started() and not self.is_finished() def add(self, amount): """Shortcut to update by increments instead of absolute values. Zero amounts are ignored. """ if amount: self.update(self.get_current_value() + amount) def update(self, current_value): """Set the progress value. Should be between 0 and max_value. Returns whether this update is actually displayed. """ self._current_value = current_value if self._need_update(): refresh = max(1500 * (time.time() - max(self.start_time, self.last_update_time)), self.minrefresh) // 1 self.logfile.seek(0) self.logfile.truncate() if self.get_current_value(): duration = time.time() - self.start_time eta = self.format(duration * self.get_max_value() / self.get_current_value() - duration) else: eta = "?" self.json["message"] = self.messages["renderProgress"] \ % (self.get_current_value(), self.get_max_value(), self.get_percentage(), str(eta)) self.json["update"] = refresh self.json["messageTime"] = time.time() self.logfile.write(json.dumps(self.json).encode()) self.logfile.flush() self.last_update_time = time.time() self.last_update = current_value return True return False def get_percentage(self): """Get the current progress percentage. Assumes 100% if max_value is 0 """ if self.get_max_value() == 0: return 100.0 else: return self.get_current_value() * 100.0 / self.get_max_value() def get_current_value(self): return self._current_value def get_max_value(self): return self._max_value def _set_max_value(self, max_value): self._max_value = max_value def _need_update(self): cur_val = self.get_current_value() if cur_val < 100: return cur_val - self.last_update > 10 elif cur_val < 500: return cur_val - self.last_update > 50 else: return cur_val - self.last_update > 100 class MultiplexingObserver(Observer): """Combine multiple observers into one. """ def __init__(self, *components): self.components = components super(MultiplexingObserver, self).__init__() def start(self, max_value): for o in self.components: o.start(max_value) super(MultiplexingObserver, self).start(max_value) def finish(self): for o in self.components: o.finish() super(MultiplexingObserver, self).finish() def update(self, current_value): for o in self.components: o.update(current_value) super(MultiplexingObserver, self).update(current_value) class ServerAnnounceObserver(Observer): """Send the output to a Minecraft server via FIFO or stdin""" def __init__(self, target='/dev/null', pct_interval=10): self.pct_interval = pct_interval self.target_handle = open(target, 'w') self.last_update = 0 super(ServerAnnounceObserver, self).__init__() def start(self, max_value): self._send_output('Starting render of %d total tiles' % max_value) super(ServerAnnounceObserver, self).start(max_value) def finish(self): self._send_output('Render complete!') super(ServerAnnounceObserver, self).finish() self.target_handle.close() def update(self, current_value): super(ServerAnnounceObserver, self).update(current_value) if self._need_update(): self._send_output('Rendered %d of %d tiles, %d%% complete' % (self.get_current_value(), self.get_max_value(), self.get_percentage())) self.last_update = current_value def _need_update(self): return(self.get_percentage() - (self.last_update * 100.0 / self.get_max_value()) >= self.pct_interval) def _send_output(self, output): self.target_handle.write('say %s\n' % output) self.target_handle.flush() # Fair amount of code duplication incoming # Perhaps both ServerAnnounceObserver and RConObserver # could share the percentage interval code. class RConObserver(Observer): """Send the output to a Minecraft server via rcon""" def __init__(self, target, password, port=25575, pct_interval=10): self.pct_interval = pct_interval self.conn = rcon.RConConnection(target, port) self.conn.login(password) self.last_update = 0 super(RConObserver, self).__init__() def start(self, max_value): self._send_output("Starting render of %d total tiles" % max_value) super(RConObserver, self).start(max_value) def finish(self): self._send_output("Render complete!") super(RConObserver, self).finish() self.conn.close() def update(self, current_value): super(RConObserver, self).update(current_value) if self._need_update(): self._send_output('Rendered %d of %d tiles, %d%% complete' % (self.get_current_value(), self.get_max_value(), self.get_percentage())) self.last_update = current_value def _need_update(self): if self.get_max_value() > 0: return(self.get_percentage() - (self.last_update * 100.0 / self.get_max_value()) >= self.pct_interval) else: return True def _send_output(self, output): self.conn.command("say", output)
16,499
Python
.py
389
32.426735
94
0.598677
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,293
settingsDefinition.py
overviewer_Minecraft-Overviewer/overviewer_core/settingsDefinition.py
# This file describes the format of the config file. Each item defined in this # module is expected to appear in the described format in a valid config file. # The only difference is, instead of actual values for the settings, values are # Setting objects which define how to validate a value as correct, and whether # the value is required or not. # Settings objects have this signature: # Setting(required, validator, default) # required # a boolean indicating that this value is required. A required setting will # always exist in a validated config. This option only has effect in the # event that a user doesn't provide a value and the default is None. In this # case, a required setting will raise an error. Otherwise, the situation will # result in the setting being omitted from the config with no error. # (If it wasn't obvious: a required setting does NOT mean that the user is # required to specify it, just that the setting is required to be set for the # operation of the program, either by the user or by using the default) # validator # a callable that takes the provided value and returns a cleaned/normalized # value to replace it with. It should raise a ValidationException if there is # a problem parsing or validating the value given. # default # This is used in the event that the user does not provide a value. In this # case, the default value is passed into the validator just the same. If # default is None, then depending on the value of required, it is either an # error to omit this setting or the setting is skipped entirely and will not # appear in the resulting parsed options. # The signature for validator callables is validator(value_given). Remember # that the default is passed in as value_given if the user did not provide a # value. # This file doesn't specify the format or even the type of the setting values, # it is up to the validators to ensure the values passed in are the right type, # either by coercion or by raising an error. # Oh, one other thing: For top level values whose required attribute is True, # the default value is set initially, before the config file is parsed, and is # available during the execution of the config file. This way, container types # can be initialized and then appended/added to when the config file is parsed. from collections import OrderedDict from .settingsValidators import * from .observer import ProgressBarObserver, LoggingObserver, JSObserver from .optimizeimages import pngnq, optipng, pngcrush import platform import sys # renders is a dictionary mapping strings to dicts. These dicts describe the # configuration for that render. Therefore, the validator for 'renders' is set # to a dict validator configured to validate keys as strings and values as... # values are set to validate as a "configdict", which is a dict mapping a set # of strings to some value. the make_configdictvalidator() function creates a # validator to use here configured with the given set of keys and Setting # objects with their respective validators. # config file. def get_default_config(): conf = dict() conf['renders'] = Setting(required=True, default=OrderedDict(), validator=make_dictValidator(validateStr, make_configDictValidator( { "world": Setting(required=True, validator=validateStr, default=None), "dimension": Setting(required=True, validator=validateDimension, default="default"), "title": Setting(required=True, validator=validateStr, default=None), "rendermode": Setting(required=True, validator=validateRenderMode, default='normal'), "northdirection": Setting(required=True, validator=validateNorthDirection, default=0), "forcerender": Setting(required=False, validator=validateBool, default=None), "imgformat": Setting(required=True, validator=validateImgFormat, default="png"), "imgquality": Setting(required=False, validator=validateImgQuality, default=95), "imglossless": Setting(required=False, validator=validateBool, default=True), "bgcolor": Setting(required=True, validator=validateBGColor, default="1a1a1a"), "defaultzoom": Setting(required=True, validator=validateDefaultZoom, default=1), "optimizeimg": Setting(required=True, validator=validateOptImg, default=[]), "nomarkers": Setting(required=False, validator=validateBool, default=None), "texturepath": Setting(required=False, validator=validateTexturePath, default=None), "renderchecks": Setting(required=False, validator=validateInt, default=None), "rerenderprob": Setting(required=True, validator=validateRerenderprob, default=0), "crop": Setting(required=False, validator=validateCrop, default=None), "changelist": Setting(required=False, validator=validateStr, default=None), "markers": Setting(required=False, validator=validateMarkers, default=[]), "overlay": Setting(required=False, validator=validateOverlays, default=[]), "showspawn": Setting(required=False, validator=validateBool, default=True), "base": Setting(required=False, validator=validateStr, default=""), "poititle": Setting(required=False, validator=validateStr, default="Markers"), "customwebassets": Setting(required=False, validator=validateWebAssetsPath, default=None), "maxzoom": Setting(required=False, validator=validateInt, default=None), "minzoom": Setting(required=False, validator=validateInt, default=0), "manualpois": Setting(required=False, validator=validateManualPOIs, default=[]), "showlocationmarker": Setting(required=False, validator=validateBool, default=True), "center": Setting(required=False, validator=validateCoords, default=None), # Remove this eventually (once people update their configs) "worldname": Setting(required=False, default=None, validator=error("The option 'worldname' is now called 'world'. Please update your config files")), } ))) # The worlds dict, mapping world names to world paths conf['worlds'] = Setting(required=True, validator=make_dictValidator(validateStr, validateWorldPath), default=OrderedDict()) conf['outputdir'] = Setting(required=True, validator=validateOutputDir, default=None) conf['processes'] = Setting(required=True, validator=int, default=-1) # TODO clean up this ugly in sys.argv hack if platform.system() == 'Windows' or not sys.stdout.isatty() or "--simple" in sys.argv: obs = LoggingObserver() else: obs = ProgressBarObserver(fd=sys.stdout) conf['observer'] = Setting(required=True, validator=validateObserver, default=obs) return conf
7,041
Python
.py
101
61.990099
128
0.719549
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,294
assetmanager.py
overviewer_Minecraft-Overviewer/overviewer_core/assetmanager.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import codecs import json import logging import os import time import traceback from PIL import Image from . import world from . import util from .files import FileReplacer, mirror_dir, get_fs_caps class AssetManager: """\ These objects provide an interface to metadata and persistent data, and at the same time, controls the generated javascript files in the output directory. There should only be one instances of these per execution. """ def __init__(self, outputdir, custom_assets_dir=None): """\ Initializes the AssetManager with the top-level output directory. It can read/parse and write/dump the overviewerConfig.js file into this top-level directory. """ self.outputdir = outputdir self.custom_assets_dir = custom_assets_dir self.renders = dict() self.fs_caps = get_fs_caps(self.outputdir) # look for overviewerConfig in self.outputdir config_loc = os.path.join(self.outputdir, "overviewerConfig.js") try: with open(config_loc) as c: ovconf_str = "{" + "\n".join(c.readlines()[1:-1]) + "}" self.overviewerConfig = json.loads(ovconf_str) except Exception as e: if os.path.exists(config_loc): logging.warning("A previous overviewerConfig.js was found, " "but I couldn't read it for some reason." "Continuing with a blank config") logging.debug(traceback.format_exc()) self.overviewerConfig = dict(tilesets=dict()) def get_tileset_config(self, name): "Return the correct dictionary from the parsed overviewerConfig.js" for conf in self.overviewerConfig['tilesets']: if conf['path'] == name: return conf return dict() def initialize(self, tilesets): """Similar to finalize() but calls the tilesets' get_initial_data() instead of get_persistent_data() to compile the generated javascript config. """ self._output_assets(tilesets, True) def finalize(self, tilesets): """Called to output the generated javascript and all static files to the output directory """ self._output_assets(tilesets, False) def _output_assets(self, tilesets, initial): if not initial: def get_data(tileset): return tileset.get_persistent_data() else: def get_data(tileset): return tileset.get_initial_data() # dictionary to hold the overviewerConfig.js settings that we will dump # to JSON using dumps dump = dict() dump['CONST'] = dict(tileSize=384) dump['CONST']['image'] = { 'defaultMarker': 'signpost.png', 'signMarker': 'signpost_icon.png', 'bedMarker': 'bed.png', 'spawnMarker': 'markers/marker_home.png', 'spawnMarker2x': 'markers/marker_home_2x.png', 'queryMarker': 'markers/marker_location.png', 'queryMarker2x': 'markers/marker_location_2x.png' } dump['CONST']['mapDivId'] = 'mcmap' dump['CONST']['UPPERLEFT'] = world.UPPER_LEFT dump['CONST']['UPPERRIGHT'] = world.UPPER_RIGHT dump['CONST']['LOWERLEFT'] = world.LOWER_LEFT dump['CONST']['LOWERRIGHT'] = world.LOWER_RIGHT dump['CONST']['image']['compass'] = { world.UPPER_LEFT: 'compass_upper-left.png', world.UPPER_RIGHT: 'compass_upper-right.png', world.LOWER_LEFT: 'compass_lower-left.png', world.LOWER_RIGHT: 'compass_lower-right.png' } # based on the tilesets we have, group them by worlds worlds = [] for tileset in tilesets: full_name = get_data(tileset)['world'] if full_name not in worlds: worlds.append(full_name) dump['worlds'] = worlds dump['map'] = dict() dump['map']['debug'] = False dump['map']['cacheTag'] = str(int(time.time())) dump['map']['north_direction'] = 'lower-left' # only temporary dump['map']['controls'] = { 'pan': True, 'zoom': True, 'spawn': True, 'compass': True, 'mapType': True, 'overlays': True, 'coordsBox': True, } dump['tilesets'] = [] for tileset in tilesets: dump['tilesets'].append(get_data(tileset)) # write a blank image blank = Image.new("RGBA", (1, 1), tileset.options.get('bgcolor')) if tileset.options.get('imgformat') != 'png': blank = blank.convert("RGB") blank.save(os.path.join(self.outputdir, tileset.options.get('name'), "blank." + tileset.options.get('imgformat'))) # write out config jsondump = json.dumps(dump, indent=4) with FileReplacer(os.path.join(self.outputdir, "overviewerConfig.js"), capabilities=self.fs_caps) as tmpfile: with codecs.open(tmpfile, 'w', encoding='UTF-8') as f: f.write("var overviewerConfig = " + jsondump + ";\n") # Copy assets, modify index.html self.output_noconfig() def output_noconfig(self): # copy web assets into destdir: global_assets = os.path.join(util.get_program_path(), "overviewer_core", "data", "web_assets") if not os.path.isdir(global_assets): global_assets = os.path.join(util.get_program_path(), "web_assets") mirror_dir(global_assets, self.outputdir, capabilities=self.fs_caps, force_writable=True) if self.custom_assets_dir: # We could have done something fancy here rather than just # overwriting the global files, but apparently this what we used to # do pre-rewrite. mirror_dir(self.custom_assets_dir, self.outputdir, capabilities=self.fs_caps, force_writable=True) # symlink old icons dir because apache sux iconsdir = os.path.join(self.outputdir, "icons") if (os.name == "posix" and os.symlink in os.supports_dir_fd and not os.path.islink(iconsdir) and not os.path.isdir(iconsdir)): od_fd = os.open(self.outputdir, os.O_DIRECTORY) try: os.symlink("markers", "icons", target_is_directory=True, dir_fd=od_fd) except OSError: # Example setup where this happens: # Linux renders onto Windows CIFS share logging.warning("Could not create the icons symlink") finally: os.close(od_fd) # write a dummy baseMarkers.js if none exists basemarkers_path = os.path.join(self.outputdir, "baseMarkers.js") if not os.path.exists(basemarkers_path): with open(basemarkers_path, "w") as f: f.write("// if you wants signs, please see genPOI.py\n") # create overviewer.js from the source js files js_src = os.path.join(util.get_program_path(), "overviewer_core", "data", "js_src") if not os.path.isdir(js_src): js_src = os.path.join(util.get_program_path(), "js_src") with FileReplacer(os.path.join(self.outputdir, "overviewer.js"), capabilities=self.fs_caps) as tmpfile: with open(tmpfile, "w") as fout: # first copy in js_src/overviewer.js with open(os.path.join(js_src, "overviewer.js"), 'r') as f: fout.write(f.read()) # now copy in the rest for js in os.listdir(js_src): if not js.endswith("overviewer.js") and js.endswith(".js"): with open(os.path.join(js_src, js)) as f: fout.write(f.read()) # Add time and version in index.html indexpath = os.path.join(self.outputdir, "index.html") index = codecs.open(indexpath, 'r', encoding='UTF-8').read() index = index.replace("{title}", "Minecraft Overviewer") index = index.replace("{time}", time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime())) versionstr = "%s (%s)" % (util.findGitVersion(), util.findGitHash()[:7]) index = index.replace("{version}", versionstr) with FileReplacer(indexpath, capabilities=self.fs_caps) as indexpath: with codecs.open(indexpath, 'w', encoding='UTF-8') as output: output.write(index)
9,497
Python
.py
196
37.632653
100
0.596096
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,295
progressbar.py
overviewer_Minecraft-Overviewer/overviewer_core/progressbar.py
#!/usr/bin/env python3 # -*- coding: iso-8859-1 -*- # # progressbar - Text progressbar library for python. # Copyright (c) 2005 Nilton Volpato # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """Text progressbar library for python. This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available. """ __author__ = "Nilton Volpato" __author_email__ = "first-name dot last-name @ gmail.com" __date__ = "2006-05-07" __version__ = "2.2" # Changelog # # 2006-05-07: v2.2 fixed bug in windows # 2005-12-04: v2.1 autodetect terminal width, added start method # 2005-12-04: v2.0 everything is now a widget (wow!) # 2005-12-03: v1.0 rewrite using widgets # 2005-06-02: v0.5 rewrite # 2004-??-??: v0.1 first version import sys, time from array import array try: from fcntl import ioctl import termios except ImportError: pass import signal class ProgressBarWidget(object): """This is an element of ProgressBar formatting. The ProgressBar object will call it's update value when an update is needed. It's size may change between call, but the results will not be good if the size changes drastically and repeatedly. """ def update(self, pbar): """Returns the string representing the widget. The parameter pbar is a reference to the calling ProgressBar, where one can access attributes of the class for knowing how the update must be made. At least this function must be overriden.""" pass class ProgressBarWidgetHFill(object): """This is a variable width element of ProgressBar formatting. The ProgressBar object will call it's update value, informing the width this object must the made. This is like TeX \\hfill, it will expand to fill the line. You can use more than one in the same line, and they will all have the same width, and together will fill the line. """ def update(self, pbar, width): """Returns the string representing the widget. The parameter pbar is a reference to the calling ProgressBar, where one can access attributes of the class for knowing how the update must be made. The parameter width is the total horizontal width the widget must have. At least this function must be overriden.""" pass class ETA(ProgressBarWidget): "Widget for the Estimated Time of Arrival" def __init__(self, prefix='ETA: ', format=None): self.prefix = prefix if format: self.format = format else: self.format = lambda seconds: '%02ih %02im %02is' % \ (seconds // 3600, (seconds % 3600) // 60, seconds % 60) def update(self, pbar): if pbar.finished: return 'Time: ' + self.format(pbar.seconds_elapsed) else: if pbar.currval: eta = pbar.seconds_elapsed * pbar.maxval / pbar.currval - pbar.seconds_elapsed return self.prefix + self.format(eta) else: return self.prefix + '-' * 6 class GenericSpeed(ProgressBarWidget): "Widget for showing the values/s" def __init__(self, format='%6.2f ?/s'): if callable(format): self.format = format else: self.format = lambda speed: format % speed def update(self, pbar): if pbar.seconds_elapsed < 2e-6: speed = 0.0 else: speed = float(pbar.currval) / pbar.seconds_elapsed return self.format(speed) class FileTransferSpeed(ProgressBarWidget): "Widget for showing the transfer speed (useful for file transfers)." def __init__(self): self.fmt = '%6.2f %s' self.units = ['B','K','M','G','T','P'] def update(self, pbar): if pbar.seconds_elapsed < 2e-6:#== 0: bps = 0.0 else: bps = float(pbar.currval) / pbar.seconds_elapsed spd = bps for u in self.units: if spd < 1000: break spd /= 1000 return self.fmt % (spd, u+'/s') class RotatingMarker(ProgressBarWidget): "A rotating marker for filling the bar of progress." def __init__(self, markers='|/-\\'): self.markers = markers self.curmark = -1 def update(self, pbar): if pbar.finished: return self.markers[0] self.curmark = (self.curmark + 1)%len(self.markers) return self.markers[self.curmark] class Percentage(ProgressBarWidget): "Just the percentage done." def __init__(self, format='%3d%%'): self.format = format def update(self, pbar): return self.format % pbar.percentage() class CounterWidget(ProgressBarWidget): "Simple display of (just) the current value" def update(self, pbar): return str(pbar.currval) class FractionWidget(ProgressBarWidget): def __init__(self, sep=' / '): self.sep = sep def update(self, pbar): return '%2d%s%2d' % (pbar.currval, self.sep, pbar.maxval) class Bar(ProgressBarWidgetHFill): "The bar of progress. It will strech to fill the line." def __init__(self, marker='#', left='|', right='|'): self.marker = marker self.left = left self.right = right def _format_marker(self, pbar): if isinstance(self.marker, str): return self.marker else: return self.marker.update(pbar) def update(self, pbar, width): percent = pbar.percentage() cwidth = int(width - len(self.left) - len(self.right)) marked_width = int(percent * cwidth / 100) m = self._format_marker(pbar) bar = (self.left + (m*marked_width).ljust(cwidth) + self.right) return bar class ReverseBar(Bar): "The reverse bar of progress, or bar of regress. :)" def update(self, pbar, width): percent = pbar.percentage() cwidth = width - len(self.left) - len(self.right) marked_width = int(percent * cwidth / 100) m = self._format_marker(pbar) bar = (self.left + (m*marked_width).rjust(cwidth) + self.right) return bar default_widgets = [Percentage(), ' ', Bar()] class ProgressBar(object): """This is the ProgressBar class, it updates and prints the bar. The term_width parameter may be an integer. Or None, in which case it will try to guess it, if it fails it will default to 80 columns. The simple use is like this: >>> pbar = ProgressBar().start() >>> for i in xrange(100): ... # do something ... pbar.update(i+1) ... >>> pbar.finish() But anything you want to do is possible (well, almost anything). You can supply different widgets of any type in any order. And you can even write your own widgets! There are many widgets already shipped and you should experiment with them. When implementing a widget update method you may access any attribute or function of the ProgressBar object calling the widget's update method. The most important attributes you would like to access are: - currval: current value of the progress, 0 <= currval <= maxval - maxval: maximum (and final) value of the progress - finished: True if the bar is have finished (reached 100%), False o/w - start_time: first time update() method of ProgressBar was called - seconds_elapsed: seconds elapsed since start_time - percentage(): percentage of the progress (this is a method) """ def __init__(self, maxval=100, widgets=default_widgets, term_width=None, fd=sys.stderr): assert maxval > 0 self.maxval = maxval self.widgets = widgets self.fd = fd self.signal_set = False if term_width is None: try: self.handle_resize(None,None) signal.signal(signal.SIGWINCH, self.handle_resize) signal.siginterrupt(signal.SIGWINCH, False) self.signal_set = True except: self.term_width = 79 else: self.term_width = term_width self.currval = 0 self.finished = False self.start_time = None self.seconds_elapsed = 0 def handle_resize(self, signum, frame): h,w=array('h', ioctl(self.fd,termios.TIOCGWINSZ,'\0'*8))[:2] self.term_width = w def percentage(self): "Returns the percentage of the progress." return self.currval*100.0 / self.maxval def _format_widgets(self): r = [] hfill_inds = [] num_hfill = 0 currwidth = 0 for i, w in enumerate(self.widgets): if isinstance(w, ProgressBarWidgetHFill): r.append(w) hfill_inds.append(i) num_hfill += 1 elif isinstance(w, str): r.append(w) currwidth += len(w) else: weval = w.update(self) currwidth += len(weval) r.append(weval) for iw in hfill_inds: r[iw] = r[iw].update(self, (self.term_width-currwidth)/num_hfill) return r def _format_line(self): return ''.join(self._format_widgets()).ljust(self.term_width) def _need_update(self): return True def update(self, value): "Updates the progress bar to a new value." assert 0 <= value <= self.maxval self.currval = value if not self._need_update() or self.finished: return False if not self.start_time: self.start_time = time.time() self.seconds_elapsed = time.time() - self.start_time if value != self.maxval: self.fd.write(self._format_line() + '\r') else: self.finished = True self.fd.write(self._format_line() + '\n') self.fd.flush() return True def start(self): """Start measuring time, and prints the bar at 0%. It returns self so you can use it like this: >>> pbar = ProgressBar().start() >>> for i in xrange(100): ... # do something ... pbar.update(i+1) ... >>> pbar.finish() """ self.update(0) return self def finish(self): """Used to tell the progress is finished.""" self.update(self.maxval) if self.signal_set: signal.signal(signal.SIGWINCH, signal.SIG_DFL) if __name__=='__main__': import os def example1(): widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()] pbar = ProgressBar(widgets=widgets, maxval=10000000).start() for i in range(1000000): # do something pbar.update(10*i+1) pbar.finish() print def example2(): class CrazyFileTransferSpeed(FileTransferSpeed): "It's bigger between 45 and 80 percent" def update(self, pbar): if 45 < pbar.percentage() < 80: return 'Bigger Now ' + FileTransferSpeed.update(self,pbar) else: return FileTransferSpeed.update(self,pbar) widgets = [CrazyFileTransferSpeed(),' <<<', Bar(), '>>> ', Percentage(),' ', ETA()] pbar = ProgressBar(widgets=widgets, maxval=10000000) # maybe do something pbar.start() for i in range(2000000): # do something pbar.update(5*i+1) pbar.finish() print def example3(): widgets = [Bar('>'), ' ', ETA(), ' ', ReverseBar('<')] pbar = ProgressBar(widgets=widgets, maxval=10000000).start() for i in range(1000000): # do something pbar.update(10*i+1) pbar.finish() print def example4(): widgets = ['Test: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'), ' ', ETA(), ' ', FileTransferSpeed()] pbar = ProgressBar(widgets=widgets, maxval=500) pbar.start() for i in range(100,500+1,50): time.sleep(0.2) pbar.update(i) pbar.finish() print example1() example2() example3() example4()
13,669
Python
.py
345
31.86087
94
0.625283
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,296
files.py
overviewer_Minecraft-Overviewer/overviewer_core/files.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. import os import os.path import tempfile import shutil import logging import stat import errno default_caps = {"chmod_works": True, "rename_works": True} def get_fs_caps(dir_to_test): return {"chmod_works": does_chmod_work(dir_to_test), "rename_works": does_rename_work(dir_to_test) } def does_chmod_work(dir_to_test): "Detects if chmod works in a given directory" # a CIFS mounted FS is the only thing known to reliably not provide chmod if not os.path.isdir(dir_to_test): return True f1 = tempfile.NamedTemporaryFile(dir=dir_to_test) try: f1_stat = os.stat(f1.name) os.chmod(f1.name, f1_stat.st_mode | stat.S_IRUSR) chmod_works = True logging.debug("Detected that chmods work in %r" % dir_to_test) except OSError: chmod_works = False logging.debug("Detected that chmods do NOT work in %r" % dir_to_test) return chmod_works def does_rename_work(dir_to_test): try: with tempfile.NamedTemporaryFile(dir=dir_to_test) as f1: with tempfile.NamedTemporaryFile(dir=dir_to_test) as f2: try: os.rename(f1.name,f2.name) except OSError: renameworks = False logging.debug("Detected that overwriting renames do NOT work in %r" % dir_to_test) else: renameworks = True logging.debug("Detected that overwriting renames work in %r" % dir_to_test) # re-make this file so it can be deleted without error open(f1.name, 'w').close() except FileNotFoundError: # Special handling for CIFS, which simply cannot cope with any rename whatsoever renameworks = False return renameworks ## useful recursive copy, that ignores common OS cruft def mirror_dir(src, dst, entities=None, capabilities=default_caps, force_writable=False): '''copies all of the entities from src to dst''' chmod_works = capabilities.get("chmod_works") if not os.path.exists(dst): os.mkdir(dst) if entities and type(entities) != list: raise Exception("Expected a list, got a %r instead" % type(entities)) # files which are problematic and should not be copied # usually, generated by the OS skip_files = ['Thumbs.db', '.DS_Store'] for entry in os.listdir(src): if entry in skip_files: continue if entities and entry not in entities: continue if os.path.isdir(os.path.join(src,entry)): mirror_dir(os.path.join(src, entry), os.path.join(dst, entry), capabilities=capabilities, force_writable=force_writable) elif os.path.isfile(os.path.join(src,entry)): try: if chmod_works: shutil.copy(os.path.join(src, entry), os.path.join(dst, entry)) if force_writable: # for shitty neckbeard ware dst_stat = os.stat(os.path.join(dst, entry)) os.chmod(os.path.join(dst, entry), dst_stat.st_mode | stat.S_IWUSR) else: shutil.copyfile(os.path.join(src, entry), os.path.join(dst, entry)) except IOError as outer: try: # maybe permission problems? src_stat = os.stat(os.path.join(src, entry)) os.chmod(os.path.join(src, entry), src_stat.st_mode | stat.S_IRUSR) dst_stat = os.stat(os.path.join(dst, entry)) os.chmod(os.path.join(dst, entry), dst_stat.st_mode | stat.S_IWUSR) except OSError: # we don't care if this fails pass # try again; if this stills throws an error, let it propagate up if chmod_works: shutil.copy(os.path.join(src, entry), os.path.join(dst, entry)) if force_writable: dst_stat = os.stat(os.path.join(dst, entry)) os.chmod(os.path.join(dst, entry), dst_stat.st_mode | stat.S_IWUSR) else: shutil.copyfile(os.path.join(src, entry), os.path.join(dst, entry)) # Define a context manager to handle atomic renaming or "just forget it write # straight to the file" depending on whether os.rename provides atomic # overwrites. # Detect whether os.rename will overwrite files doc = """This class acts as a context manager for files that are to be written out overwriting an existing file. The parameter is the destination filename. The value returned into the context is the filename that should be used. On systems that support an atomic os.rename(), the filename will actually be a temporary file, and it will be atomically replaced over the destination file on exit. On systems that don't support an atomic rename, the filename returned is the filename given. If an error is encountered, the file is attempted to be removed, and the error is propagated. Example: with FileReplacer("config") as configname: with open(configout, 'w') as configout: configout.write(newconfig) """ class FileReplacer(object): __doc__ = doc def __init__(self, destname, capabilities=default_caps): self.caps = capabilities self.destname = destname if self.caps.get("rename_works"): self.tmpname = destname + ".tmp" def __enter__(self): if self.caps.get("rename_works"): # rename works here. Return a temporary filename return self.tmpname return self.destname def __exit__(self, exc_type, exc_val, exc_tb): if self.caps.get("rename_works"): if exc_type: # error try: os.remove(self.tmpname) except Exception as e: logging.warning("An error was raised, so I was doing " "some cleanup first, but I couldn't remove " "'%s'!", self.tmpname) else: # copy permission bits, if needed if self.caps.get("chmod_works") and os.path.exists(self.destname): try: shutil.copymode(self.destname, self.tmpname) except OSError as e: # Ignore errno ENOENT: file does not exist. Due to a race # condition, two processes could conceivably try and update # the same temp file at the same time if e.errno != errno.ENOENT: raise # atomic rename into place try: os.rename(self.tmpname, self.destname) except OSError as e: # Ignore errno ENOENT: file does not exist. Due to a race # condition, two processes could conceivably try and update # the same temp file at the same time if e.errno != errno.ENOENT: raise
7,912
Python
.py
164
37.073171
132
0.608036
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,297
settingsValidators.py
overviewer_Minecraft-Overviewer/overviewer_core/settingsValidators.py
# see settingsDefinition.py import logging import os import os.path from collections import OrderedDict from . import rendermodes from . import util from .optimizeimages import Optimizer from .world import LOWER_LEFT, LOWER_RIGHT, UPPER_LEFT, UPPER_RIGHT class ValidationException(Exception): pass class Setting(object): __slots__ = ['required', 'validator', 'default'] def __init__(self, required, validator, default): self.required = required self.validator = validator self.default = default def expand_path(p): p = os.path.expanduser(p) p = os.path.expandvars(p) p = os.path.abspath(p) return p def checkBadEscape(s): # If any of these weird characters are in the path, raise an exception # instead of fixing this should help us educate our users about pathslashes bad_escapes = ['\a', '\b', '\t', '\n', '\v', '\f', '\r'] for b in bad_escapes: if b in s: raise ValueError("Invalid character %s in path. Please use " "forward slashes ('/'). Please see our docs for " "more info." % repr(b)) for c in range(10): if chr(c) in s: raise ValueError("Invalid character '\\%s' in path. " "Please use forward slashes ('/'). " "See our docs for more info." % c) return s def validateMarkers(filterlist): if type(filterlist) != list: raise ValidationException("Markers must specify a list of filters.") for x in filterlist: if type(x) != dict: raise ValidationException("Markers must specify a list of dictionaries.") if "name" not in x: raise ValidationException("Filter must define a name.") if "filterFunction" not in x: raise ValidationException("Filter must define a filter function.") if not callable(x['filterFunction']): raise ValidationException("%r must be a function." % x['filterFunction']) return filterlist def validateOverlays(renderlist): if type(renderlist) != list: raise ValidationException("Overlay must specify a list of renders.") for x in renderlist: if validateStr(x) == '': raise ValidationException("%r must be a string." % x) return renderlist def validateWorldPath(worldpath): checkBadEscape(worldpath) abs_path = expand_path(worldpath) if not os.path.exists(os.path.join(abs_path, "level.dat")): raise ValidationException("No level.dat file in '%s'. Are you sure you have the right " "path?" % (abs_path,)) return abs_path def validateRenderMode(mode): # make sure that mode is a list of things that are all rendermode primative if isinstance(mode, str): # Try and find an item named "mode" in the rendermodes module mode = mode.lower().replace("-", "_") try: mode = getattr(rendermodes, mode) except AttributeError: raise ValidationException("You must specify a valid rendermode, not '%s'. " "See the docs for valid rendermodes." % mode) if isinstance(mode, rendermodes.RenderPrimitive): mode = [mode] if not isinstance(mode, list): raise ValidationException("%r is not a valid list of rendermodes. " "It should be a list." % mode) for m in mode: if not isinstance(m, rendermodes.RenderPrimitive): raise ValidationException("%r is not a valid rendermode primitive." % m) return mode def validateNorthDirection(direction): # normalize to integers intdir = 0 # default if type(direction) == int: intdir = direction elif isinstance(direction, str): direction = direction.lower().replace("-", "").replace("_", "") if direction == "upperleft": intdir = UPPER_LEFT elif direction == "upperright": intdir = UPPER_RIGHT elif direction == "lowerright": intdir = LOWER_RIGHT elif direction == "lowerleft": intdir = LOWER_LEFT else: raise ValidationException("'%s' is not a valid north direction." % direction) if intdir < 0 or intdir > 3: raise ValidationException("%r is not a valid north direction." % direction) return intdir def validateRerenderprob(s): val = float(s) if val < 0 or val >= 1: raise ValidationException("%r is not a valid rerender probability value. " "Should be between 0.0 and 1.0." % s) return val def validateImgFormat(fmt): if fmt not in ("png", "jpg", "jpeg", "webp"): raise ValidationException("%r is not a valid image format." % fmt) if fmt == "jpeg": fmt = "jpg" if fmt == "webp": try: from PIL import _webp except ImportError: raise ValidationException("WebP is not supported by your PIL/Pillow installation.") return fmt def validateImgQuality(qual): intqual = int(qual) if (intqual < 0 or intqual > 100): raise ValidationException("%r is not a valid image quality." % intqual) return intqual def validateBGColor(color): """BG color must be an HTML color, with an option leading # (hash symbol) returns an (r,b,g) 3-tuple """ if type(color) == str: if color[0] != "#": color = "#" + color if len(color) != 7: raise ValidationException("%r is not a valid color. Expected HTML color syntax. " "(i.e. #RRGGBB)" % color) try: r = int(color[1:3], 16) g = int(color[3:5], 16) b = int(color[5:7], 16) return (r, g, b, 0) except ValueError: raise ValidationException("%r is not a valid color. Expected HTML color syntax. " "(i.e. #RRGGBB)" % color) elif type(color) == tuple: if len(color) != 4: raise ValidationException("%r is not a valid color. Expected a 4-tuple." % (color,)) return color def validateOptImg(optimizers): if isinstance(optimizers, int): from .optimizeimages import pngcrush logging.warning("You're using a deprecated definition of optimizeimg. " "We'll do what you say for now, but please fix this as soon as possible.") optimizers = [pngcrush()] if not isinstance(optimizers, list): raise ValidationException("What you passed to optimizeimg is not a list. " "Make sure you specify them like [foo()], with square brackets.") if optimizers: for opt, next_opt in list(zip(optimizers, optimizers[1:])) + [(optimizers[-1], None)]: if not isinstance(opt, Optimizer): raise ValidationException("Invalid Optimizer!") opt.check_availability() # Check whether the chaining is somewhat sane if next_opt: if opt.is_crusher() and not next_opt.is_crusher(): logging.warning("You're feeding a crushed output into an optimizer that " "does not crush. This is most likely pointless, and wastes " "time.") return optimizers def validateTexturePath(path): # Expand user dir in directories strings path = expand_path(path) if not os.path.exists(path): raise ValidationException("%r does not exist." % path) return path def validateBool(b): return bool(b) def validateFloat(f): return float(f) def validateInt(i): return int(i) def validateStr(s): return str(s) def validateDimension(d): # returns (original, argument to get_type) # these are provided as arguments to RegionSet.get_type() pretty_names = { "nether": "DIM-1", "overworld": None, "end": "DIM1", "default": 0, } try: return (d, pretty_names[d]) except KeyError: return (d, d) def validateOutputDir(d): checkBadEscape(d) if not d.strip(): raise ValidationException("You must specify a valid output directory.") return expand_path(d) def validateCrop(value): if not isinstance(value, list): value = [value] cropZones = [] for zone in value: if not isinstance(zone, tuple) or len(zone) != 4: raise ValidationException("The value for the 'crop' setting must be an array of " "tuples of length 4.") a, b, c, d = tuple(int(x) for x in zone) if a >= c: a, c = c, a if b >= d: b, d = d, b cropZones.append((a, b, c, d)) return cropZones def validateObserver(observer): if all([hasattr(observer, m) for m in ['start', 'add', 'update', 'finish']]): return observer else: raise ValidationException("%r does not look like an observer." % repr(observer)) def validateDefaultZoom(z): if z > 0: return int(z) else: raise ValidationException("The default zoom is set below 1.") def validateWebAssetsPath(p): try: validatePath(p) except ValidationException as e: raise ValidationException("Bad custom web assets path: %s" % e.message) def validatePath(p): checkBadEscape(p) abs_path = expand_path(p) if not os.path.exists(abs_path): raise ValidationException("'%s' does not exist. Path initially given as '%s'" % (abs_path, p)) def validateManualPOIs(d): for poi in d: if 'x' not in poi or 'y' not in poi or 'z' not in poi or 'id' not in poi: raise ValidationException("Not all POIs have x/y/z coordinates or an id: %r." % poi) return d def validateCoords(c): if not isinstance(c, (list, tuple)): raise ValidationException("Your coordinates '{}' are not a list or a tuple.".format(c)) if len(c) not in [2, 3]: raise ValidationException("'{}' is not a valid list or tuple of coordinates, " "because we expect either 2 or 3 elements.".format(c)) if len(c) == 2: x, z = [validateInt(i) for i in c] y = 64 else: x, y, z = [validateInt(i) for i in c] return (x, y, z) def make_dictValidator(keyvalidator, valuevalidator): """Compose and return a dict validator -- a validator that validates each key and value in a dictionary. The arguments are the validator function to use for the keys, and the validator function to use for the values. """ def v(d): newd = OrderedDict() for key, value in d.items(): newd[keyvalidator(key)] = valuevalidator(value) return newd # Put these objects as attributes of the function so they can be accessed # externally later if need be v.keyvalidator = keyvalidator v.valuevalidator = valuevalidator return v def make_configDictValidator(config, ignore_undefined=False): """Okay, stay with me here, this may get confusing. This function returns a validator that validates a "configdict". This is a term I just made up to refer to a dict that holds config information: keys are strings and values are whatever that config value is. The argument to /this/ function is a dictionary defining the valid keys for the configdict. It therefore maps those key names to Setting objects. When the returned validator function validates, it calls all the appropriate validators for each configdict setting I hope that makes sense. ignore_undefined, if True, will ignore any items in the dict to be validated which don't have a corresponding definition in the config. Otherwise, undefined entries will raise an error. """ def configDictValidator(d): newdict = OrderedDict() # values are config keys that the user specified that don't match any # valid key # keys are the correct configuration key undefined_key_matches = {} # Go through the keys the user gave us and make sure they're all valid. for key in d.keys(): if key not in config: # Try to find a probable match match = _get_closest_match(key, iter(config.keys())) if match and ignore_undefined: # Save this for later. It only matters if this is a typo of # some required key that wasn't specified. (If all required # keys are specified, then this should be ignored) undefined_key_matches[match] = key newdict[key] = d[key] elif match: raise ValidationException( "'%s' is not a configuration item. Did you mean '%s'?" % (key, match)) elif not ignore_undefined: raise ValidationException("'%s' is not a configuration item." % key) else: # the key is to be ignored. Copy it as-is to the `newdict` # to be returned. It shouldn't conflict, and may be used as # a default value for a render configdict later on. newdict[key] = d[key] # Iterate through the defined keys in the configuration (`config`), # checking each one to see if the user specified it (in `d`). Then # validate it and copy the result to `newdict` for configkey, configsetting in config.items(): if configkey in d: # This key /was/ specified in the user's dict. Make sure it validates. newdict[configkey] = configsetting.validator(d[configkey]) elif configsetting.default is not None: # There is a default, use that instead newdict[configkey] = configsetting.validator(configsetting.default) elif configsetting.required: # The user did not give us this key, there is no default, AND # it's required. This is an error. if configkey in undefined_key_matches: raise ValidationException( "Key '%s' is not a valid configuration item. Did you mean '%s'?" % (undefined_key_matches[configkey], configkey)) else: raise ValidationException("Required key '%s' was not specified. You must give " "a value for this setting." % configkey) return newdict # Put these objects as attributes of the function so they can be accessed # externally later if need be configDictValidator.config = config configDictValidator.ignore_undefined = ignore_undefined return configDictValidator def error(errstr): def validator(_): raise ValidationException(errstr) return validator # Activestate recipe 576874 def _levenshtein(s1, s2): l1 = len(s1) l2 = len(s2) matrix = [list(range(l1 + 1))] * (l2 + 1) for zz in range(l2 + 1): matrix[zz] = list(range(zz, zz + l1 + 1)) for zz in range(0, l2): for sz in range(0, l1): if s1[sz] == s2[zz]: matrix[zz + 1][sz + 1] = min(matrix[zz + 1][sz] + 1, matrix[zz][sz + 1] + 1, matrix[zz][sz]) else: matrix[zz + 1][sz + 1] = min(matrix[zz + 1][sz] + 1, matrix[zz][sz + 1] + 1, matrix[zz][sz] + 1) return matrix[l2][l1] def _get_closest_match(s, keys): """Returns a probable match for the given key `s` out of the possible keys in `keys`. Returns None if no matches are very close. """ # Adjust this. 3 is probably a good number, it's probably not a typo if the # distance is >3 threshold = 3 minmatch = None mindist = threshold + 1 for key in keys: d = _levenshtein(s, key) if d < mindist: minmatch = key mindist = d if mindist <= threshold: return minmatch return None
16,345
Python
.py
373
34.120643
99
0.606021
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,298
textures.py
overviewer_Minecraft-Overviewer/overviewer_core/textures.py
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # Minecraft Overviewer is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Overviewer. If not, see <http://www.gnu.org/licenses/>. from collections import OrderedDict import sys import imp import os import os.path import zipfile from io import BytesIO import math from random import randint import numpy from PIL import Image, ImageEnhance, ImageOps, ImageDraw import logging import functools from . import util BLOCKTEX = "assets/minecraft/textures/block/" # global variables to collate information in @material decorators blockmap_generators = {} known_blocks = set() used_datas = set() max_blockid = 0 max_data = 0 transparent_blocks = set() solid_blocks = set() fluid_blocks = set() nospawn_blocks = set() nodata_blocks = set() # This is here for circular import reasons. # Please don't ask, I choose to repress these memories. # ... okay fine I'll tell you. # Initialising the C extension requires access to the globals above. # Due to the circular import, this wouldn't work, unless we reload the # module in the C extension or just move the import below its dependencies. from .c_overviewer import alpha_over class TextureException(Exception): "To be thrown when a texture is not found." pass color_map = ["white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black"] ## ## Textures object ## class Textures(object): """An object that generates a set of block sprites to use while rendering. It accepts a background color, north direction, and local textures path. """ def __init__(self, texturepath=None, bgcolor=(26, 26, 26, 0), northdirection=0): self.bgcolor = bgcolor self.rotation = northdirection self.find_file_local_path = texturepath # not yet configurable self.texture_size = 24 self.texture_dimensions = (self.texture_size, self.texture_size) # this is set in in generate() self.generated = False # see load_image_texture() self.texture_cache = {} # once we find a jarfile that contains a texture, we cache the ZipFile object here self.jars = OrderedDict() ## ## pickle support ## def __getstate__(self): # we must get rid of the huge image lists, and other images attributes = self.__dict__.copy() for attr in ['blockmap', 'biome_grass_texture', 'watertexture', 'lavatexture', 'firetexture', 'portaltexture', 'lightcolor', 'grasscolor', 'foliagecolor', 'watercolor', 'texture_cache']: try: del attributes[attr] except KeyError: pass attributes['jars'] = OrderedDict() return attributes def __setstate__(self, attrs): # regenerate textures, if needed for attr, val in list(attrs.items()): setattr(self, attr, val) self.texture_cache = {} if self.generated: self.generate() ## ## The big one: generate() ## def generate(self): # Make sure we have the foliage/grasscolor images available try: self.load_foliage_color() self.load_grass_color() except TextureException as e: logging.error( "Your system is missing either assets/minecraft/textures/colormap/foliage.png " "or assets/minecraft/textures/colormap/grass.png. Either complement your " "resource pack with these texture files, or install the vanilla Minecraft " "client to use as a fallback.") raise e # generate biome grass mask self.biome_grass_texture = self.build_block(self.load_image_texture("assets/minecraft/textures/block/grass_block_top.png"), self.load_image_texture("assets/minecraft/textures/block/grass_block_side_overlay.png")) # generate the blocks global blockmap_generators global known_blocks, used_datas self.blockmap = [None] * max_blockid * max_data for (blockid, data), texgen in list(blockmap_generators.items()): tex = texgen(self, blockid, data) self.blockmap[blockid * max_data + data] = self.generate_texture_tuple(tex) if self.texture_size != 24: # rescale biome grass self.biome_grass_texture = self.biome_grass_texture.resize(self.texture_dimensions, Image.ANTIALIAS) # rescale the rest for i, tex in enumerate(blockmap): if tex is None: continue block = tex[0] scaled_block = block.resize(self.texture_dimensions, Image.ANTIALIAS) blockmap[i] = self.generate_texture_tuple(scaled_block) self.generated = True ## ## Helpers for opening textures ## def find_file(self, filename, mode="rb", verbose=False): """Searches for the given file and returns an open handle to it. This searches the following locations in this order: * In the directory textures_path given in the initializer if not already open * In an already open resource pack or client jar file * In the resource pack given by textures_path * The program dir (same dir as overviewer.py) for extracted textures * On Darwin, in /Applications/Minecraft for extracted textures * Inside a minecraft client jar. Client jars are searched for in the following location depending on platform: * On Windows, at %APPDATA%/.minecraft/versions/ * On Darwin, at $HOME/Library/Application Support/minecraft/versions * at $HOME/.minecraft/versions/ Only the latest non-snapshot version >1.6 is used * The overviewer_core/data/textures dir """ if verbose: logging.info("Starting search for {0}".format(filename)) # Look for the file is stored in with the overviewer # installation. We include a few files that aren't included with Minecraft # textures. This used to be for things such as water and lava, since # they were generated by the game and not stored as images. Nowdays I # believe that's not true, but we still have a few files distributed # with overviewer. # Do this first so we don't try all .jar files for stuff like "water.png" programdir = util.get_program_path() if verbose: logging.info("Looking for texture in overviewer_core/data/textures") path = os.path.join(programdir, "overviewer_core", "data", "textures", filename) if os.path.isfile(path): if verbose: logging.info("Found %s in '%s'", filename, path) return open(path, mode) elif hasattr(sys, "frozen") or imp.is_frozen("__main__"): # windows special case, when the package dir doesn't exist path = os.path.join(programdir, "textures", filename) if os.path.isfile(path): if verbose: logging.info("Found %s in '%s'", filename, path) return open(path, mode) # A texture path was given on the command line. Search this location # for the file first. if self.find_file_local_path: if (self.find_file_local_path not in self.jars and os.path.isfile(self.find_file_local_path)): # Must be a resource pack. Look for the requested file within # it. try: pack = zipfile.ZipFile(self.find_file_local_path) # pack.getinfo() will raise KeyError if the file is # not found. pack.getinfo(filename) if verbose: logging.info("Found %s in '%s'", filename, self.find_file_local_path) self.jars[self.find_file_local_path] = pack # ok cool now move this to the start so we pick it first self.jars.move_to_end(self.find_file_local_path, last=False) return pack.open(filename) except (zipfile.BadZipfile, KeyError, IOError): pass elif os.path.isdir(self.find_file_local_path): full_path = os.path.join(self.find_file_local_path, filename) if os.path.isfile(full_path): if verbose: logging.info("Found %s in '%s'", filename, full_path) return open(full_path, mode) # We already have some jars open, better use them. if len(self.jars) > 0: for jarpath in self.jars: try: jar = self.jars[jarpath] jar.getinfo(filename) if verbose: logging.info("Found (cached) %s in '%s'", filename, jarpath) return jar.open(filename) except (KeyError, IOError) as e: pass # If we haven't returned at this point, then the requested file was NOT # found in the user-specified texture path or resource pack. if verbose: logging.info("Did not find the file in specified texture path") # Look in the location of the overviewer executable for the given path path = os.path.join(programdir, filename) if os.path.isfile(path): if verbose: logging.info("Found %s in '%s'", filename, path) return open(path, mode) if sys.platform.startswith("darwin"): path = os.path.join("/Applications/Minecraft", filename) if os.path.isfile(path): if verbose: logging.info("Found %s in '%s'", filename, path) return open(path, mode) if verbose: logging.info("Did not find the file in overviewer executable directory") if verbose: logging.info("Looking for installed minecraft jar files...") # Find an installed minecraft client jar and look in it for the texture # file we need. versiondir = "" if "APPDATA" in os.environ and sys.platform.startswith("win"): versiondir = os.path.join(os.environ['APPDATA'], ".minecraft", "versions") elif "HOME" in os.environ: # For linux: versiondir = os.path.join(os.environ['HOME'], ".minecraft", "versions") if not os.path.exists(versiondir) and sys.platform.startswith("darwin"): # For Mac: versiondir = os.path.join(os.environ['HOME'], "Library", "Application Support", "minecraft", "versions") try: if verbose: logging.info("Looking in the following directory: \"%s\"" % versiondir) versions = os.listdir(versiondir) if verbose: logging.info("Found these versions: {0}".format(versions)) except OSError: # Directory doesn't exist? Ignore it. It will find no versions and # fall through the checks below to the error at the bottom of the # method. versions = [] available_versions = [] for version in versions: # Look for the latest non-snapshot that is at least 1.8. This # version is only compatible with >=1.8, and we cannot in general # tell if a snapshot is more or less recent than a release. # Allow two component names such as "1.8" and three component names # such as "1.8.1" if version.count(".") not in (1,2): continue try: versionparts = [int(x) for x in version.split(".")] except ValueError: continue if versionparts < [1,8]: continue available_versions.append(versionparts) available_versions.sort(reverse=True) if not available_versions: if verbose: logging.info("Did not find any non-snapshot minecraft jars >=1.8.0") while(available_versions): most_recent_version = available_versions.pop(0) if verbose: logging.info("Trying {0}. Searching it for the file...".format(".".join(str(x) for x in most_recent_version))) jarname = ".".join(str(x) for x in most_recent_version) jarpath = os.path.join(versiondir, jarname, jarname + ".jar") if os.path.isfile(jarpath): try: jar = zipfile.ZipFile(jarpath) jar.getinfo(filename) if verbose: logging.info("Found %s in '%s'", filename, jarpath) self.jars[jarpath] = jar return jar.open(filename) except (KeyError, IOError) as e: pass except (zipfile.BadZipFile) as e: logging.warning("Your jar {0} is corrupted, I'll be skipping it, but you " "should probably look into that.".format(jarpath)) if verbose: logging.info("Did not find file {0} in jar {1}".format(filename, jarpath)) raise TextureException("Could not find the textures while searching for '{0}'. Try specifying the 'texturepath' option in your config file.\nSet it to the path to a Minecraft Resource pack.\nAlternately, install the Minecraft client (which includes textures)\nAlso see <http://docs.overviewer.org/en/latest/running/#installing-the-textures>\n(Remember, this version of Overviewer requires a 1.19-compatible resource pack)\n(Also note that I won't automatically use snapshots; you'll have to use the texturepath option to use a snapshot jar)".format(filename)) def load_image_texture(self, filename): # Textures may be animated or in a different resolution than 16x16. # This method will always return a 16x16 image img = self.load_image(filename) w,h = img.size if w != h: img = img.crop((0,0,w,w)) if w != 16: img = img.resize((16, 16), Image.ANTIALIAS) self.texture_cache[filename] = img return img def load_image(self, filename): """Returns an image object""" try: img = self.texture_cache[filename] if isinstance(img, Exception): # Did we cache an exception? raise img # Okay then, raise it. return img except KeyError: pass try: fileobj = self.find_file(filename, verbose=logging.getLogger().isEnabledFor(logging.DEBUG)) except (TextureException, IOError) as e: # We cache when our good friend find_file can't find # a texture, so that we do not repeatedly search for it. self.texture_cache[filename] = e raise e buffer = BytesIO(fileobj.read()) try: img = Image.open(buffer).convert("RGBA") except IOError: raise TextureException("The texture {} appears to be corrupted. Please fix it. Run " "Overviewer in verbose mode (-v) to find out where I loaded " "that file from.".format(filename)) self.texture_cache[filename] = img return img def load_water(self): """Special-case function for loading water.""" watertexture = getattr(self, "watertexture", None) if watertexture: return watertexture watertexture = self.load_image_texture("assets/minecraft/textures/block/water_still.png") self.watertexture = watertexture return watertexture def load_lava(self): """Special-case function for loading lava.""" lavatexture = getattr(self, "lavatexture", None) if lavatexture: return lavatexture lavatexture = self.load_image_texture("assets/minecraft/textures/block/lava_still.png") self.lavatexture = lavatexture return lavatexture def load_portal(self): """Special-case function for loading portal.""" portaltexture = getattr(self, "portaltexture", None) if portaltexture: return portaltexture portaltexture = self.load_image_texture("assets/minecraft/textures/block/nether_portal.png") self.portaltexture = portaltexture return portaltexture def load_light_color(self): """Helper function to load the light color texture.""" if hasattr(self, "lightcolor"): return self.lightcolor try: lightcolor = list(self.load_image("light_normal.png").getdata()) except Exception: logging.warning("Light color image could not be found.") lightcolor = None self.lightcolor = lightcolor return lightcolor def load_grass_color(self): """Helper function to load the grass color texture.""" if not hasattr(self, "grasscolor"): self.grasscolor = list(self.load_image("assets/minecraft/textures/colormap/grass.png").getdata()) return self.grasscolor def load_foliage_color(self): """Helper function to load the foliage color texture.""" if not hasattr(self, "foliagecolor"): self.foliagecolor = list(self.load_image("assets/minecraft/textures/colormap/foliage.png").getdata()) return self.foliagecolor #I guess "watercolor" is wrong. But I can't correct as my texture pack don't define water color. def load_water_color(self): """Helper function to load the water color texture.""" if not hasattr(self, "watercolor"): self.watercolor = list(self.load_image("watercolor.png").getdata()) return self.watercolor def _split_terrain(self, terrain): """Builds and returns a length 256 array of each 16x16 chunk of texture. """ textures = [] (terrain_width, terrain_height) = terrain.size texture_resolution = terrain_width / 16 for y in range(16): for x in range(16): left = x*texture_resolution upper = y*texture_resolution right = left+texture_resolution lower = upper+texture_resolution region = terrain.transform( (16, 16), Image.EXTENT, (left,upper,right,lower), Image.BICUBIC) textures.append(region) return textures ## ## Image Transformation Functions ## @staticmethod def transform_image_top(img): """Takes a PIL image and rotates it left 45 degrees and shrinks the y axis by a factor of 2. Returns the resulting image, which will be 24x12 pixels """ # Resize to 17x17, since the diagonal is approximately 24 pixels, a nice # even number that can be split in half twice img = img.resize((17, 17), Image.ANTIALIAS) # Build the Affine transformation matrix for this perspective transform = numpy.matrix(numpy.identity(3)) # Translate up and left, since rotations are about the origin transform *= numpy.matrix([[1,0,8.5],[0,1,8.5],[0,0,1]]) # Rotate 45 degrees ratio = math.cos(math.pi/4) #transform *= numpy.matrix("[0.707,-0.707,0;0.707,0.707,0;0,0,1]") transform *= numpy.matrix([[ratio,-ratio,0],[ratio,ratio,0],[0,0,1]]) # Translate back down and right transform *= numpy.matrix([[1,0,-12],[0,1,-12],[0,0,1]]) # scale the image down by a factor of 2 transform *= numpy.matrix("[1,0,0;0,2,0;0,0,1]") transform = numpy.array(transform)[:2,:].ravel().tolist() newimg = img.transform((24,12), Image.AFFINE, transform) return newimg @staticmethod def transform_image_side(img): """Takes an image and shears it for the left side of the cube (reflect for the right side)""" # Size of the cube side before shear img = img.resize((12,12), Image.ANTIALIAS) # Apply shear transform = numpy.matrix(numpy.identity(3)) transform *= numpy.matrix("[1,0,0;-0.5,1,0;0,0,1]") transform = numpy.array(transform)[:2,:].ravel().tolist() newimg = img.transform((12,18), Image.AFFINE, transform) return newimg @staticmethod def transform_image_slope(img): """Takes an image and shears it in the shape of a slope going up in the -y direction (reflect for +x direction). Used for minetracks""" # Take the same size as trasform_image_side img = img.resize((12,12), Image.ANTIALIAS) # Apply shear transform = numpy.matrix(numpy.identity(3)) transform *= numpy.matrix("[0.75,-0.5,3;0.25,0.5,-3;0,0,1]") transform = numpy.array(transform)[:2,:].ravel().tolist() newimg = img.transform((24,24), Image.AFFINE, transform) return newimg @staticmethod def transform_image_angle(img, angle): """Takes an image an shears it in arbitrary angle with the axis of rotation being vertical. WARNING! Don't use angle = pi/2 (or multiplies), it will return a blank image (or maybe garbage). NOTE: angle is in the image not in game, so for the left side of a block angle = 30 degree. """ # Take the same size as trasform_image_side img = img.resize((12,12), Image.ANTIALIAS) # some values cos_angle = math.cos(angle) sin_angle = math.sin(angle) # function_x and function_y are used to keep the result image in the # same position, and constant_x and constant_y are the coordinates # for the center for angle = 0. constant_x = 6. constant_y = 6. function_x = 6.*(1-cos_angle) function_y = -6*sin_angle big_term = ( (sin_angle * (function_x + constant_x)) - cos_angle* (function_y + constant_y))/cos_angle # The numpy array is not really used, but is helpful to # see the matrix used for the transformation. transform = numpy.array([[1./cos_angle, 0, -(function_x + constant_x)/cos_angle], [-sin_angle/(cos_angle), 1., big_term ], [0, 0, 1.]]) transform = tuple(transform[0]) + tuple(transform[1]) newimg = img.transform((24,24), Image.AFFINE, transform) return newimg def build_block(self, top, side): """From a top texture and a side texture, build a block image. top and side should be 16x16 image objects. Returns a 24x24 image """ img = Image.new("RGBA", (24,24), self.bgcolor) original_texture = top.copy() top = self.transform_image_top(top) if not side: alpha_over(img, top, (0,0), top) return img side = self.transform_image_side(side) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) # Darken the sides slightly. These methods also affect the alpha layer, # so save them first (we don't want to "darken" the alpha layer making # the block transparent) sidealpha = side.split()[3] side = ImageEnhance.Brightness(side).enhance(0.9) side.putalpha(sidealpha) othersidealpha = otherside.split()[3] otherside = ImageEnhance.Brightness(otherside).enhance(0.8) otherside.putalpha(othersidealpha) alpha_over(img, top, (0,0), top) alpha_over(img, side, (0,6), side) alpha_over(img, otherside, (12,6), otherside) # Manually touch up 6 pixels that leave a gap because of how the # shearing works out. This makes the blocks perfectly tessellate-able for x,y in [(13,23), (17,21), (21,19)]: # Copy a pixel to x,y from x-1,y img.putpixel((x,y), img.getpixel((x-1,y))) for x,y in [(3,4), (7,2), (11,0)]: # Copy a pixel to x,y from x+1,y img.putpixel((x,y), img.getpixel((x+1,y))) return img def build_slab_block(self, top, side, upper): """From a top texture and a side texture, build a slab block image. top and side should be 16x16 image objects. Returns a 24x24 image """ # cut the side texture in half mask = side.crop((0,8,16,16)) side = Image.new(side.mode, side.size, self.bgcolor) alpha_over(side, mask,(0,0,16,8), mask) # plain slab top = self.transform_image_top(top) side = self.transform_image_side(side) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) sidealpha = side.split()[3] side = ImageEnhance.Brightness(side).enhance(0.9) side.putalpha(sidealpha) othersidealpha = otherside.split()[3] otherside = ImageEnhance.Brightness(otherside).enhance(0.8) otherside.putalpha(othersidealpha) # upside down slab delta = 0 if upper: delta = 6 img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, side, (0,12 - delta), side) alpha_over(img, otherside, (12,12 - delta), otherside) alpha_over(img, top, (0,6 - delta), top) # Manually touch up 6 pixels that leave a gap because of how the # shearing works out. This makes the blocks perfectly tessellate-able if upper: for x,y in [(3,4), (7,2), (11,0)]: # Copy a pixel to x,y from x+1,y img.putpixel((x,y), img.getpixel((x+1,y))) for x,y in [(13,17), (17,15), (21,13)]: # Copy a pixel to x,y from x-1,y img.putpixel((x,y), img.getpixel((x-1,y))) else: for x,y in [(3,10), (7,8), (11,6)]: # Copy a pixel to x,y from x+1,y img.putpixel((x,y), img.getpixel((x+1,y))) for x,y in [(13,23), (17,21), (21,19)]: # Copy a pixel to x,y from x-1,y img.putpixel((x,y), img.getpixel((x-1,y))) return img def build_full_block(self, top, side1, side2, side3, side4, bottom=None): """From a top texture, a bottom texture and 4 different side textures, build a full block with four differnts faces. All images should be 16x16 image objects. Returns a 24x24 image. Can be used to render any block. side1 is in the -y face of the cube (top left, east) side2 is in the +x (top right, south) side3 is in the -x (bottom left, north) side4 is in the +y (bottom right, west) A non transparent block uses top, side 3 and side 4. If top is a tuple then first item is the top image and the second item is an increment (integer) from 0 to 16 (pixels in the original minecraft texture). This increment will be used to crop the side images and to paste the top image increment pixels lower, so if you use an increment of 8, it will draw a half-block. NOTE: this method uses the bottom of the texture image (as done in minecraft with beds and cakes) """ increment = 0 if isinstance(top, tuple): increment = int(round((top[1] / 16.)*12.)) # range increment in the block height in pixels (half texture size) crop_height = increment top = top[0] if side1 is not None: side1 = side1.copy() ImageDraw.Draw(side1).rectangle((0, 0,16,crop_height),outline=(0,0,0,0),fill=(0,0,0,0)) if side2 is not None: side2 = side2.copy() ImageDraw.Draw(side2).rectangle((0, 0,16,crop_height),outline=(0,0,0,0),fill=(0,0,0,0)) if side3 is not None: side3 = side3.copy() ImageDraw.Draw(side3).rectangle((0, 0,16,crop_height),outline=(0,0,0,0),fill=(0,0,0,0)) if side4 is not None: side4 = side4.copy() ImageDraw.Draw(side4).rectangle((0, 0,16,crop_height),outline=(0,0,0,0),fill=(0,0,0,0)) img = Image.new("RGBA", (24,24), self.bgcolor) # first back sides if side1 is not None : side1 = self.transform_image_side(side1) side1 = side1.transpose(Image.FLIP_LEFT_RIGHT) # Darken this side. sidealpha = side1.split()[3] side1 = ImageEnhance.Brightness(side1).enhance(0.9) side1.putalpha(sidealpha) alpha_over(img, side1, (0,0), side1) if side2 is not None : side2 = self.transform_image_side(side2) # Darken this side. sidealpha2 = side2.split()[3] side2 = ImageEnhance.Brightness(side2).enhance(0.8) side2.putalpha(sidealpha2) alpha_over(img, side2, (12,0), side2) if bottom is not None : bottom = self.transform_image_top(bottom) alpha_over(img, bottom, (0,12), bottom) # front sides if side3 is not None : side3 = self.transform_image_side(side3) # Darken this side sidealpha = side3.split()[3] side3 = ImageEnhance.Brightness(side3).enhance(0.9) side3.putalpha(sidealpha) alpha_over(img, side3, (0,6), side3) if side4 is not None : side4 = self.transform_image_side(side4) side4 = side4.transpose(Image.FLIP_LEFT_RIGHT) # Darken this side sidealpha = side4.split()[3] side4 = ImageEnhance.Brightness(side4).enhance(0.8) side4.putalpha(sidealpha) alpha_over(img, side4, (12,6), side4) if top is not None : top = self.transform_image_top(top) alpha_over(img, top, (0, increment), top) # Manually touch up 6 pixels that leave a gap because of how the # shearing works out. This makes the blocks perfectly tessellate-able for x,y in [(13,23), (17,21), (21,19)]: # Copy a pixel to x,y from x-1,y img.putpixel((x,y), img.getpixel((x-1,y))) for x,y in [(3,4), (7,2), (11,0)]: # Copy a pixel to x,y from x+1,y img.putpixel((x,y), img.getpixel((x+1,y))) return img def build_axis_block(self, top, side, data): """ Build an block with Axis property. data = {'y': 0, 'x': 1, 'z': 2}[axis] """ def draw_x(): return self.build_full_block(side.rotate(90), None, None, top, side.rotate(90)) def draw_y(): return self.build_full_block(side, None, None, side.rotate(270), top) draw_funcs = [draw_x, draw_y] if data == 0: # up return self.build_block(top, side) elif data == 1: # x return draw_funcs[(self.rotation + 0) % len(draw_funcs)]() elif data == 2: # y return draw_funcs[(self.rotation + 1) % len(draw_funcs)]() def build_sprite(self, side): """From a side texture, create a sprite-like texture such as those used for spiderwebs or flowers.""" img = Image.new("RGBA", (24,24), self.bgcolor) side = self.transform_image_side(side) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, side, (6,3), side) alpha_over(img, otherside, (6,3), otherside) return img def build_billboard(self, tex): """From a texture, create a billboard-like texture such as those used for tall grass or melon stems. """ img = Image.new("RGBA", (24,24), self.bgcolor) front = tex.resize((14, 12), Image.ANTIALIAS) alpha_over(img, front, (5,9)) return img def generate_opaque_mask(self, img): """ Takes the alpha channel of the image and generates a mask (used for lighting the block) that deprecates values of alpha smallers than 50, and sets every other value to 255. """ alpha = img.split()[3] return alpha.point(lambda a: int(min(a, 25.5) * 10)) def tint_texture(self, im, c): # apparently converting to grayscale drops the alpha channel? i = ImageOps.colorize(ImageOps.grayscale(im), (0,0,0), c) i.putalpha(im.split()[3]); # copy the alpha band back in. assuming RGBA return i def generate_texture_tuple(self, img): """ This takes an image and returns the needed tuple for the blockmap array.""" if img is None: return None return (img, self.generate_opaque_mask(img)) ## ## The other big one: @material and associated framework ## # the material registration decorator def material(blockid=[], data=[0], **kwargs): # mapping from property name to the set to store them in properties = {"transparent" : transparent_blocks, "solid" : solid_blocks, "fluid" : fluid_blocks, "nospawn" : nospawn_blocks, "nodata" : nodata_blocks} # make sure blockid and data are iterable try: iter(blockid) except Exception: blockid = [blockid,] try: iter(data) except Exception: data = [data,] def inner_material(func): global blockmap_generators global max_data, max_blockid # create a wrapper function with a known signature @functools.wraps(func) def func_wrapper(texobj, blockid, data): return func(texobj, blockid, data) used_datas.update(data) if max(data) >= max_data: max_data = max(data) + 1 for block in blockid: # set the property sets appropriately known_blocks.update([block]) if block >= max_blockid: max_blockid = block + 1 for prop in properties: try: if block in kwargs.get(prop, []): properties[prop].update([block]) except TypeError: if kwargs.get(prop, False): properties[prop].update([block]) # populate blockmap_generators with our function for d in data: blockmap_generators[(block, d)] = func_wrapper return func_wrapper return inner_material # shortcut function for pure blocks, default to solid, nodata def block(blockid=[], top_image=None, side_image=None, **kwargs): new_kwargs = {'solid' : True, 'nodata' : True} new_kwargs.update(kwargs) if top_image is None: raise ValueError("top_image was not provided") if side_image is None: side_image = top_image @material(blockid=blockid, **new_kwargs) def inner_block(self, unused_id, unused_data): return self.build_block(self.load_image_texture(top_image), self.load_image_texture(side_image)) return inner_block # shortcut function for sprite blocks, defaults to transparent, nodata def sprite(blockid=[], imagename=None, **kwargs): new_kwargs = {'transparent' : True, 'nodata' : True} new_kwargs.update(kwargs) if imagename is None: raise ValueError("imagename was not provided") @material(blockid=blockid, **new_kwargs) def inner_sprite(self, unused_id, unused_data): return self.build_sprite(self.load_image_texture(imagename)) return inner_sprite # shortcut function for billboard blocks, defaults to transparent, nodata def billboard(blockid=[], imagename=None, **kwargs): new_kwargs = {'transparent' : True, 'nodata' : True} new_kwargs.update(kwargs) if imagename is None: raise ValueError("imagename was not provided") @material(blockid=blockid, **new_kwargs) def inner_billboard(self, unused_id, unused_data): return self.build_billboard(self.load_image_texture(imagename)) return inner_billboard ## ## and finally: actual texture definitions ## # stone @material(blockid=1, data=list(range(7)), solid=True) def stone(self, blockid, data): if data == 0: # regular old-school stone img = self.load_image_texture("assets/minecraft/textures/block/stone.png") elif data == 1: # granite img = self.load_image_texture("assets/minecraft/textures/block/granite.png") elif data == 2: # polished granite img = self.load_image_texture("assets/minecraft/textures/block/polished_granite.png") elif data == 3: # diorite img = self.load_image_texture("assets/minecraft/textures/block/diorite.png") elif data == 4: # polished diorite img = self.load_image_texture("assets/minecraft/textures/block/polished_diorite.png") elif data == 5: # andesite img = self.load_image_texture("assets/minecraft/textures/block/andesite.png") elif data == 6: # polished andesite img = self.load_image_texture("assets/minecraft/textures/block/polished_andesite.png") return self.build_block(img, img) @material(blockid=2, data=list(range(11))+[0x10,], solid=True) def grass(self, blockid, data): # 0x10 bit means SNOW side_img = self.load_image_texture("assets/minecraft/textures/block/grass_block_side.png") if data & 0x10: side_img = self.load_image_texture("assets/minecraft/textures/block/grass_block_snow.png") img = self.build_block(self.load_image_texture("assets/minecraft/textures/block/grass_block_top.png"), side_img) if not data & 0x10: alpha_over(img, self.biome_grass_texture, (0, 0), self.biome_grass_texture) return img # dirt @material(blockid=3, data=list(range(3)), solid=True) def dirt_blocks(self, blockid, data): texture_map = [{"top": "dirt", "side": "dirt"}, # Normal {"top": "coarse_dirt", "side": "coarse_dirt"}, # Coarse {"top": "podzol_top", "side": "podzol_side"}] # Podzol top_img = self.load_image_texture("assets/minecraft/textures/block/%s.png" % texture_map[data]["top"]) side_img = self.load_image_texture("assets/minecraft/textures/block/%s.png" % texture_map[data]["side"]) return self.build_block(top_img, side_img) # cobblestone block(blockid=4, top_image="assets/minecraft/textures/block/cobblestone.png") # wooden planks @material(blockid=5, data=list(range(8)), solid=True) def wooden_planks(self, blockid, data): if data == 0: # normal return self.build_block(self.load_image_texture("assets/minecraft/textures/block/oak_planks.png"), self.load_image_texture("assets/minecraft/textures/block/oak_planks.png")) if data == 1: # pine return self.build_block(self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png"),self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png")) if data == 2: # birch return self.build_block(self.load_image_texture("assets/minecraft/textures/block/birch_planks.png"),self.load_image_texture("assets/minecraft/textures/block/birch_planks.png")) if data == 3: # jungle wood return self.build_block(self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png"),self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png")) if data == 4: # acacia return self.build_block(self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png"),self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png")) if data == 5: # dark oak return self.build_block(self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png"),self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png")) if data == 6: # crimson return self.build_block(self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png"),self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png")) if data == 7: # warped return self.build_block(self.load_image_texture("assets/minecraft/textures/block/warped_planks.png"),self.load_image_texture("assets/minecraft/textures/block/warped_planks.png")) @material(blockid=6, data=list(range(16)), transparent=True) def saplings(self, blockid, data): # usual saplings tex = self.load_image_texture("assets/minecraft/textures/block/oak_sapling.png") if data & 0x3 == 1: # spruce sapling tex = self.load_image_texture("assets/minecraft/textures/block/spruce_sapling.png") elif data & 0x3 == 2: # birch sapling tex = self.load_image_texture("assets/minecraft/textures/block/birch_sapling.png") elif data & 0x3 == 3: # jungle sapling tex = self.load_image_texture("assets/minecraft/textures/block/jungle_sapling.png") elif data & 0x3 == 4: # acacia sapling tex = self.load_image_texture("assets/minecraft/textures/block/acacia_sapling.png") elif data & 0x3 == 5: # dark oak/roofed oak/big oak sapling tex = self.load_image_texture("assets/minecraft/textures/block/dark_oak_sapling.png") return self.build_sprite(tex) sprite(blockid=11385, imagename="assets/minecraft/textures/block/oak_sapling.png") sprite(blockid=11386, imagename="assets/minecraft/textures/block/spruce_sapling.png") sprite(blockid=11387, imagename="assets/minecraft/textures/block/birch_sapling.png") sprite(blockid=11388, imagename="assets/minecraft/textures/block/jungle_sapling.png") sprite(blockid=11389, imagename="assets/minecraft/textures/block/acacia_sapling.png") sprite(blockid=11390, imagename="assets/minecraft/textures/block/dark_oak_sapling.png") sprite(blockid=11413, imagename="assets/minecraft/textures/block/bamboo_stage0.png") # bedrock block(blockid=7, top_image="assets/minecraft/textures/block/bedrock.png") # water, glass, and ice (no inner surfaces) # uses pseudo-ancildata found in iterate.c @material(blockid=[8, 9, 20, 79, 95], data=list(range(512)), fluid=(8, 9), transparent=True, nospawn=True, solid=(79, 20, 95)) def no_inner_surfaces(self, blockid, data): if blockid == 8 or blockid == 9: texture = self.load_water() elif blockid == 20: texture = self.load_image_texture("assets/minecraft/textures/block/glass.png") elif blockid == 95: texture = self.load_image_texture("assets/minecraft/textures/block/%s_stained_glass.png" % color_map[data & 0x0f]) else: texture = self.load_image_texture("assets/minecraft/textures/block/ice.png") # now that we've used the lower 4 bits to get color, shift down to get the 5 bits that encode face hiding if not (blockid == 8 or blockid == 9): # water doesn't have a shifted pseudodata data = data >> 4 if (data & 0b10000) == 16: top = texture else: top = None if (data & 0b0001) == 1: side1 = texture # top left else: side1 = None if (data & 0b1000) == 8: side2 = texture # top right else: side2 = None if (data & 0b0010) == 2: side3 = texture # bottom left else: side3 = None if (data & 0b0100) == 4: side4 = texture # bottom right else: side4 = None # if nothing shown do not draw at all if top is None and side3 is None and side4 is None: return None img = self.build_full_block(top,None,None,side3,side4) return img @material(blockid=[10, 11], data=list(range(16)), fluid=True, transparent=False, nospawn=True) def lava(self, blockid, data): lavatex = self.load_lava() return self.build_block(lavatex, lavatex) # sand @material(blockid=12, data=list(range(2)), solid=True) def sand_blocks(self, blockid, data): if data == 0: # normal img = self.build_block(self.load_image_texture("assets/minecraft/textures/block/sand.png"), self.load_image_texture("assets/minecraft/textures/block/sand.png")) if data == 1: # red img = self.build_block(self.load_image_texture("assets/minecraft/textures/block/red_sand.png"), self.load_image_texture("assets/minecraft/textures/block/red_sand.png")) return img # gravel block(blockid=13, top_image="assets/minecraft/textures/block/gravel.png") # gold ore block(blockid=14, top_image="assets/minecraft/textures/block/gold_ore.png") # iron ore block(blockid=15, top_image="assets/minecraft/textures/block/iron_ore.png") # coal ore block(blockid=16, top_image="assets/minecraft/textures/block/coal_ore.png") @material(blockid=[17, 162, 11306, 11307, 11308, 11309, 11310, 11311, 1008, 1009, 1126], data=list(range(12)), solid=True) def wood(self, blockid, data): # extract orientation and wood type frorm data bits wood_type = data & 3 wood_orientation = data & 12 if self.rotation == 1: if wood_orientation == 4: wood_orientation = 8 elif wood_orientation == 8: wood_orientation = 4 elif self.rotation == 3: if wood_orientation == 4: wood_orientation = 8 elif wood_orientation == 8: wood_orientation = 4 # dictionary of blockid : { wood_type : (top, side) } wood_tex = { 17: { 0: ("oak_log_top.png", "oak_log.png"), 1: ("spruce_log_top.png", "spruce_log.png"), 2: ("birch_log_top.png", "birch_log.png"), 3: ("jungle_log_top.png", "jungle_log.png"), }, 162: { 0: ("acacia_log_top.png", "acacia_log.png"), 1: ("dark_oak_log_top.png", "dark_oak_log.png"), }, 11306: { 0: ("stripped_oak_log_top.png", "stripped_oak_log.png"), 1: ("stripped_spruce_log_top.png", "stripped_spruce_log.png"), 2: ("stripped_birch_log_top.png", "stripped_birch_log.png"), 3: ("stripped_jungle_log_top.png", "stripped_jungle_log.png"), }, 11307: { 0: ("stripped_acacia_log_top.png", "stripped_acacia_log.png"), 1: ("stripped_dark_oak_log_top.png", "stripped_dark_oak_log.png"), }, 11308: { 0: ("oak_log.png", None), 1: ("spruce_log.png", None), 2: ("birch_log.png", None), 3: ("jungle_log.png", None), }, 11309: { 0: ("acacia_log.png", None), 1: ("dark_oak_log.png", None), }, 11310: { 0: ("stripped_oak_log.png", None), 1: ("stripped_spruce_log.png", None), 2: ("stripped_birch_log.png", None), 3: ("stripped_jungle_log.png", None), }, 11311: { 0: ("stripped_acacia_log.png", None), 1: ("stripped_dark_oak_log.png", None), }, 1008: { 0: ("warped_stem_top.png", "warped_stem.png"), 1: ("warped_stem_top.png", "stripped_warped_stem.png"), 2: ("crimson_stem_top.png", "crimson_stem.png"), 3: ("crimson_stem_top.png", "stripped_crimson_stem.png"), }, 1009: { 0: ("warped_stem.png", None), 1: ("stripped_warped_stem.png", None), 2: ("crimson_stem.png", None), 3: ("stripped_crimson_stem.png", None), }, 1126: { 0: ("mangrove_log_top.png", "mangrove_log.png"), 1: ("stripped_mangrove_log_top.png", "stripped_mangrove_log.png"), }, } top_f, side_f = wood_tex[blockid].get(wood_type, wood_tex[blockid][0]) if not side_f: side_f = top_f top = self.load_image_texture(BLOCKTEX + top_f) side = self.load_image_texture(BLOCKTEX + side_f) # choose orientation and paste textures if wood_orientation == 0: return self.build_block(top, side) elif wood_orientation == 4: # east-west orientation return self.build_full_block(side.rotate(90), None, None, top, side.rotate(90)) elif wood_orientation == 8: # north-south orientation return self.build_full_block(side, None, None, side.rotate(270), top) @material(blockid=[18, 161], data=list(range(16)), transparent=True, solid=True) def leaves(self, blockid, data): # mask out the bits 4 and 8 # they are used for player placed and check-for-decay blocks data = data & 0x7 t = self.load_image_texture("assets/minecraft/textures/block/oak_leaves.png") if (blockid, data) == (18, 1): # pine! t = self.load_image_texture("assets/minecraft/textures/block/spruce_leaves.png") elif (blockid, data) == (18, 2): # birth tree t = self.load_image_texture("assets/minecraft/textures/block/birch_leaves.png") elif (blockid, data) == (18, 3): # jungle tree t = self.load_image_texture("assets/minecraft/textures/block/jungle_leaves.png") elif (blockid, data) == (161, 4): # acacia tree t = self.load_image_texture("assets/minecraft/textures/block/acacia_leaves.png") elif (blockid, data) == (161, 5): t = self.load_image_texture("assets/minecraft/textures/block/dark_oak_leaves.png") elif (blockid, data) == (18, 6): t = self.load_image_texture("assets/minecraft/textures/block/flowering_azalea_leaves.png") elif (blockid, data) == (18, 7): t = self.load_image_texture("assets/minecraft/textures/block/azalea_leaves.png") elif (blockid, data) == (18, 8): t = self.load_image_texture("assets/minecraft/textures/block/mangrove_leaves.png") return self.build_block(t, t) # sponge block(blockid=19, top_image="assets/minecraft/textures/block/sponge.png") # lapis lazuli ore block(blockid=21, top_image="assets/minecraft/textures/block/lapis_ore.png") # lapis lazuli block block(blockid=22, top_image="assets/minecraft/textures/block/lapis_block.png") # dispenser, dropper, furnace, blast furnace, and smoker @material(blockid=[23, 61, 158, 11362, 11364], data=list(range(14)), solid=True) def furnaces(self, blockid, data): # first, do the rotation if needed # Masked as bit 4 indicates whether the block is lit/triggered or not if self.rotation in [1, 2, 3] and data & 0b111 in [2, 3, 4, 5]: rotation_map = {1: {2: 5, 3: 4, 4: 2, 5: 3}, 2: {2: 3, 3: 2, 4: 5, 5: 4}, 3: {2: 4, 3: 5, 4: 3, 5: 2}} data = data & 0b1000 | rotation_map[self.rotation][data & 0b111] # Rotation angles for top texture using data & 0b111 as an index top_rotation_map = [0, 0, 180, 0, 270, 90, 0, 0] # Dispenser texture_map = {23: {'top': 'furnace_top', 'side': 'furnace_side', 'front': 'dispenser_front', 'top_vert': 'dispenser_front_vertical'}, # Furnace 61: {'top': 'furnace_top', 'side': 'furnace_side', 'front': 'furnace_front', 'front_on': 'furnace_front_on'}, # Dropper 158: {'top': 'furnace_top', 'side': 'furnace_side', 'front': 'dropper_front', 'top_vert': 'dropper_front_vertical'}, # Blast furance 11362: {'top': 'blast_furnace_top', 'side': 'blast_furnace_side', 'front': 'blast_furnace_front', 'front_on': 'blast_furnace_front_on'}, # Smoker 11364: {'top': 'smoker_top', 'side': 'smoker_side', 'front': 'smoker_front', 'front_on': 'smoker_front_on'}} if data & 0b111 in [0, 1] and 'top_vert' in texture_map[blockid]: # Block has a special top texture when it faces up/down # This also affects which texture is used for the sides/front top_name = 'top_vert' if data & 0b111 == 1 else 'top' side_name = 'top' front_name = 'top' else: top_name = 'top' side_name = 'side' # Use block's lit/on front texture if it is defined & bit 4 is set # Note: Some front_on texture images have multiple frames, # but load_image_texture() crops this appropriately # as long as the image width is 16px if data & 0b1000 == 8 and 'front_on' in texture_map[blockid]: front_name = 'front_on' else: front_name = 'front' top = self.load_image_texture("assets/minecraft/textures/block/%s.png" % texture_map[blockid][top_name]).copy() top = top.rotate(top_rotation_map[data & 0b111]) side = self.load_image_texture("assets/minecraft/textures/block/%s.png" % texture_map[blockid][side_name]) front = self.load_image_texture("assets/minecraft/textures/block/%s.png" % texture_map[blockid][front_name]) if data & 0b111 == 3: # pointing west return self.build_full_block(top, None, None, side, front) elif data & 0b111 == 4: # pointing north return self.build_full_block(top, None, None, front, side) else: # in any other direction the front can't be seen return self.build_full_block(top, None, None, side, side) # sandstone @material(blockid=24, data=list(range(3)), solid=True) def sandstone(self, blockid, data): top = self.load_image_texture("assets/minecraft/textures/block/sandstone_top.png") if data == 0: # normal return self.build_block(top, self.load_image_texture("assets/minecraft/textures/block/sandstone.png")) if data == 1: # hieroglyphic return self.build_block(top, self.load_image_texture("assets/minecraft/textures/block/chiseled_sandstone.png")) if data == 2: # soft return self.build_block(top, self.load_image_texture("assets/minecraft/textures/block/cut_sandstone.png")) # red sandstone @material(blockid=179, data=list(range(3)), solid=True) def sandstone(self, blockid, data): top = self.load_image_texture("assets/minecraft/textures/block/red_sandstone_top.png") if data == 0: # normal side = self.load_image_texture("assets/minecraft/textures/block/red_sandstone.png") return self.build_full_block(top, None, None, side, side, self.load_image_texture("assets/minecraft/textures/block/red_sandstone_bottom.png") ) if data == 1: # hieroglyphic return self.build_block(top, self.load_image_texture("assets/minecraft/textures/block/chiseled_red_sandstone.png")) if data == 2: # soft return self.build_block(top, self.load_image_texture("assets/minecraft/textures/block/cut_red_sandstone.png")) # note block block(blockid=25, top_image="assets/minecraft/textures/block/note_block.png") # Bed @material(blockid=26, data=list(range(256)), transparent=True, nospawn=True) def bed(self, blockid, data): # Bits 1-2 Rotation # Bit 3 Occupancy, no impact on appearance # Bit 4 Foot/Head of bed (0 = foot, 1 = head) # Bits 5-8 Color # first get rotation done # Masked to not clobber block head/foot & color info data = data & 0b11111100 | ((self.rotation + (data & 0b11)) % 4) bed_texture = self.load_image("assets/minecraft/textures/entity/bed/%s.png" % color_map[data >> 4]) increment = 8 left_face = None right_face = None top_face = None if data & 0x8 == 0x8: # head of the bed top = bed_texture.copy().crop((6, 6, 22, 22)) # Composing the side side = Image.new("RGBA", (16, 16), self.bgcolor) side_part1 = bed_texture.copy().crop((0, 6, 6, 22)).rotate(90, expand=True) # foot of the bed side_part2 = bed_texture.copy().crop((53, 3, 56, 6)) side_part2_f = side_part2.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(side, side_part1, (0, 7), side_part1) alpha_over(side, side_part2, (0, 13), side_part2) end = Image.new("RGBA", (16, 16), self.bgcolor) end_part = bed_texture.copy().crop((6, 0, 22, 6)).rotate(180) alpha_over(end, end_part, (0, 7), end_part) alpha_over(end, side_part2, (0, 13), side_part2) alpha_over(end, side_part2_f, (13, 13), side_part2_f) if data & 0x03 == 0x00: # South top_face = top.rotate(180) left_face = side.transpose(Image.FLIP_LEFT_RIGHT) right_face = end elif data & 0x03 == 0x01: # West top_face = top.rotate(90) left_face = end right_face = side.transpose(Image.FLIP_LEFT_RIGHT) elif data & 0x03 == 0x02: # North top_face = top left_face = side elif data & 0x03 == 0x03: # East top_face = top.rotate(270) right_face = side else: # foot of the bed top = bed_texture.copy().crop((6, 28, 22, 44)) side = Image.new("RGBA", (16, 16), self.bgcolor) side_part1 = bed_texture.copy().crop((0, 28, 6, 44)).rotate(90, expand=True) side_part2 = bed_texture.copy().crop((53, 3, 56, 6)) side_part2_f = side_part2.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(side, side_part1, (0, 7), side_part1) alpha_over(side, side_part2, (13, 13), side_part2) end = Image.new("RGBA", (16, 16), self.bgcolor) end_part = bed_texture.copy().crop((22, 22, 38, 28)).rotate(180) alpha_over(end, end_part, (0, 7), end_part) alpha_over(end, side_part2, (0, 13), side_part2) alpha_over(end, side_part2_f, (13, 13), side_part2_f) if data & 0x03 == 0x00: # South top_face = top.rotate(180) left_face = side.transpose(Image.FLIP_LEFT_RIGHT) elif data & 0x03 == 0x01: # West top_face = top.rotate(90) right_face = side.transpose(Image.FLIP_LEFT_RIGHT) elif data & 0x03 == 0x02: # North top_face = top left_face = side right_face = end elif data & 0x03 == 0x03: # East top_face = top.rotate(270) left_face = end right_face = side top_face = (top_face, increment) return self.build_full_block(top_face, None, None, left_face, right_face) # powered, detector, activator and normal rails @material(blockid=[27, 28, 66, 157], data=list(range(14)), transparent=True) def rails(self, blockid, data): # first, do rotation # Masked to not clobber powered rail on/off info # Ascending and flat straight if self.rotation == 1: if (data & 0b0111) == 0: data = data & 0b1000 | 1 elif (data & 0b0111) == 1: data = data & 0b1000 | 0 elif (data & 0b0111) == 2: data = data & 0b1000 | 5 elif (data & 0b0111) == 3: data = data & 0b1000 | 4 elif (data & 0b0111) == 4: data = data & 0b1000 | 2 elif (data & 0b0111) == 5: data = data & 0b1000 | 3 elif self.rotation == 2: if (data & 0b0111) == 2: data = data & 0b1000 | 3 elif (data & 0b0111) == 3: data = data & 0b1000 | 2 elif (data & 0b0111) == 4: data = data & 0b1000 | 5 elif (data & 0b0111) == 5: data = data & 0b1000 | 4 elif self.rotation == 3: if (data & 0b0111) == 0: data = data & 0b1000 | 1 elif (data & 0b0111) == 1: data = data & 0b1000 | 0 elif (data & 0b0111) == 2: data = data & 0b1000 | 4 elif (data & 0b0111) == 3: data = data & 0b1000 | 5 elif (data & 0b0111) == 4: data = data & 0b1000 | 3 elif (data & 0b0111) == 5: data = data & 0b1000 | 2 if blockid == 66: # normal minetrack only #Corners if self.rotation == 1: if data == 6: data = 7 elif data == 7: data = 8 elif data == 8: data = 6 elif data == 9: data = 9 elif self.rotation == 2: if data == 6: data = 8 elif data == 7: data = 9 elif data == 8: data = 6 elif data == 9: data = 7 elif self.rotation == 3: if data == 6: data = 9 elif data == 7: data = 6 elif data == 8: data = 8 elif data == 9: data = 7 img = Image.new("RGBA", (24,24), self.bgcolor) if blockid == 27: # powered rail if data & 0x8 == 0: # unpowered raw_straight = self.load_image_texture("assets/minecraft/textures/block/powered_rail.png") raw_corner = self.load_image_texture("assets/minecraft/textures/block/rail_corner.png") # they don't exist but make the code # much simplier elif data & 0x8 == 0x8: # powered raw_straight = self.load_image_texture("assets/minecraft/textures/block/powered_rail_on.png") raw_corner = self.load_image_texture("assets/minecraft/textures/block/rail_corner.png") # leave corners for code simplicity # filter the 'powered' bit data = data & 0x7 elif blockid == 28: # detector rail raw_straight = self.load_image_texture("assets/minecraft/textures/block/detector_rail.png") raw_corner = self.load_image_texture("assets/minecraft/textures/block/rail_corner.png") # leave corners for code simplicity elif blockid == 66: # normal rail raw_straight = self.load_image_texture("assets/minecraft/textures/block/rail.png") raw_corner = self.load_image_texture("assets/minecraft/textures/block/rail_corner.png") elif blockid == 157: # activator rail if data & 0x8 == 0: # unpowered raw_straight = self.load_image_texture("assets/minecraft/textures/block/activator_rail.png") raw_corner = self.load_image_texture("assets/minecraft/textures/block/rail_corner.png") # they don't exist but make the code # much simplier elif data & 0x8 == 0x8: # powered raw_straight = self.load_image_texture("assets/minecraft/textures/block/activator_rail_on.png") raw_corner = self.load_image_texture("assets/minecraft/textures/block/rail_corner.png") # leave corners for code simplicity # filter the 'powered' bit data = data & 0x7 ## use transform_image to scale and shear if data == 0: track = self.transform_image_top(raw_straight) alpha_over(img, track, (0,12), track) elif data == 6: track = self.transform_image_top(raw_corner) alpha_over(img, track, (0,12), track) elif data == 7: track = self.transform_image_top(raw_corner.rotate(270)) alpha_over(img, track, (0,12), track) elif data == 8: # flip track = self.transform_image_top(raw_corner.transpose(Image.FLIP_TOP_BOTTOM).rotate(90)) alpha_over(img, track, (0,12), track) elif data == 9: track = self.transform_image_top(raw_corner.transpose(Image.FLIP_TOP_BOTTOM)) alpha_over(img, track, (0,12), track) elif data == 1: track = self.transform_image_top(raw_straight.rotate(90)) alpha_over(img, track, (0,12), track) #slopes elif data == 2: # slope going up in +x direction track = self.transform_image_slope(raw_straight) track = track.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, track, (2,0), track) # the 2 pixels move is needed to fit with the adjacent tracks elif data == 3: # slope going up in -x direction # tracks are sprites, in this case we are seeing the "side" of # the sprite, so draw a line to make it beautiful. ImageDraw.Draw(img).line([(11,11),(23,17)],fill=(164,164,164)) # grey from track texture (exterior grey). # the track doesn't start from image corners, be carefull drawing the line! elif data == 4: # slope going up in -y direction track = self.transform_image_slope(raw_straight) alpha_over(img, track, (0,0), track) elif data == 5: # slope going up in +y direction # same as "data == 3" ImageDraw.Draw(img).line([(1,17),(12,11)],fill=(164,164,164)) return img # sticky and normal piston body @material(blockid=[29, 33], data=[0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13], transparent=True, solid=True, nospawn=True) def piston(self, blockid, data): # first, rotation # Masked to not clobber block head/foot info if self.rotation in [1, 2, 3] and (data & 0b111) in [2, 3, 4, 5]: rotation_map = {1: {2: 5, 3: 4, 4: 2, 5: 3}, 2: {2: 3, 3: 2, 4: 5, 5: 4}, 3: {2: 4, 3: 5, 4: 3, 5: 2}} data = (data & 0b1000) | rotation_map[self.rotation][data & 0b111] if blockid == 29: # sticky piston_t = self.load_image_texture("assets/minecraft/textures/block/piston_top_sticky.png").copy() else: # normal piston_t = self.load_image_texture("assets/minecraft/textures/block/piston_top.png").copy() # other textures side_t = self.load_image_texture("assets/minecraft/textures/block/piston_side.png").copy() back_t = self.load_image_texture("assets/minecraft/textures/block/piston_bottom.png").copy() interior_t = self.load_image_texture("assets/minecraft/textures/block/piston_inner.png").copy() if data & 0x08 == 0x08: # pushed out, non full blocks, tricky stuff # remove piston texture from piston body ImageDraw.Draw(side_t).rectangle((0, 0, 16, 3), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) if data & 0x07 == 0x0: # down side_t = side_t.rotate(180) img = self.build_full_block(back_t, None, None, side_t, side_t) elif data & 0x07 == 0x1: # up img = self.build_full_block((interior_t, 4), None, None, side_t, side_t) elif data & 0x07 == 0x2: # north img = self.build_full_block(side_t, None, None, side_t.rotate(90), back_t) elif data & 0x07 == 0x3: # south img = self.build_full_block(side_t.rotate(180), None, None, side_t.rotate(270), None) temp = self.transform_image_side(interior_t) temp = temp.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, temp, (9, 4), temp) elif data & 0x07 == 0x4: # west img = self.build_full_block(side_t.rotate(90), None, None, None, side_t.rotate(270)) temp = self.transform_image_side(interior_t) alpha_over(img, temp, (3, 4), temp) elif data & 0x07 == 0x5: # east img = self.build_full_block(side_t.rotate(270), None, None, back_t, side_t.rotate(90)) else: # pushed in, normal full blocks, easy stuff if data & 0x07 == 0x0: # down side_t = side_t.rotate(180) img = self.build_full_block(back_t, None, None, side_t, side_t) elif data & 0x07 == 0x1: # up img = self.build_full_block(piston_t, None, None, side_t, side_t) elif data & 0x07 == 0x2: # north img = self.build_full_block(side_t, None, None, side_t.rotate(90), back_t) elif data & 0x07 == 0x3: # south img = self.build_full_block(side_t.rotate(180), None, None, side_t.rotate(270), piston_t) elif data & 0x07 == 0x4: # west img = self.build_full_block(side_t.rotate(90), None, None, piston_t, side_t.rotate(270)) elif data & 0x07 == 0x5: # east img = self.build_full_block(side_t.rotate(270), None, None, back_t, side_t.rotate(90)) return img # sticky and normal piston shaft @material(blockid=34, data=[0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13], transparent=True, nospawn=True) def piston_extension(self, blockid, data): # first, rotation # Masked to not clobber block head/foot info if self.rotation in [1, 2, 3] and (data & 0b111) in [2, 3, 4, 5]: rotation_map = {1: {2: 5, 3: 4, 4: 2, 5: 3}, 2: {2: 3, 3: 2, 4: 5, 5: 4}, 3: {2: 4, 3: 5, 4: 3, 5: 2}} data = (data & 0b1000) | rotation_map[self.rotation][data & 0b111] if data & 0x8 == 0x8: # sticky piston_t = self.load_image_texture("assets/minecraft/textures/block/piston_top_sticky.png").copy() else: # normal piston_t = self.load_image_texture("assets/minecraft/textures/block/piston_top.png").copy() # other textures side_t = self.load_image_texture("assets/minecraft/textures/block/piston_side.png").copy() back_t = self.load_image_texture("assets/minecraft/textures/block/piston_top.png").copy() # crop piston body ImageDraw.Draw(side_t).rectangle((0, 4, 16, 16), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) # generate the horizontal piston extension stick h_stick = Image.new("RGBA", (24, 24), self.bgcolor) temp = self.transform_image_side(side_t) alpha_over(h_stick, temp, (1, 7), temp) temp = self.transform_image_top(side_t.rotate(90)) alpha_over(h_stick, temp, (1, 1), temp) # Darken it sidealpha = h_stick.split()[3] h_stick = ImageEnhance.Brightness(h_stick).enhance(0.85) h_stick.putalpha(sidealpha) # generate the vertical piston extension stick v_stick = Image.new("RGBA", (24, 24), self.bgcolor) temp = self.transform_image_side(side_t.rotate(90)) alpha_over(v_stick, temp, (12, 6), temp) temp = temp.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(v_stick, temp, (1, 6), temp) # Darken it sidealpha = v_stick.split()[3] v_stick = ImageEnhance.Brightness(v_stick).enhance(0.85) v_stick.putalpha(sidealpha) # Piston orientation is stored in the 3 first bits if data & 0x07 == 0x0: # down side_t = side_t.rotate(180) img = self.build_full_block((back_t, 12), None, None, side_t, side_t) alpha_over(img, v_stick, (0, -3), v_stick) elif data & 0x07 == 0x1: # up img = Image.new("RGBA", (24, 24), self.bgcolor) img2 = self.build_full_block(piston_t, None, None, side_t, side_t) alpha_over(img, v_stick, (0, 4), v_stick) alpha_over(img, img2, (0, 0), img2) elif data & 0x07 == 0x2: # north img = self.build_full_block(side_t, None, None, side_t.rotate(90), None) temp = self.transform_image_side(back_t).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, temp, (2, 2), temp) alpha_over(img, h_stick, (6, 3), h_stick) elif data & 0x07 == 0x3: # south img = Image.new("RGBA", (24, 24), self.bgcolor) img2 = self.build_full_block(side_t.rotate(180), None, None, side_t.rotate(270), piston_t) alpha_over(img, h_stick, (0, 0), h_stick) alpha_over(img, img2, (0, 0), img2) elif data & 0x07 == 0x4: # west img = self.build_full_block(side_t.rotate(90), None, None, piston_t, side_t.rotate(270)) h_stick = h_stick.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, h_stick, (0, 0), h_stick) elif data & 0x07 == 0x5: # east img = Image.new("RGBA", (24, 24), self.bgcolor) img2 = self.build_full_block(side_t.rotate(270), None, None, None, side_t.rotate(90)) h_stick = h_stick.transpose(Image.FLIP_LEFT_RIGHT) temp = self.transform_image_side(back_t) alpha_over(img2, temp, (10, 2), temp) alpha_over(img, img2, (0, 0), img2) alpha_over(img, h_stick, (-3, 2), h_stick) return img # cobweb sprite(blockid=30, imagename="assets/minecraft/textures/block/cobweb.png", nospawn=True) @material(blockid=31, data=list(range(3)), transparent=True) def tall_grass(self, blockid, data): if data == 0: # dead shrub texture = self.load_image_texture("assets/minecraft/textures/block/dead_bush.png") elif data == 1: # tall grass texture = self.load_image_texture("assets/minecraft/textures/block/grass.png") elif data == 2: # fern texture = self.load_image_texture("assets/minecraft/textures/block/fern.png") return self.build_billboard(texture) # dead bush billboard(blockid=32, imagename="assets/minecraft/textures/block/dead_bush.png") @material(blockid=35, data=list(range(16)), solid=True) def wool(self, blockid, data): texture = self.load_image_texture("assets/minecraft/textures/block/%s_wool.png" % color_map[data]) return self.build_block(texture, texture) # dandelion sprite(blockid=37, imagename="assets/minecraft/textures/block/dandelion.png") # flowers @material(blockid=38, data=list(range(13)), transparent=True) def flower(self, blockid, data): flower_map = ["poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy", "dandelion", "wither_rose", "cornflower", "lily_of_the_valley"] texture = self.load_image_texture("assets/minecraft/textures/block/%s.png" % flower_map[data]) return self.build_billboard(texture) # brown mushroom sprite(blockid=39, imagename="assets/minecraft/textures/block/brown_mushroom.png") # red mushroom sprite(blockid=40, imagename="assets/minecraft/textures/block/red_mushroom.png") # warped fungus sprite(blockid=1016, imagename="assets/minecraft/textures/block/warped_fungus.png") # crimson fungus sprite(blockid=1017, imagename="assets/minecraft/textures/block/crimson_fungus.png") # warped roots sprite(blockid=1018, imagename="assets/minecraft/textures/block/warped_roots.png") # crimson roots sprite(blockid=1019, imagename="assets/minecraft/textures/block/crimson_roots.png") # block of gold block(blockid=41, top_image="assets/minecraft/textures/block/gold_block.png") # block of iron block(blockid=42, top_image="assets/minecraft/textures/block/iron_block.png") # double slabs and slabs # these wooden slabs are unobtainable without cheating, they are still # here because lots of pre-1.3 worlds use this blocks, add prismarine slabs @material(blockid=[43, 44, 181, 182, 204, 205, 1124] + list(range(11340, 11359)) + list(range(1027, 1030)) + list(range(1072, 1080)) + list(range(1103, 1107)), data=list(range(16)), transparent=[44, 182, 205, 1124] + list(range(11340, 11359)) + list(range(1027, 1030)) + list(range(1072, 1080)) + list(range(1103, 1107)), solid=True) def slabs(self, blockid, data): if blockid == 44 or blockid == 182: texture = data & 7 else: # data > 8 are special double slabs texture = data if blockid == 44 or blockid == 43: if texture== 0: # stone slab top = self.load_image_texture("assets/minecraft/textures/block/stone.png") side = self.load_image_texture("assets/minecraft/textures/block/stone.png") elif texture== 1: # sandstone slab top = self.load_image_texture("assets/minecraft/textures/block/sandstone_top.png") side = self.load_image_texture("assets/minecraft/textures/block/sandstone.png") elif texture== 2: # wooden slab top = side = self.load_image_texture("assets/minecraft/textures/block/oak_planks.png") elif texture== 3: # cobblestone slab top = side = self.load_image_texture("assets/minecraft/textures/block/cobblestone.png") elif texture== 4: # brick top = side = self.load_image_texture("assets/minecraft/textures/block/bricks.png") elif texture== 5: # stone brick top = side = self.load_image_texture("assets/minecraft/textures/block/stone_bricks.png") elif texture== 6: # nether brick slab top = side = self.load_image_texture("assets/minecraft/textures/block/nether_bricks.png") elif texture== 7: #quartz top = side = self.load_image_texture("assets/minecraft/textures/block/quartz_block_side.png") elif texture== 8: # special stone double slab with top texture only top = side = self.load_image_texture("assets/minecraft/textures/block/smooth_stone.png") elif texture== 9: # special sandstone double slab with top texture only top = side = self.load_image_texture("assets/minecraft/textures/block/sandstone_top.png") else: return None elif blockid == 182: # single red sandstone slab if texture == 0: top = self.load_image_texture("assets/minecraft/textures/block/red_sandstone_top.png") side = self.load_image_texture("assets/minecraft/textures/block/red_sandstone.png") else: return None elif blockid == 181: # double red sandstone slab if texture == 0: # red sandstone top = self.load_image_texture("assets/minecraft/textures/block/red_sandstone_top.png") side = self.load_image_texture("assets/minecraft/textures/block/red_sandstone.png") elif texture == 8: # 'full' red sandstone (smooth) top = side = self.load_image_texture("assets/minecraft/textures/block/red_sandstone_top.png"); else: return None elif blockid == 204 or blockid == 205: # purpur slab (single=205 double=204) top = side = self.load_image_texture("assets/minecraft/textures/block/purpur_block.png"); elif blockid == 11340: # prismarine slabs top = side = self.load_image_texture("assets/minecraft/textures/block/prismarine.png").copy() elif blockid == 11341: # dark prismarine slabs top = side = self.load_image_texture("assets/minecraft/textures/block/dark_prismarine.png").copy() elif blockid == 11342: # prismarine brick slabs top = side = self.load_image_texture("assets/minecraft/textures/block/prismarine_bricks.png").copy() elif blockid == 11343: # andesite slabs top = side = self.load_image_texture("assets/minecraft/textures/block/andesite.png").copy() elif blockid == 11344: # diorite slabs top = side = self.load_image_texture("assets/minecraft/textures/block/diorite.png").copy() elif blockid == 11345: # granite slabs top = side = self.load_image_texture("assets/minecraft/textures/block/granite.png").copy() elif blockid == 11346: # polished andesite slabs top = side = self.load_image_texture("assets/minecraft/textures/block/polished_andesite.png").copy() elif blockid == 11347: # polished diorite slabs top = side = self.load_image_texture("assets/minecraft/textures/block/polished_diorite.png").copy() elif blockid == 11348: # polished granite slabs top = side = self.load_image_texture("assets/minecraft/textures/block/polished_granite.png").copy() elif blockid == 11349: # red nether brick slab top = side = self.load_image_texture("assets/minecraft/textures/block/red_nether_bricks.png").copy() elif blockid == 11350: # smooth sandstone slab top = side = self.load_image_texture("assets/minecraft/textures/block/sandstone_top.png").copy() elif blockid == 11351: # cut sandstone slab top = side = self.load_image_texture("assets/minecraft/textures/block/cut_sandstone.png").copy() elif blockid == 11352: # smooth red sandstone slab top = side = self.load_image_texture("assets/minecraft/textures/block/red_sandstone_top.png").copy() elif blockid == 11353: # cut red sandstone slab top = side = self.load_image_texture("assets/minecraft/textures/block/cut_red_sandstone.png").copy() elif blockid == 11354: # end_stone_brick_slab top = side = self.load_image_texture("assets/minecraft/textures/block/end_stone_bricks.png").copy() elif blockid == 11355: # mossy_cobblestone_slab top = side = self.load_image_texture("assets/minecraft/textures/block/mossy_cobblestone.png").copy() elif blockid == 11356: # mossy_stone_brick_slab top = side = self.load_image_texture("assets/minecraft/textures/block/mossy_stone_bricks.png").copy() elif blockid == 11357: # smooth_quartz_slab top = side = self.load_image_texture("assets/minecraft/textures/block/quartz_block_bottom.png").copy() elif blockid == 11358: # smooth_stone_slab top = self.load_image_texture("assets/minecraft/textures/block/smooth_stone.png").copy() side = self.load_image_texture("assets/minecraft/textures/block/smooth_stone_slab_side.png").copy() elif blockid == 1027: # blackstone_slab top = side = self.load_image_texture("assets/minecraft/textures/block/blackstone.png").copy() elif blockid == 1028: # polished_blackstone_slab top = side = self.load_image_texture("assets/minecraft/textures/block/polished_blackstone.png").copy() elif blockid == 1029: # polished_blackstone_brick_slab top = side = self.load_image_texture("assets/minecraft/textures/block/polished_blackstone_bricks.png").copy() elif blockid in range(1072, 1080): copper_tex = { 1072: "assets/minecraft/textures/block/cut_copper.png", 1076: "assets/minecraft/textures/block/cut_copper.png", 1073: "assets/minecraft/textures/block/exposed_cut_copper.png", 1077: "assets/minecraft/textures/block/exposed_cut_copper.png", 1074: "assets/minecraft/textures/block/weathered_cut_copper.png", 1078: "assets/minecraft/textures/block/weathered_cut_copper.png", 1075: "assets/minecraft/textures/block/oxidized_cut_copper.png", 1079: "assets/minecraft/textures/block/oxidized_cut_copper.png", } top = side = self.load_image_texture(copper_tex[blockid]).copy() elif blockid in range(1103, 1107): deepslate_tex = { 1103: "assets/minecraft/textures/block/cobbled_deepslate.png", 1104: "assets/minecraft/textures/block/polished_deepslate.png", 1105: "assets/minecraft/textures/block/deepslate_bricks.png", 1106: "assets/minecraft/textures/block/deepslate_tiles.png", } top = side = self.load_image_texture(deepslate_tex[blockid]).copy() elif blockid == 1124: top = side = self.load_image_texture("assets/minecraft/textures/block/mud_bricks.png").copy() if blockid == 43 or blockid == 181 or blockid == 204: # double slab return self.build_block(top, side) return self.build_slab_block(top, side, data & 8 == 8); # brick block block(blockid=45, top_image="assets/minecraft/textures/block/bricks.png") # TNT block(blockid=46, top_image="assets/minecraft/textures/block/tnt_top.png", side_image="assets/minecraft/textures/block/tnt_side.png", nospawn=True) # bookshelf block(blockid=47, top_image="assets/minecraft/textures/block/oak_planks.png", side_image="assets/minecraft/textures/block/bookshelf.png") # moss stone block(blockid=48, top_image="assets/minecraft/textures/block/mossy_cobblestone.png") # obsidian block(blockid=49, top_image="assets/minecraft/textures/block/obsidian.png") # torch, redstone torch (off), redstone torch(on), soul_torch @material(blockid=[50, 75, 76, 1039], data=[1, 2, 3, 4, 5], transparent=True) def torches(self, blockid, data): # first, rotations if self.rotation == 1: if data == 1: data = 3 elif data == 2: data = 4 elif data == 3: data = 2 elif data == 4: data = 1 elif self.rotation == 2: if data == 1: data = 2 elif data == 2: data = 1 elif data == 3: data = 4 elif data == 4: data = 3 elif self.rotation == 3: if data == 1: data = 4 elif data == 2: data = 3 elif data == 3: data = 1 elif data == 4: data = 2 # choose the proper texture if blockid == 50: # torch small = self.load_image_texture("assets/minecraft/textures/block/torch.png") elif blockid == 75: # off redstone torch small = self.load_image_texture("assets/minecraft/textures/block/redstone_torch_off.png") elif blockid == 76: # on redstone torch small = self.load_image_texture("assets/minecraft/textures/block/redstone_torch.png") elif blockid == 1039: # soul torch small= self.load_image_texture("assets/minecraft/textures/block/soul_torch.png") # compose a torch bigger than the normal # (better for doing transformations) torch = Image.new("RGBA", (16,16), self.bgcolor) alpha_over(torch,small,(-4,-3)) alpha_over(torch,small,(-5,-2)) alpha_over(torch,small,(-3,-2)) # angle of inclination of the texture rotation = 15 if data == 1: # pointing south torch = torch.rotate(-rotation, Image.NEAREST) # nearest filter is more nitid. img = self.build_full_block(None, None, None, torch, None, None) elif data == 2: # pointing north torch = torch.rotate(rotation, Image.NEAREST) img = self.build_full_block(None, None, torch, None, None, None) elif data == 3: # pointing west torch = torch.rotate(rotation, Image.NEAREST) img = self.build_full_block(None, torch, None, None, None, None) elif data == 4: # pointing east torch = torch.rotate(-rotation, Image.NEAREST) img = self.build_full_block(None, None, None, None, torch, None) elif data == 5: # standing on the floor # compose a "3d torch". img = Image.new("RGBA", (24,24), self.bgcolor) small_crop = small.crop((2,2,14,14)) slice = small_crop.copy() ImageDraw.Draw(slice).rectangle((6,0,12,12),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(slice).rectangle((0,0,4,12),outline=(0,0,0,0),fill=(0,0,0,0)) alpha_over(img, slice, (7,5)) alpha_over(img, small_crop, (6,6)) alpha_over(img, small_crop, (7,6)) alpha_over(img, slice, (7,7)) return img # lantern @material(blockid=[11373, 1038], data=[0, 1], transparent=True) def lantern(self, blockid, data): # get the multipart texture of the lantern if blockid == 11373: inputtexture = self.load_image_texture("assets/minecraft/textures/block/lantern.png") if blockid == 1038: inputtexture = self.load_image_texture("assets/minecraft/textures/block/soul_lantern.png") # # now create a textures, using the parts defined in lantern.json # JSON data for sides # from": [ 5, 1, 5 ], # "to": [11, 8, 11 ], # { "uv": [ 0, 2, 6, 9 ], "texture": "#all" } side_crop = inputtexture.crop((0, 2, 6, 9)) side_slice = side_crop.copy() side_texture = Image.new("RGBA", (16, 16), self.bgcolor) side_texture.paste(side_slice,(5, 8)) # JSON data for top # { "uv": [ 0, 9, 6, 15 ], "texture": "#all" } top_crop = inputtexture.crop((0, 9, 6, 15)) top_slice = top_crop.copy() top_texture = Image.new("RGBA", (16, 16), self.bgcolor) top_texture.paste(top_slice,(5, 5)) # mimic parts of build_full_block, to get an object smaller than a block # build_full_block(self, top, side1, side2, side3, side4, bottom=None): # a non transparent block uses top, side 3 and side 4. img = Image.new("RGBA", (24, 24), self.bgcolor) # prepare the side textures # side3 side3 = self.transform_image_side(side_texture) # Darken this side sidealpha = side3.split()[3] side3 = ImageEnhance.Brightness(side3).enhance(0.9) side3.putalpha(sidealpha) # place the transformed texture hangoff = 0 if data == 1: hangoff = 8 xoff = 4 yoff =- hangoff alpha_over(img, side3, (xoff+0, yoff+6), side3) # side4 side4 = self.transform_image_side(side_texture) side4 = side4.transpose(Image.FLIP_LEFT_RIGHT) # Darken this side sidealpha = side4.split()[3] side4 = ImageEnhance.Brightness(side4).enhance(0.8) side4.putalpha(sidealpha) alpha_over(img, side4, (12-xoff, yoff+6), side4) # top top = self.transform_image_top(top_texture) alpha_over(img, top, (0, 8-hangoff), top) return img # bamboo @material(blockid=11416, transparent=True) def bamboo(self, blockid, data): # get the multipart texture of the lantern inputtexture = self.load_image_texture("assets/minecraft/textures/block/bamboo_stalk.png") # # now create a textures, using the parts defined in bamboo1_age0.json # { "from": [ 7, 0, 7 ], # "to": [ 9, 16, 9 ], # "faces": { # "down": { "uv": [ 13, 4, 15, 6 ], "texture": "#all", "cullface": "down" }, # "up": { "uv": [ 13, 0, 15, 2], "texture": "#all", "cullface": "up" }, # "north": { "uv": [ 0, 0, 2, 16 ], "texture": "#all" }, # "south": { "uv": [ 0, 0, 2, 16 ], "texture": "#all" }, # "west": { "uv": [ 0, 0, 2, 16 ], "texture": "#all" }, # "east": { "uv": [ 0, 0, 2, 16 ], "texture": "#all" } # } # } side_crop = inputtexture.crop((0, 0, 3, 16)) side_slice = side_crop.copy() side_texture = Image.new("RGBA", (16, 16), self.bgcolor) side_texture.paste(side_slice,(0, 0)) # JSON data for top # "up": { "uv": [ 13, 0, 15, 2], "texture": "#all", "cullface": "up" }, top_crop = inputtexture.crop((13, 0, 16, 3)) top_slice = top_crop.copy() top_texture = Image.new("RGBA", (16, 16), self.bgcolor) top_texture.paste(top_slice,(5, 5)) # mimic parts of build_full_block, to get an object smaller than a block # build_full_block(self, top, side1, side2, side3, side4, bottom=None): # a non transparent block uses top, side 3 and side 4. img = Image.new("RGBA", (24, 24), self.bgcolor) # prepare the side textures # side3 side3 = self.transform_image_side(side_texture) # Darken this side sidealpha = side3.split()[3] side3 = ImageEnhance.Brightness(side3).enhance(0.9) side3.putalpha(sidealpha) # place the transformed texture xoff = 3 yoff = 0 alpha_over(img, side3, (4+xoff, yoff), side3) # side4 side4 = self.transform_image_side(side_texture) side4 = side4.transpose(Image.FLIP_LEFT_RIGHT) # Darken this side sidealpha = side4.split()[3] side4 = ImageEnhance.Brightness(side4).enhance(0.8) side4.putalpha(sidealpha) alpha_over(img, side4, (-4+xoff, yoff), side4) # top top = self.transform_image_top(top_texture) alpha_over(img, top, (-4+xoff, -5), top) return img # composter @material(blockid=11417, data=list(range(9)), transparent=True) def composter(self, blockid, data): side = self.load_image_texture("assets/minecraft/textures/block/composter_side.png") top = self.load_image_texture("assets/minecraft/textures/block/composter_top.png") # bottom = self.load_image_texture("assets/minecraft/textures/block/composter_bottom.png") if data == 0: # empty return self.build_full_block(top, side, side, side, side) if data == 8: compost = self.transform_image_top( self.load_image_texture("assets/minecraft/textures/block/composter_ready.png")) else: compost = self.transform_image_top( self.load_image_texture("assets/minecraft/textures/block/composter_compost.png")) nudge = {1: (0, 9), 2: (0, 8), 3: (0, 7), 4: (0, 6), 5: (0, 4), 6: (0, 2), 7: (0, 0), 8: (0, 0)} img = self.build_full_block(None, side, side, None, None) alpha_over(img, compost, nudge[data], compost) img2 = self.build_full_block(top, None, None, side, side) alpha_over(img, img2, (0, 0), img2) return img # fire and soul_fire @material(blockid=[51, 1040], transparent=True) def fire(self, blockid, data): if blockid == 51: textureNS = self.load_image_texture("assets/minecraft/textures/block/fire_0.png") textureEW = self.load_image_texture("assets/minecraft/textures/block/fire_1.png") elif blockid == 1040: textureNS = self.load_image_texture("assets/minecraft/textures/block/soul_fire_0.png") textureEW = self.load_image_texture("assets/minecraft/textures/block/soul_fire_1.png") side1 = self.transform_image_side(textureNS) side2 = self.transform_image_side(textureEW).transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, side1, (12,0), side1) alpha_over(img, side2, (0,0), side2) alpha_over(img, side1, (0,6), side1) alpha_over(img, side2, (12,6), side2) return img # monster spawner block(blockid=52, top_image="assets/minecraft/textures/block/spawner.png", transparent=True) # wooden, cobblestone, red brick, stone brick, netherbrick, sandstone, spruce, birch, # jungle, quartz, red sandstone, purper_stairs, crimson_stairs, warped_stairs, (dark) prismarine, # mossy brick and mossy cobblestone, stone smooth_quartz # polished_granite polished_andesite polished_diorite granite diorite andesite end_stone_bricks red_nether_brick stairs # smooth_red_sandstone blackstone polished_blackstone polished_blackstone_brick # also all the copper variants # also all deepslate variants @material(blockid=[53, 67, 108, 109, 114, 128, 134, 135, 136, 156, 163, 164, 180, 203, 509, 510, 11337, 11338, 11339, 11370, 11371, 11374, 11375, 11376, 11377, 11378, 11379, 11380, 11381, 11382, 11383, 11384, 11415, 1030, 1031, 1032, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1099, 1100, 1101, 1102], data=list(range(128)), transparent=True, solid=True, nospawn=True) def stairs(self, blockid, data): # preserve the upside-down bit upside_down = data & 0x4 # find solid quarters within the top or bottom half of the block # NW NE SE SW quarters = [data & 0x8, data & 0x10, data & 0x20, data & 0x40] # rotate the quarters so we can pretend northdirection is always upper-left numpy.roll(quarters, [0,1,3,2][self.rotation]) nw,ne,se,sw = quarters stair_id_to_tex = { 53: "assets/minecraft/textures/block/oak_planks.png", 67: "assets/minecraft/textures/block/cobblestone.png", 108: "assets/minecraft/textures/block/bricks.png", 109: "assets/minecraft/textures/block/stone_bricks.png", 114: "assets/minecraft/textures/block/nether_bricks.png", 128: "assets/minecraft/textures/block/sandstone.png", 134: "assets/minecraft/textures/block/spruce_planks.png", 135: "assets/minecraft/textures/block/birch_planks.png", 136: "assets/minecraft/textures/block/jungle_planks.png", 156: "assets/minecraft/textures/block/quartz_block_side.png", 163: "assets/minecraft/textures/block/acacia_planks.png", 164: "assets/minecraft/textures/block/dark_oak_planks.png", 180: "assets/minecraft/textures/block/red_sandstone.png", 203: "assets/minecraft/textures/block/purpur_block.png", 509: "assets/minecraft/textures/block/crimson_planks.png", 510: "assets/minecraft/textures/block/warped_planks.png", 11337: "assets/minecraft/textures/block/prismarine.png", 11338: "assets/minecraft/textures/block/dark_prismarine.png", 11339: "assets/minecraft/textures/block/prismarine_bricks.png", 11370: "assets/minecraft/textures/block/mossy_stone_bricks.png", 11371: "assets/minecraft/textures/block/mossy_cobblestone.png", 11374: "assets/minecraft/textures/block/sandstone_top.png", 11375: "assets/minecraft/textures/block/quartz_block_side.png", 11376: "assets/minecraft/textures/block/polished_granite.png", 11377: "assets/minecraft/textures/block/polished_diorite.png", 11378: "assets/minecraft/textures/block/polished_andesite.png", 11379: "assets/minecraft/textures/block/stone.png", 11380: "assets/minecraft/textures/block/granite.png", 11381: "assets/minecraft/textures/block/diorite.png", 11382: "assets/minecraft/textures/block/andesite.png", 11383: "assets/minecraft/textures/block/end_stone_bricks.png", 11384: "assets/minecraft/textures/block/red_nether_bricks.png", 11415: "assets/minecraft/textures/block/red_sandstone_top.png", 1030: "assets/minecraft/textures/block/blackstone.png", 1031: "assets/minecraft/textures/block/polished_blackstone.png", 1032: "assets/minecraft/textures/block/polished_blackstone_bricks.png", # Cut copper stairs 1064: "assets/minecraft/textures/block/cut_copper.png", 1065: "assets/minecraft/textures/block/exposed_cut_copper.png", 1066: "assets/minecraft/textures/block/weathered_cut_copper.png", 1067: "assets/minecraft/textures/block/oxidized_cut_copper.png", # Waxed cut copper stairs 1068: "assets/minecraft/textures/block/cut_copper.png", 1069: "assets/minecraft/textures/block/exposed_cut_copper.png", 1070: "assets/minecraft/textures/block/weathered_cut_copper.png", 1071: "assets/minecraft/textures/block/oxidized_cut_copper.png", # Deepslate 1099: "assets/minecraft/textures/block/cobbled_deepslate.png", 1100: "assets/minecraft/textures/block/polished_deepslate.png", 1101: "assets/minecraft/textures/block/deepslate_bricks.png", 1102: "assets/minecraft/textures/block/deepslate_tiles.png", } texture = self.load_image_texture(stair_id_to_tex[blockid]).copy() outside_l = texture.copy() outside_r = texture.copy() inside_l = texture.copy() inside_r = texture.copy() # sandstone, red sandstone, and quartz stairs have special top texture special_tops = { 128: "assets/minecraft/textures/block/sandstone_top.png", 156: "assets/minecraft/textures/block/quartz_block_top.png", 180: "assets/minecraft/textures/block/red_sandstone_top.png", 11375: "assets/minecraft/textures/block/quartz_block_top.png", } if blockid in special_tops: texture = self.load_image_texture(special_tops[blockid]).copy() slab_top = texture.copy() push = 8 if upside_down else 0 def rect(tex,coords): ImageDraw.Draw(tex).rectangle(coords,outline=(0,0,0,0),fill=(0,0,0,0)) # cut out top or bottom half from inner surfaces rect(inside_l, (0,8-push,15,15-push)) rect(inside_r, (0,8-push,15,15-push)) # cut out missing or obstructed quarters from each surface if not nw: rect(outside_l, (0,push,7,7+push)) rect(texture, (0,0,7,7)) if not nw or sw: rect(inside_r, (8,push,15,7+push)) # will be flipped if not ne: rect(texture, (8,0,15,7)) if not ne or nw: rect(inside_l, (0,push,7,7+push)) if not ne or se: rect(inside_r, (0,push,7,7+push)) # will be flipped if not se: rect(outside_r, (0,push,7,7+push)) # will be flipped rect(texture, (8,8,15,15)) if not se or sw: rect(inside_l, (8,push,15,7+push)) if not sw: rect(outside_l, (8,push,15,7+push)) rect(outside_r, (8,push,15,7+push)) # will be flipped rect(texture, (0,8,7,15)) img = Image.new("RGBA", (24,24), self.bgcolor) if upside_down: # top should have no cut-outs after all texture = slab_top else: # render the slab-level surface slab_top = self.transform_image_top(slab_top) alpha_over(img, slab_top, (0,6)) # render inner left surface inside_l = self.transform_image_side(inside_l) # Darken the vertical part of the second step sidealpha = inside_l.split()[3] # darken it a bit more than usual, looks better inside_l = ImageEnhance.Brightness(inside_l).enhance(0.8) inside_l.putalpha(sidealpha) alpha_over(img, inside_l, (6,3)) # render inner right surface inside_r = self.transform_image_side(inside_r).transpose(Image.FLIP_LEFT_RIGHT) # Darken the vertical part of the second step sidealpha = inside_r.split()[3] # darken it a bit more than usual, looks better inside_r = ImageEnhance.Brightness(inside_r).enhance(0.7) inside_r.putalpha(sidealpha) alpha_over(img, inside_r, (6,3)) # render outer surfaces alpha_over(img, self.build_full_block(texture, None, None, outside_l, outside_r)) return img # normal, locked (used in april's fool day), ender and trapped chest # NOTE: locked chest used to be id95 (which is now stained glass) @material(blockid=[54, 130, 146], data=list(range(30)), transparent = True) def chests(self, blockid, data): # the first 3 bits are the orientation as stored in minecraft, # bits 0x8 and 0x10 indicate which half of the double chest is it. # first, do the rotation if needed orientation_data = data & 7 if self.rotation == 1: if orientation_data == 2: data = 5 | (data & 24) elif orientation_data == 3: data = 4 | (data & 24) elif orientation_data == 4: data = 2 | (data & 24) elif orientation_data == 5: data = 3 | (data & 24) elif self.rotation == 2: if orientation_data == 2: data = 3 | (data & 24) elif orientation_data == 3: data = 2 | (data & 24) elif orientation_data == 4: data = 5 | (data & 24) elif orientation_data == 5: data = 4 | (data & 24) elif self.rotation == 3: if orientation_data == 2: data = 4 | (data & 24) elif orientation_data == 3: data = 5 | (data & 24) elif orientation_data == 4: data = 3 | (data & 24) elif orientation_data == 5: data = 2 | (data & 24) if blockid == 130 and not data in [2, 3, 4, 5]: return None # iterate.c will only return the ancil data (without pseudo # ancil data) for locked and ender chests, so only # ancilData = 2,3,4,5 are used for this blockids if data & 24 == 0: if blockid == 130: t = self.load_image("assets/minecraft/textures/entity/chest/ender.png") else: try: t = self.load_image("assets/minecraft/textures/entity/chest/normal.png") except (TextureException, IOError): t = self.load_image("assets/minecraft/textures/entity/chest/chest.png") t = ImageOps.flip(t) # for some reason the 1.15 images are upside down # the textures is no longer in terrain.png, get it from # item/chest.png and get by cropping all the needed stuff if t.size != (64, 64): t = t.resize((64, 64), Image.ANTIALIAS) # top top = t.crop((28, 50, 42, 64)) top.load() # every crop need a load, crop is a lazy operation # see PIL manual img = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(img, top, (1, 1)) top = img # front front_top = t.crop((42, 45, 56, 50)) front_top.load() front_bottom = t.crop((42, 21, 56, 31)) front_bottom.load() front_lock = t.crop((1, 59, 3, 63)) front_lock.load() front = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(front, front_top, (1, 1)) alpha_over(front, front_bottom, (1, 5)) alpha_over(front, front_lock, (7, 3)) # left side # left side, right side, and back are essentially the same for # the default texture, we take it anyway just in case other # textures make use of it. side_l_top = t.crop((14, 45, 28, 50)) side_l_top.load() side_l_bottom = t.crop((14, 21, 28, 31)) side_l_bottom.load() side_l = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(side_l, side_l_top, (1, 1)) alpha_over(side_l, side_l_bottom, (1, 5)) # right side side_r_top = t.crop((28, 45, 42, 50)) side_r_top.load() side_r_bottom = t.crop((28, 21, 42, 31)) side_r_bottom.load() side_r = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(side_r, side_r_top, (1, 1)) alpha_over(side_r, side_r_bottom, (1, 5)) # back back_top = t.crop((0, 45, 14, 50)) back_top.load() back_bottom = t.crop((0, 21, 14, 31)) back_bottom.load() back = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(back, back_top, (1, 1)) alpha_over(back, back_bottom, (1, 5)) else: # large chest # the textures is no longer in terrain.png, get it from # item/chest.png and get all the needed stuff t_left = self.load_image("assets/minecraft/textures/entity/chest/normal_left.png") t_right = self.load_image("assets/minecraft/textures/entity/chest/normal_right.png") # for some reason the 1.15 images are upside down t_left = ImageOps.flip(t_left) t_right = ImageOps.flip(t_right) # Top top_left = t_right.crop((29, 50, 44, 64)) top_left.load() top_right = t_left.crop((29, 50, 44, 64)) top_right.load() top = Image.new("RGBA", (32, 16), self.bgcolor) alpha_over(top,top_left, (1, 1)) alpha_over(top,top_right, (16, 1)) # Front front_top_left = t_left.crop((43, 45, 58, 50)) front_top_left.load() front_top_right = t_right.crop((43, 45, 58, 50)) front_top_right.load() front_bottom_left = t_left.crop((43, 21, 58, 31)) front_bottom_left.load() front_bottom_right = t_right.crop((43, 21, 58, 31)) front_bottom_right.load() front_lock = t_left.crop((1, 59, 3, 63)) front_lock.load() front = Image.new("RGBA", (32, 16), self.bgcolor) alpha_over(front, front_top_left, (1, 1)) alpha_over(front, front_top_right, (16, 1)) alpha_over(front, front_bottom_left, (1, 5)) alpha_over(front, front_bottom_right, (16, 5)) alpha_over(front, front_lock, (15, 3)) # Back back_top_left = t_right.crop((14, 45, 29, 50)) back_top_left.load() back_top_right = t_left.crop((14, 45, 29, 50)) back_top_right.load() back_bottom_left = t_right.crop((14, 21, 29, 31)) back_bottom_left.load() back_bottom_right = t_left.crop((14, 21, 29, 31)) back_bottom_right.load() back = Image.new("RGBA", (32, 16), self.bgcolor) alpha_over(back, back_top_left, (1, 1)) alpha_over(back, back_top_right, (16, 1)) alpha_over(back, back_bottom_left, (1, 5)) alpha_over(back, back_bottom_right, (16, 5)) # left side side_l_top = t_left.crop((29, 45, 43, 50)) side_l_top.load() side_l_bottom = t_left.crop((29, 21, 43, 31)) side_l_bottom.load() side_l = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(side_l, side_l_top, (1, 1)) alpha_over(side_l, side_l_bottom, (1, 5)) # right side side_r_top = t_right.crop((0, 45, 14, 50)) side_r_top.load() side_r_bottom = t_right.crop((0, 21, 14, 31)) side_r_bottom.load() side_r = Image.new("RGBA", (16, 16), self.bgcolor) alpha_over(side_r, side_r_top, (1, 1)) alpha_over(side_r, side_r_bottom, (1, 5)) # double chest, left half if ((data & 24 == 8 and data & 7 in [3, 5]) or (data & 24 == 16 and data & 7 in [2, 4])): top = top.crop((0, 0, 16, 16)) top.load() front = front.crop((0, 0, 16, 16)) front.load() back = back.crop((0, 0, 16, 16)) back.load() #~ side = side_l # double chest, right half elif ((data & 24 == 16 and data & 7 in [3, 5]) or (data & 24 == 8 and data & 7 in [2, 4])): top = top.crop((16, 0, 32, 16)) top.load() front = front.crop((16, 0, 32, 16)) front.load() back = back.crop((16, 0, 32, 16)) back.load() #~ side = side_r else: # just in case return None # compose the final block img = Image.new("RGBA", (24, 24), self.bgcolor) if data & 7 == 2: # north side = self.transform_image_side(side_r) alpha_over(img, side, (1, 7)) back = self.transform_image_side(back) alpha_over(img, back.transpose(Image.FLIP_LEFT_RIGHT), (11, 7)) front = self.transform_image_side(front) top = self.transform_image_top(top.rotate(180)) alpha_over(img, top, (0, 2)) elif data & 7 == 3: # south side = self.transform_image_side(side_l) alpha_over(img, side, (1, 7)) front = self.transform_image_side(front).transpose(Image.FLIP_LEFT_RIGHT) top = self.transform_image_top(top.rotate(180)) alpha_over(img, top, (0, 2)) alpha_over(img, front, (11, 7)) elif data & 7 == 4: # west side = self.transform_image_side(side_r) alpha_over(img, side.transpose(Image.FLIP_LEFT_RIGHT), (11, 7)) front = self.transform_image_side(front) alpha_over(img, front, (1, 7)) top = self.transform_image_top(top.rotate(270)) alpha_over(img, top, (0, 2)) elif data & 7 == 5: # east back = self.transform_image_side(back) side = self.transform_image_side(side_l).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, side, (11, 7)) alpha_over(img, back, (1, 7)) top = self.transform_image_top(top.rotate(270)) alpha_over(img, top, (0, 2)) else: # just in case img = None return img # redstone wire # uses pseudo-ancildata found in iterate.c @material(blockid=55, data=list(range(128)), transparent=True) def wire(self, blockid, data): if data & 0b1000000 == 64: # powered redstone wire redstone_wire_t = self.load_image_texture("assets/minecraft/textures/block/redstone_dust_line0.png").rotate(90) redstone_wire_t = self.tint_texture(redstone_wire_t,(255,0,0)) redstone_cross_t = self.load_image_texture("assets/minecraft/textures/block/redstone_dust_dot.png") redstone_cross_t = self.tint_texture(redstone_cross_t,(255,0,0)) else: # unpowered redstone wire redstone_wire_t = self.load_image_texture("assets/minecraft/textures/block/redstone_dust_line0.png").rotate(90) redstone_wire_t = self.tint_texture(redstone_wire_t,(48,0,0)) redstone_cross_t = self.load_image_texture("assets/minecraft/textures/block/redstone_dust_dot.png") redstone_cross_t = self.tint_texture(redstone_cross_t,(48,0,0)) # generate an image per redstone direction branch_top_left = redstone_cross_t.copy() ImageDraw.Draw(branch_top_left).rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_top_left).rectangle((11,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_top_left).rectangle((0,11,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) branch_top_right = redstone_cross_t.copy() ImageDraw.Draw(branch_top_right).rectangle((0,0,15,4),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_top_right).rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_top_right).rectangle((0,11,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) branch_bottom_right = redstone_cross_t.copy() ImageDraw.Draw(branch_bottom_right).rectangle((0,0,15,4),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_bottom_right).rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_bottom_right).rectangle((11,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) branch_bottom_left = redstone_cross_t.copy() ImageDraw.Draw(branch_bottom_left).rectangle((0,0,15,4),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_bottom_left).rectangle((11,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(branch_bottom_left).rectangle((0,11,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # generate the bottom texture if data & 0b111111 == 0: bottom = redstone_cross_t.copy() # see iterate.c for where these masks come from has_x = (data & 0b1010) > 0 has_z = (data & 0b0101) > 0 if has_x and has_z: bottom = redstone_cross_t.copy() if has_x: alpha_over(bottom, redstone_wire_t.copy()) if has_z: alpha_over(bottom, redstone_wire_t.copy().rotate(90)) else: if has_x: bottom = redstone_wire_t.copy() elif has_z: bottom = redstone_wire_t.copy().rotate(90) elif data & 0b1111 == 0: bottom = redstone_cross_t.copy() # check for going up redstone wire if data & 0b100000 == 32: side1 = redstone_wire_t.rotate(90) else: side1 = None if data & 0b010000 == 16: side2 = redstone_wire_t.rotate(90) else: side2 = None img = self.build_full_block(None,side1,side2,None,None,bottom) return img # diamond ore block(blockid=56, top_image="assets/minecraft/textures/block/diamond_ore.png") # diamond block block(blockid=57, top_image="assets/minecraft/textures/block/diamond_block.png") # Table blocks with no facing or other properties where sides are not all the same # Includes: Crafting table, fletching table, cartography table, smithing table @material(blockid=[58, 11359, 11360, 11361], solid=True, nodata=True) def block_table(self, blockid, data): block_name = {58: "crafting_table", 11359: "fletching_table", 11360: "cartography_table", 11361: "smithing_table"}[blockid] # Top texture doesn't vary with self.rotation, but texture rotation does top_tex = block_name + "_top" top_rot = [0, 270, 180, 90][self.rotation] # List of side textures from side 1 to 4 for each blockid side_tex_map = {58: ["front", "side", "front", "side"], 11359: ["front", "side", "side", "front"], 11360: ["side3", "side3", "side2", "side1"], 11361: ["front", "side", "side", "front"]}[blockid] # Determine which side textures to use side3_id = [2, 3, 1, 0][self.rotation] side4_id = [3, 1, 0, 2][self.rotation] side3_tex = block_name + "_" + side_tex_map[side3_id] side4_tex = block_name + "_" + side_tex_map[side4_id] tex_path = "assets/minecraft/textures/block" top = self.load_image_texture("{}/{}.png".format(tex_path, top_tex)).copy() side3 = self.load_image_texture("{}/{}.png".format(tex_path, side3_tex)) side4 = self.load_image_texture("{}/{}.png".format(tex_path, side4_tex)).copy() top = top.rotate(top_rot) side4 = side4.transpose(Image.FLIP_LEFT_RIGHT) return self.build_full_block(top, None, None, side3, side4, None) @material(blockid=11366, data=list(range(8)), transparent=True, solid=True, nospawn=True) def lectern(self, blockid, data): # Do rotation, mask to not clobber book data data = data & 0b100 | ((self.rotation + (data & 0b11)) % 4) # Load textures base_raw_t = self.load_image_texture("assets/minecraft/textures/block/lectern_base.png") front_raw_t = self.load_image_texture("assets/minecraft/textures/block/lectern_front.png") side_raw_t = self.load_image_texture("assets/minecraft/textures/block/lectern_sides.png") top_raw_t = self.load_image_texture("assets/minecraft/textures/block/lectern_top.png") def create_tile(img_src, coord_crop, coord_paste, rot): # Takes an image, crops a region, optionally rotates the # texture, then finally pastes it onto a 16x16 image img_out = Image.new("RGBA", (16, 16), self.bgcolor) img_in = img_src.crop(coord_crop) if rot != 0: img_in = img_in.rotate(rot, expand=True) img_out.paste(img_in, coord_paste) return img_out def darken_image(img_src, darken_value): # Takes an image & alters the brightness, leaving alpha intact alpha = img_src.split()[3] img_out = ImageEnhance.Brightness(img_src).enhance(darken_value) img_out.putalpha(alpha) return img_out # Generate base base_top_t = base_raw_t.rotate([0, 270, 180, 90][data & 0b11]) # Front & side textures are one pixel taller than they should be # pre-transformation as otherwise the topmost row of pixels # post-transformation are rather transparent, which results in # a visible gap between the base's sides & top base_front_t = create_tile(base_raw_t, (0, 13, 16, 16), (0, 13), 0) base_side_t = create_tile(base_raw_t, (0, 5, 16, 8), (0, 13), 0) base_side3_t = base_front_t if data & 0b11 == 1 else base_side_t base_side4_t = base_front_t if data & 0b11 == 0 else base_side_t img = self.build_full_block((base_top_t, 14), None, None, base_side3_t, base_side4_t, None) # Generate central pillar side_flip_t = side_raw_t.transpose(Image.FLIP_LEFT_RIGHT) # Define parameters used to obtain the texture for each side pillar_param = [{'img': front_raw_t, 'crop': (8, 4, 16, 16), 'paste': (4, 2), 'rot': 0}, # South {'img': side_raw_t, 'crop': (2, 8, 15, 16), 'paste': (4, 1), 'rot': 270}, # West {'img': front_raw_t, 'crop': (0, 4, 8, 13), 'paste': (4, 5), 'rot': 0}, # North {'img': side_flip_t, 'crop': (2, 8, 15, 16), 'paste': (4, 1), 'rot': 90}] # East # Determine which sides are rendered pillar_side = [pillar_param[(3 - (data & 0b11)) % 4], pillar_param[(2 - (data & 0b11)) % 4]] pillar_side3_t = create_tile(pillar_side[0]['img'], pillar_side[0]['crop'], pillar_side[0]['paste'], pillar_side[0]['rot']) pillar_side4_t = create_tile(pillar_side[1]['img'], pillar_side[1]['crop'], pillar_side[1]['paste'], pillar_side[1]['rot']) pillar_side4_t = pillar_side4_t.transpose(Image.FLIP_LEFT_RIGHT) pillar_side3_t = self.transform_image_side(pillar_side3_t) pillar_side3_t = darken_image(pillar_side3_t, 0.9) pillar_side4_t = self.transform_image_side(pillar_side4_t).transpose(Image.FLIP_LEFT_RIGHT) pillar_side4_t = darken_image(pillar_side4_t, 0.8) alpha_over(img, pillar_side3_t, (3, 4), pillar_side3_t) alpha_over(img, pillar_side4_t, (9, 4), pillar_side4_t) # Generate stand if (data & 0b11) in [0, 1]: # South, West stand_side3_t = create_tile(side_raw_t, (0, 0, 16, 4), (0, 4), 0) stand_side4_t = create_tile(side_raw_t, (0, 4, 13, 8), (0, 0), -22.5) else: # North, East stand_side3_t = create_tile(side_raw_t, (0, 4, 16, 8), (0, 0), 0) stand_side4_t = create_tile(side_raw_t, (0, 4, 13, 8), (0, 0), 22.5) stand_side3_t = self.transform_image_angle(stand_side3_t, math.radians(22.5)) stand_side3_t = darken_image(stand_side3_t, 0.9) stand_side4_t = self.transform_image_side(stand_side4_t).transpose(Image.FLIP_LEFT_RIGHT) stand_side4_t = darken_image(stand_side4_t, 0.8) stand_top_t = create_tile(top_raw_t, (0, 1, 16, 14), (0, 1), 0) if data & 0b100: # Lectern has a book, modify the stand top texture book_raw_t = self.load_image("assets/minecraft/textures/entity/enchanting_table_book.png") book_t = Image.new("RGBA", (14, 10), self.bgcolor) book_part_t = book_raw_t.crop((0, 0, 7, 10)) # Left cover alpha_over(stand_top_t, book_part_t, (1, 3), book_part_t) book_part_t = book_raw_t.crop((15, 0, 22, 10)) # Right cover alpha_over(stand_top_t, book_part_t, (8, 3)) book_part_t = book_raw_t.crop((24, 10, 29, 18)).rotate(180) # Left page alpha_over(stand_top_t, book_part_t, (3, 4), book_part_t) book_part_t = book_raw_t.crop((29, 10, 34, 18)).rotate(180) # Right page alpha_over(stand_top_t, book_part_t, (8, 4), book_part_t) # Perform affine transformation transform_matrix = numpy.matrix(numpy.identity(3)) if (data & 0b11) in [0, 1]: # South, West # Translate: 8 -X, 8 -Y transform_matrix *= numpy.matrix([[1, 0, 8], [0, 1, 8], [0, 0, 1]]) # Rotate 40 degrees clockwise tc = math.cos(math.radians(40)) ts = math.sin(math.radians(40)) transform_matrix *= numpy.matrix([[tc, ts, 0], [-ts, tc, 0], [0, 0, 1]]) # Shear in the Y direction tt = math.tan(math.radians(10)) transform_matrix *= numpy.matrix([[1, 0, 0], [tt, 1, 0], [0, 0, 1]]) # Scale to 70% height & 110% width transform_matrix *= numpy.matrix([[1 / 1.1, 0, 0], [0, 1 / 0.7, 0], [0, 0, 1]]) # Translate: 12 +X, 8 +Y transform_matrix *= numpy.matrix([[1, 0, -12], [0, 1, -8], [0, 0, 1]]) else: # North, East # Translate: 8 -X, 8 -Y transform_matrix *= numpy.matrix([[1, 0, 8], [0, 1, 8], [0, 0, 1]]) # Shear in the X direction tt = math.tan(math.radians(25)) transform_matrix *= numpy.matrix([[1, tt, 0], [0, 1, 0], [0, 0, 1]]) # Scale to 80% height transform_matrix *= numpy.matrix([[1, 0, 0], [0, 1 / 0.8, 0], [0, 0, 1]]) # Rotate 220 degrees clockwise tc = math.cos(math.radians(40 + 180)) ts = math.sin(math.radians(40 + 180)) transform_matrix *= numpy.matrix([[tc, ts, 0], [-ts, tc, 0], [0, 0, 1]]) # Scale to 60% height transform_matrix *= numpy.matrix([[1, 0, 0], [0, 1 / 0.6, 0], [0, 0, 1]]) # Translate: +13 X, +7 Y transform_matrix *= numpy.matrix([[1, 0, -13], [0, 1, -7], [0, 0, 1]]) transform_matrix = numpy.array(transform_matrix)[:2, :].ravel().tolist() stand_top_t = stand_top_t.transform((24, 24), Image.AFFINE, transform_matrix) img_stand = Image.new("RGBA", (24, 24), self.bgcolor) alpha_over(img_stand, stand_side3_t, (-4, 2), stand_side3_t) # Fix some holes alpha_over(img_stand, stand_side3_t, (-3, 3), stand_side3_t) alpha_over(img_stand, stand_side4_t, (12, 5), stand_side4_t) alpha_over(img_stand, stand_top_t, (0, 0), stand_top_t) # Flip the stand if North or South facing if (data & 0b11) in [0, 2]: img_stand = img_stand.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, img_stand, (0, -2), img_stand) return img @material(blockid=11367, data=list(range(4)), solid=True) def loom(self, blockid, data): # Do rotation data = (self.rotation + data) % 4 top_rot = [180, 90, 0, 270][data] side3_tex = "front" if data == 1 else "side" side4_tex = "front" if data == 0 else "side" tex_path = "assets/minecraft/textures/block" top = self.load_image_texture("{}/loom_top.png".format(tex_path)).copy() side3 = self.load_image_texture("{}/loom_{}.png".format(tex_path, side3_tex)) side4 = self.load_image_texture("{}/loom_{}.png".format(tex_path, side4_tex)).copy() top = top.rotate(top_rot) side4 = side4.transpose(Image.FLIP_LEFT_RIGHT) return self.build_full_block(top, None, None, side3, side4, None) @material(blockid=11368, data=list(range(4)), transparent=True, solid=True, nospawn=True) def stonecutter(self, blockid, data): # Do rotation data = (self.rotation + data) % 4 top_t = self.load_image_texture("assets/minecraft/textures/block/stonecutter_top.png").copy() side_t = self.load_image_texture("assets/minecraft/textures/block/stonecutter_side.png") # Stonecutter saw texture contains multiple tiles, since it's # 16px wide rely on load_image_texture() to crop appropriately blade_t = self.load_image_texture("assets/minecraft/textures/block/stonecutter_saw.png").copy() top_t = top_t.rotate([180, 90, 0, 270][data]) img = self.build_full_block((top_t, 7), None, None, side_t, side_t, None) # Add saw blade if data in [0, 2]: blade_t = blade_t.transpose(Image.FLIP_LEFT_RIGHT) blade_t = self.transform_image_side(blade_t) if data in [0, 2]: blade_t = blade_t.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, blade_t, (6, -4), blade_t) return img @material(blockid=11369, data=list(range(12)), transparent=True, solid=True, nospawn=True) def grindstone(self, blockid, data): # Do rotation, mask to not clobber mounting info data = data & 0b1100 | ((self.rotation + (data & 0b11)) % 4) # Load textures side_raw_t = self.load_image_texture("assets/minecraft/textures/block/grindstone_side.png").copy() round_raw_t = self.load_image_texture("assets/minecraft/textures/block/grindstone_round.png").copy() pivot_raw_t = self.load_image_texture("assets/minecraft/textures/block/grindstone_pivot.png").copy() leg_raw_t = self.load_image_texture("assets/minecraft/textures/block/dark_oak_log.png").copy() def create_tile(img_src, coord_crop, coord_paste, scale): # Takes an image, crops a region, optionally scales the # texture, then finally pastes it onto a 16x16 image img_out = Image.new("RGBA", (16, 16), self.bgcolor) img_in = img_src.crop(coord_crop) if scale >= 0 and scale != 1: w, h = img_in.size img_in = img_in.resize((int(w * scale), int(h * scale)), Image.NEAREST) img_out.paste(img_in, coord_paste) return img_out # Set variables defining positions of various parts wall_mounted = bool(data & 0b0100) rot_leg = [0, 270, 0][data >> 2] if wall_mounted: pos_leg = (32, 28) if data & 0b11 in [2, 3] else (10, 18) coord_leg = [(0, 0), (-10, -1), (2, 3)] offset_final = [(2, 1), (-2, 1), (-2, -1), (2, -1)][data & 0b11] else: pos_leg = [(22, 31), (22, 9)][data >> 3] coord_leg = [(0, 0), (-1, 2), (-2, -3)] offset_final = (0, 2 * (data >> 2) - 1) # Create parts # Scale up small parts like pivot & leg to avoid ugly results # when shearing & combining parts, then scale down to original # size just before final image composition scale_factor = 2 side_t = create_tile(side_raw_t, (0, 0, 12, 12), (2, 0), 1) round_ud_t = create_tile(round_raw_t, (0, 0, 8, 12), (4, 2), 1) round_lr_t = create_tile(round_raw_t, (0, 0, 8, 12), (4, 0), 1) pivot_outer_t = create_tile(pivot_raw_t, (0, 0, 6, 6), (2, 2), scale_factor) pivot_lr_t = create_tile(pivot_raw_t, (6, 0, 8, 6), (2, 2), scale_factor) pivot_ud_t = create_tile(pivot_raw_t, (8, 0, 10, 6), (2, 2), scale_factor) leg_outer_t = create_tile(leg_raw_t, (6, 9, 10, 16), (2, 2), scale_factor).rotate(rot_leg) leg_lr_t = create_tile(leg_raw_t, (12, 9, 14, 16), (2, 2), scale_factor).rotate(rot_leg) leg_ud_t = create_tile(leg_raw_t, (2, 6, 4, 10), (2, 2), scale_factor) # Transform to block sides & tops side_t = self.transform_image_side(side_t) round_ud_t = self.transform_image_top(round_ud_t) round_lr_t = self.transform_image_side(round_lr_t).transpose(Image.FLIP_LEFT_RIGHT) pivot_outer_t = self.transform_image_side(pivot_outer_t) pivot_lr_t = self.transform_image_side(pivot_lr_t).transpose(Image.FLIP_LEFT_RIGHT) pivot_ud_t = self.transform_image_top(pivot_ud_t) leg_outer_t = self.transform_image_side(leg_outer_t) if wall_mounted: leg_lr_t = self.transform_image_top(leg_lr_t).transpose(Image.FLIP_LEFT_RIGHT) leg_ud_t = self.transform_image_side(leg_ud_t).transpose(Image.FLIP_LEFT_RIGHT) else: leg_lr_t = self.transform_image_side(leg_lr_t).transpose(Image.FLIP_LEFT_RIGHT) leg_ud_t = self.transform_image_top(leg_ud_t) # Compose leg texture img_leg = Image.new("RGBA", (24 * scale_factor, 24 * scale_factor), self.bgcolor) alpha_over(img_leg, leg_outer_t, coord_leg[0], leg_outer_t) alpha_over(img_leg, leg_lr_t, coord_leg[1], leg_lr_t) alpha_over(img_leg, leg_ud_t, coord_leg[2], leg_ud_t) # Compose pivot texture (& combine with leg) img_pivot = Image.new("RGBA", (24 * scale_factor, 24 * scale_factor), self.bgcolor) alpha_over(img_pivot, pivot_ud_t, (20, 18), pivot_ud_t) alpha_over(img_pivot, pivot_lr_t, (23, 24), pivot_lr_t) # Fix gaps between face edges alpha_over(img_pivot, pivot_lr_t, (24, 24), pivot_lr_t) alpha_over(img_pivot, img_leg, pos_leg, img_leg) alpha_over(img_pivot, pivot_outer_t, (21, 21), pivot_outer_t) if hasattr(Image, "LANCZOS"): # workaround for older Pillow img_pivot = img_pivot.resize((24, 24), Image.LANCZOS) else: img_pivot = img_pivot.resize((24, 24)) # Combine leg, side, round & pivot img = Image.new("RGBA", (24, 24), self.bgcolor) img_final = img.copy() alpha_over(img, img_pivot, (1, -5), img_pivot) alpha_over(img, round_ud_t, (0, 2), round_ud_t) # Fix gaps between face edges alpha_over(img, side_t, (3, 6), side_t) alpha_over(img, round_ud_t, (0, 1), round_ud_t) alpha_over(img, round_lr_t, (10, 6), round_lr_t) alpha_over(img, img_pivot, (-5, -1), img_pivot) if (data & 0b11) in [1, 3]: img = img.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img_final, img, offset_final, img) return img_final # crops with 8 data values (like wheat) @material(blockid=59, data=list(range(8)), transparent=True, nospawn=True) def crops8(self, blockid, data): raw_crop = self.load_image_texture("assets/minecraft/textures/block/wheat_stage%d.png" % data) crop1 = self.transform_image_top(raw_crop) crop2 = self.transform_image_side(raw_crop) crop3 = crop2.transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, crop1, (0,12), crop1) alpha_over(img, crop2, (6,3), crop2) alpha_over(img, crop3, (6,3), crop3) return img # farmland and grass path (15/16 blocks) @material(blockid=[60, 208], data=list(range(2)), solid=True, transparent=True, nospawn=True) def farmland(self, blockid, data): if blockid == 60: side = self.load_image_texture("assets/minecraft/textures/block/dirt.png").copy() if data == 0: top = self.load_image_texture("assets/minecraft/textures/block/farmland.png") else: top = self.load_image_texture("assets/minecraft/textures/block/farmland_moist.png") # dirt.png is 16 pixels tall, so we need to crop it before building full block side = side.crop((0, 1, 16, 16)) else: top = self.load_image_texture("assets/minecraft/textures/block/dirt_path_top.png") side = self.load_image_texture("assets/minecraft/textures/block/dirt_path_side.png") # side already has 1 transparent pixel at the top, so it doesn't need to be modified # just shift the top image down 1 pixel return self.build_full_block((top, 1), side, side, side, side) # signposts @material(blockid=[63,11401,11402,11403,11404,11405,11406,12505,12506], data=list(range(16)), transparent=True) def signpost(self, blockid, data): # first rotations if self.rotation == 1: data = (data + 4) % 16 elif self.rotation == 2: data = (data + 8) % 16 elif self.rotation == 3: data = (data + 12) % 16 sign_texture = { # (texture on sign, texture on stick) 63: ("oak_planks.png", "oak_log.png"), 11401: ("oak_planks.png", "oak_log.png"), 11402: ("spruce_planks.png", "spruce_log.png"), 11403: ("birch_planks.png", "birch_log.png"), 11404: ("jungle_planks.png", "jungle_log.png"), 11405: ("acacia_planks.png", "acacia_log.png"), 11406: ("dark_oak_planks.png", "dark_oak_log.png"), 12505: ("crimson_planks.png", "crimson_stem.png"), 12506: ("warped_planks.png", "warped_stem.png"), } texture_path, texture_stick_path = ["assets/minecraft/textures/block/" + x for x in sign_texture[blockid]] texture = self.load_image_texture(texture_path).copy() # cut the planks to the size of a signpost ImageDraw.Draw(texture).rectangle((0,12,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # If the signpost is looking directly to the image, draw some # random dots, they will look as text. if data in (0,1,2,3,4,5,15): for i in range(15): x = randint(4,11) y = randint(3,7) texture.putpixel((x,y),(0,0,0,255)) # Minecraft uses wood texture for the signpost stick texture_stick = self.load_image_texture(texture_stick_path) texture_stick = texture_stick.resize((12,12), Image.ANTIALIAS) ImageDraw.Draw(texture_stick).rectangle((2,0,12,12),outline=(0,0,0,0),fill=(0,0,0,0)) img = Image.new("RGBA", (24,24), self.bgcolor) # W N ~90 E S ~270 angles = (330.,345.,0.,15.,30.,55.,95.,120.,150.,165.,180.,195.,210.,230.,265.,310.) angle = math.radians(angles[data]) post = self.transform_image_angle(texture, angle) # choose the position of the "3D effect" incrementx = 0 if data in (1,6,7,8,9,14): incrementx = -1 elif data in (3,4,5,11,12,13): incrementx = +1 alpha_over(img, texture_stick,(11, 8),texture_stick) # post2 is a brighter signpost pasted with a small shift, # gives to the signpost some 3D effect. post2 = ImageEnhance.Brightness(post).enhance(1.2) alpha_over(img, post2,(incrementx, -3),post2) alpha_over(img, post, (0,-2), post) return img # wooden and iron door # uses pseudo-ancildata found in iterate.c @material(blockid=[64,71,193,194,195,196,197, 499, 500], data=list(range(32)), transparent=True) def door(self, blockid, data): #Masked to not clobber block top/bottom & swung info if self.rotation == 1: if (data & 0b00011) == 0: data = data & 0b11100 | 1 elif (data & 0b00011) == 1: data = data & 0b11100 | 2 elif (data & 0b00011) == 2: data = data & 0b11100 | 3 elif (data & 0b00011) == 3: data = data & 0b11100 | 0 elif self.rotation == 2: if (data & 0b00011) == 0: data = data & 0b11100 | 2 elif (data & 0b00011) == 1: data = data & 0b11100 | 3 elif (data & 0b00011) == 2: data = data & 0b11100 | 0 elif (data & 0b00011) == 3: data = data & 0b11100 | 1 elif self.rotation == 3: if (data & 0b00011) == 0: data = data & 0b11100 | 3 elif (data & 0b00011) == 1: data = data & 0b11100 | 0 elif (data & 0b00011) == 2: data = data & 0b11100 | 1 elif (data & 0b00011) == 3: data = data & 0b11100 | 2 if data & 0x8 == 0x8: # top of the door if blockid == 64: # classic wood door raw_door = self.load_image_texture("assets/minecraft/textures/block/oak_door_top.png") elif blockid == 71: # iron door raw_door = self.load_image_texture("assets/minecraft/textures/block/iron_door_top.png") elif blockid == 193: # spruce door raw_door = self.load_image_texture("assets/minecraft/textures/block/spruce_door_top.png") elif blockid == 194: # birch door raw_door = self.load_image_texture("assets/minecraft/textures/block/birch_door_top.png") elif blockid == 195: # jungle door raw_door = self.load_image_texture("assets/minecraft/textures/block/jungle_door_top.png") elif blockid == 196: # acacia door raw_door = self.load_image_texture("assets/minecraft/textures/block/acacia_door_top.png") elif blockid == 197: # dark_oak door raw_door = self.load_image_texture("assets/minecraft/textures/block/dark_oak_door_top.png") elif blockid == 499: # crimson door raw_door = self.load_image_texture("assets/minecraft/textures/block/crimson_door_top.png") elif blockid == 500: # warped door raw_door = self.load_image_texture("assets/minecraft/textures/block/warped_door_top.png") else: # bottom of the door if blockid == 64: raw_door = self.load_image_texture("assets/minecraft/textures/block/oak_door_bottom.png") elif blockid == 71: # iron door raw_door = self.load_image_texture("assets/minecraft/textures/block/iron_door_bottom.png") elif blockid == 193: # spruce door raw_door = self.load_image_texture("assets/minecraft/textures/block/spruce_door_bottom.png") elif blockid == 194: # birch door raw_door = self.load_image_texture("assets/minecraft/textures/block/birch_door_bottom.png") elif blockid == 195: # jungle door raw_door = self.load_image_texture("assets/minecraft/textures/block/jungle_door_bottom.png") elif blockid == 196: # acacia door raw_door = self.load_image_texture("assets/minecraft/textures/block/acacia_door_bottom.png") elif blockid == 197: # dark_oak door raw_door = self.load_image_texture("assets/minecraft/textures/block/dark_oak_door_bottom.png") elif blockid == 499: # crimson door raw_door = self.load_image_texture("assets/minecraft/textures/block/crimson_door_bottom.png") elif blockid == 500: # warped door raw_door = self.load_image_texture("assets/minecraft/textures/block/warped_door_bottom.png") # if you want to render all doors as closed, then force # force closed to be True if data & 0x4 == 0x4: closed = False else: closed = True if data & 0x10 == 0x10: # hinge on the left (facing same door direction) hinge_on_left = True else: # hinge on the right (default single door) hinge_on_left = False # mask out the high bits to figure out the orientation img = Image.new("RGBA", (24,24), self.bgcolor) if (data & 0x03) == 0: # facing west when closed if hinge_on_left: if closed: tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) alpha_over(img, tex, (0,6), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) tex = tex.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (12,6), tex) else: if closed: tex = self.transform_image_side(raw_door) alpha_over(img, tex, (0,6), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) tex = tex.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (0,0), tex) if (data & 0x03) == 1: # facing north when closed if hinge_on_left: if closed: tex = self.transform_image_side(raw_door).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (0,0), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door) alpha_over(img, tex, (0,6), tex) else: if closed: tex = self.transform_image_side(raw_door).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (0,0), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door) alpha_over(img, tex, (12,0), tex) if (data & 0x03) == 2: # facing east when closed if hinge_on_left: if closed: tex = self.transform_image_side(raw_door) alpha_over(img, tex, (12,0), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door) tex = tex.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (0,0), tex) else: if closed: tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) alpha_over(img, tex, (12,0), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (12,6), tex) if (data & 0x03) == 3: # facing south when closed if hinge_on_left: if closed: tex = self.transform_image_side(raw_door).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (12,6), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) alpha_over(img, tex, (12,0), tex) else: if closed: tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) tex = tex.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (12,6), tex) else: # flip first to set the doornob on the correct side tex = self.transform_image_side(raw_door.transpose(Image.FLIP_LEFT_RIGHT)) alpha_over(img, tex, (0,6), tex) return img # ladder @material(blockid=65, data=[2, 3, 4, 5], transparent=True) def ladder(self, blockid, data): # first rotations if self.rotation == 1: if data == 2: data = 5 elif data == 3: data = 4 elif data == 4: data = 2 elif data == 5: data = 3 elif self.rotation == 2: if data == 2: data = 3 elif data == 3: data = 2 elif data == 4: data = 5 elif data == 5: data = 4 elif self.rotation == 3: if data == 2: data = 4 elif data == 3: data = 5 elif data == 4: data = 3 elif data == 5: data = 2 img = Image.new("RGBA", (24,24), self.bgcolor) raw_texture = self.load_image_texture("assets/minecraft/textures/block/ladder.png") if data == 5: # normally this ladder would be obsured by the block it's attached to # but since ladders can apparently be placed on transparent blocks, we # have to render this thing anyway. same for data == 2 tex = self.transform_image_side(raw_texture) alpha_over(img, tex, (0,6), tex) return img if data == 2: tex = self.transform_image_side(raw_texture).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (12,6), tex) return img if data == 3: tex = self.transform_image_side(raw_texture).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, tex, (0,0), tex) return img if data == 4: tex = self.transform_image_side(raw_texture) alpha_over(img, tex, (12,0), tex) return img # wall signs @material(blockid=[68,11407,11408,11409,11410,11411,11412,12507,12508], data=[2, 3, 4, 5], transparent=True) def wall_sign(self, blockid, data): # wall sign # first rotations if self.rotation == 1: if data == 2: data = 5 elif data == 3: data = 4 elif data == 4: data = 2 elif data == 5: data = 3 elif self.rotation == 2: if data == 2: data = 3 elif data == 3: data = 2 elif data == 4: data = 5 elif data == 5: data = 4 elif self.rotation == 3: if data == 2: data = 4 elif data == 3: data = 5 elif data == 4: data = 3 elif data == 5: data = 2 sign_texture = { 68: "oak_planks.png", 11407: "oak_planks.png", 11408: "spruce_planks.png", 11409: "birch_planks.png", 11410: "jungle_planks.png", 11411: "acacia_planks.png", 11412: "dark_oak_planks.png", 12507: "crimson_planks.png", 12508: "warped_planks.png", } texture_path = "assets/minecraft/textures/block/" + sign_texture[blockid] texture = self.load_image_texture(texture_path).copy() # cut the planks to the size of a signpost ImageDraw.Draw(texture).rectangle((0,12,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # draw some random black dots, they will look as text """ don't draw text at the moment, they are used in blank for decoration if data in (3,4): for i in range(15): x = randint(4,11) y = randint(3,7) texture.putpixel((x,y),(0,0,0,255)) """ img = Image.new("RGBA", (24,24), self.bgcolor) incrementx = 0 if data == 2: # east incrementx = +1 sign = self.build_full_block(None, None, None, None, texture) elif data == 3: # west incrementx = -1 sign = self.build_full_block(None, texture, None, None, None) elif data == 4: # north incrementx = +1 sign = self.build_full_block(None, None, texture, None, None) elif data == 5: # south incrementx = -1 sign = self.build_full_block(None, None, None, texture, None) sign2 = ImageEnhance.Brightness(sign).enhance(1.2) alpha_over(img, sign2,(incrementx, 2),sign2) alpha_over(img, sign, (0,3), sign) return img # levers @material(blockid=69, data=list(range(16)), transparent=True) def levers(self, blockid, data): if data & 8 == 8: powered = True else: powered = False data = data & 7 # first rotations if self.rotation == 1: # on wall levers if data == 1: data = 3 elif data == 2: data = 4 elif data == 3: data = 2 elif data == 4: data = 1 # on floor levers elif data == 5: data = 6 elif data == 6: data = 5 elif self.rotation == 2: if data == 1: data = 2 elif data == 2: data = 1 elif data == 3: data = 4 elif data == 4: data = 3 elif data == 5: data = 5 elif data == 6: data = 6 elif self.rotation == 3: if data == 1: data = 4 elif data == 2: data = 3 elif data == 3: data = 1 elif data == 4: data = 2 elif data == 5: data = 6 elif data == 6: data = 5 # generate the texture for the base of the lever t_base = self.load_image_texture("assets/minecraft/textures/block/stone.png").copy() ImageDraw.Draw(t_base).rectangle((0,0,15,3),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(t_base).rectangle((0,12,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(t_base).rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(t_base).rectangle((11,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # generate the texture for the stick stick = self.load_image_texture("assets/minecraft/textures/block/lever.png").copy() c_stick = Image.new("RGBA", (16,16), self.bgcolor) tmp = ImageEnhance.Brightness(stick).enhance(0.8) alpha_over(c_stick, tmp, (1,0), tmp) alpha_over(c_stick, stick, (0,0), stick) t_stick = self.transform_image_side(c_stick.rotate(45, Image.NEAREST)) # where the lever will be composed img = Image.new("RGBA", (24,24), self.bgcolor) # wall levers if data == 1: # facing SOUTH # levers can't be placed in transparent blocks, so this # direction is almost invisible return None elif data == 2: # facing NORTH base = self.transform_image_side(t_base) # paste it twice with different brightness to make a fake 3D effect alpha_over(img, base, (12,-1), base) alpha = base.split()[3] base = ImageEnhance.Brightness(base).enhance(0.9) base.putalpha(alpha) alpha_over(img, base, (11,0), base) # paste the lever stick pos = (7,-7) if powered: t_stick = t_stick.transpose(Image.FLIP_TOP_BOTTOM) pos = (7,6) alpha_over(img, t_stick, pos, t_stick) elif data == 3: # facing WEST base = self.transform_image_side(t_base) # paste it twice with different brightness to make a fake 3D effect base = base.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, base, (0,-1), base) alpha = base.split()[3] base = ImageEnhance.Brightness(base).enhance(0.9) base.putalpha(alpha) alpha_over(img, base, (1,0), base) # paste the lever stick t_stick = t_stick.transpose(Image.FLIP_LEFT_RIGHT) pos = (5,-7) if powered: t_stick = t_stick.transpose(Image.FLIP_TOP_BOTTOM) pos = (6,6) alpha_over(img, t_stick, pos, t_stick) elif data == 4: # facing EAST # levers can't be placed in transparent blocks, so this # direction is almost invisible return None # floor levers elif data == 5: # pointing south when off # lever base, fake 3d again base = self.transform_image_top(t_base) alpha = base.split()[3] tmp = ImageEnhance.Brightness(base).enhance(0.8) tmp.putalpha(alpha) alpha_over(img, tmp, (0,12), tmp) alpha_over(img, base, (0,11), base) # lever stick pos = (3,2) if not powered: t_stick = t_stick.transpose(Image.FLIP_LEFT_RIGHT) pos = (11,2) alpha_over(img, t_stick, pos, t_stick) elif data == 6: # pointing east when off # lever base, fake 3d again base = self.transform_image_top(t_base.rotate(90)) alpha = base.split()[3] tmp = ImageEnhance.Brightness(base).enhance(0.8) tmp.putalpha(alpha) alpha_over(img, tmp, (0,12), tmp) alpha_over(img, base, (0,11), base) # lever stick pos = (2,3) if not powered: t_stick = t_stick.transpose(Image.FLIP_LEFT_RIGHT) pos = (10,2) alpha_over(img, t_stick, pos, t_stick) return img # wooden and stone pressure plates, and weighted pressure plates @material(blockid=[70, 72,147,148,11301,11302,11303,11304,11305, 1033,11517,11518], data=[0,1], transparent=True) def pressure_plate(self, blockid, data): texture_name = {70:"assets/minecraft/textures/block/stone.png", # stone 72:"assets/minecraft/textures/block/oak_planks.png", # oak 11301:"assets/minecraft/textures/block/spruce_planks.png", # spruce 11302:"assets/minecraft/textures/block/birch_planks.png", # birch 11303:"assets/minecraft/textures/block/jungle_planks.png", # jungle 11304:"assets/minecraft/textures/block/acacia_planks.png", # acacia 11305:"assets/minecraft/textures/block/dark_oak_planks.png", # dark oak 11517:"assets/minecraft/textures/block/crimson_planks.png", # crimson 11518:"assets/minecraft/textures/block/warped_planks.png", # warped 147:"assets/minecraft/textures/block/gold_block.png", # light golden 148:"assets/minecraft/textures/block/iron_block.png", # heavy iron 1033:"assets/minecraft/textures/block/polished_blackstone.png" }[blockid] t = self.load_image_texture(texture_name).copy() # cut out the outside border, pressure plates are smaller # than a normal block ImageDraw.Draw(t).rectangle((0,0,15,15),outline=(0,0,0,0)) # create the textures and a darker version to make a 3d by # pasting them with an offstet of 1 pixel img = Image.new("RGBA", (24,24), self.bgcolor) top = self.transform_image_top(t) alpha = top.split()[3] topd = ImageEnhance.Brightness(top).enhance(0.8) topd.putalpha(alpha) #show it 3d or 2d if unpressed or pressed if data == 0: alpha_over(img,topd, (0,12),topd) alpha_over(img,top, (0,11),top) elif data == 1: alpha_over(img,top, (0,12),top) return img # normal and glowing redstone ore block(blockid=[73, 74], top_image="assets/minecraft/textures/block/redstone_ore.png") # stone and wood buttons @material(blockid=(77,143,11326,11327,11328,11329,11330,1034,11515,11516), data=list(range(16)), transparent=True) def buttons(self, blockid, data): # 0x8 is set if the button is pressed mask this info and render # it as unpressed data = data & 0x7 if self.rotation == 1: if data == 1: data = 3 elif data == 2: data = 4 elif data == 3: data = 2 elif data == 4: data = 1 elif data == 5: data = 6 elif data == 6: data = 5 elif self.rotation == 2: if data == 1: data = 2 elif data == 2: data = 1 elif data == 3: data = 4 elif data == 4: data = 3 elif self.rotation == 3: if data == 1: data = 4 elif data == 2: data = 3 elif data == 3: data = 1 elif data == 4: data = 2 elif data == 5: data = 6 elif data == 6: data = 5 texturepath = {77:"assets/minecraft/textures/block/stone.png", 143:"assets/minecraft/textures/block/oak_planks.png", 11326:"assets/minecraft/textures/block/spruce_planks.png", 11327:"assets/minecraft/textures/block/birch_planks.png", 11328:"assets/minecraft/textures/block/jungle_planks.png", 11329:"assets/minecraft/textures/block/acacia_planks.png", 11330:"assets/minecraft/textures/block/dark_oak_planks.png", 1034:"assets/minecraft/textures/block/polished_blackstone.png", 11515:"assets/minecraft/textures/block/crimson_planks.png", 11516:"assets/minecraft/textures/block/warped_planks.png" }[blockid] t = self.load_image_texture(texturepath).copy() # generate the texture for the button ImageDraw.Draw(t).rectangle((0,0,15,5),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(t).rectangle((0,10,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(t).rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(t).rectangle((11,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) img = Image.new("RGBA", (24,24), self.bgcolor) if data < 5: button = self.transform_image_side(t) if data == 1: # facing SOUTH # buttons can't be placed in transparent blocks, so this # direction can't be seen return None elif data == 2: # facing NORTH # paste it twice with different brightness to make a 3D effect alpha_over(img, button, (12,-1), button) alpha = button.split()[3] button = ImageEnhance.Brightness(button).enhance(0.9) button.putalpha(alpha) alpha_over(img, button, (11,0), button) elif data == 3: # facing WEST # paste it twice with different brightness to make a 3D effect button = button.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, button, (0,-1), button) alpha = button.split()[3] button = ImageEnhance.Brightness(button).enhance(0.9) button.putalpha(alpha) alpha_over(img, button, (1,0), button) elif data == 4: # facing EAST # buttons can't be placed in transparent blocks, so this # direction can't be seen return None else: if data == 5: # long axis east-west button = self.transform_image_top(t) else: # long axis north-south button = self.transform_image_top(t.rotate(90)) # paste it twice with different brightness to make a 3D effect alpha_over(img, button, (0,12), button) alpha = button.split()[3] button = ImageEnhance.Brightness(button).enhance(0.9) button.putalpha(alpha) alpha_over(img, button, (0,11), button) return img # end rod @material(blockid=198, data=list(range(6)), transparent=True, solid=True) def end_rod(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/end_rod.png") img = Image.new("RGBA", (24, 24), self.bgcolor) mask = tex.crop((0, 0, 2, 15)) sidetex = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(sidetex, mask, (14, 0), mask) mask = tex.crop((2, 3, 6, 7)) bottom = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(bottom, mask, (5, 6), mask) if data == 1 or data == 0: side = self.transform_image_side(sidetex) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) bottom = self.transform_image_top(bottom) if data == 1: # up mask = tex.crop((2, 0, 4, 2)) top = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(top, mask, (7, 2), mask) top = self.transform_image_top(top) alpha_over(img, bottom, (0, 11), bottom) alpha_over(img, side, (0, 0), side) alpha_over(img, otherside, (11, 0), otherside) alpha_over(img, top, (3, 1), top) elif data == 0: # down alpha_over(img, side, (0, 0), side) alpha_over(img, otherside, (11, 0), otherside) alpha_over(img, bottom, (0, 0), bottom) else: otherside = self.transform_image_top(sidetex) sidetex = sidetex.rotate(90) side = self.transform_image_side(sidetex) bottom = self.transform_image_side(bottom) bottom = bottom.transpose(Image.FLIP_LEFT_RIGHT) def draw_south(): alpha_over(img, bottom, (0, 0), bottom) alpha_over(img, side, (7, 8), side) alpha_over(img, otherside, (-3, 9), otherside) def draw_north(): alpha_over(img, side, (7, 8), side) alpha_over(img, otherside, (-3, 9), otherside) alpha_over(img, bottom, (12, 6), bottom) def draw_west(): _bottom = bottom.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _bottom, (13, 0), _bottom) _side = side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _side, (7, 8), _side) _otherside = otherside.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _otherside, (4, 9), _otherside) def draw_east(): _side = side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _side, (7, 8), _side) _otherside = otherside.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _otherside, (4, 9), _otherside) _bottom = bottom.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _bottom, (0, 6), _bottom) draw_funcs = [ draw_south, draw_west, draw_north, draw_east ] if data == 3: # south draw_funcs[self.rotation]() elif data == 2: # north draw_funcs[(self.rotation + 2) % len(draw_funcs)]() elif data == 4: # west draw_funcs[(self.rotation + 1) % len(draw_funcs)]() elif data == 5: # east draw_funcs[(self.rotation + 3) % len(draw_funcs)]() return img # snow @material(blockid=78, data=list(range(1, 9)), transparent=True, solid=True) def snow(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/snow.png") y = 16 - (data * 2) mask = tex.crop((0, y, 16, 16)) sidetex = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(sidetex, mask, (0,y,16,16), mask) img = Image.new("RGBA", (24,24), self.bgcolor) top = self.transform_image_top(tex) side = self.transform_image_side(sidetex) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) sidealpha = side.split()[3] side = ImageEnhance.Brightness(side).enhance(0.9) side.putalpha(sidealpha) othersidealpha = otherside.split()[3] otherside = ImageEnhance.Brightness(otherside).enhance(0.8) otherside.putalpha(othersidealpha) alpha_over(img, side, (0, 6), side) alpha_over(img, otherside, (12, 6), otherside) alpha_over(img, top, (0, 12 - int(12 / 8 * data)), top) return img # snow block block(blockid=80, top_image="assets/minecraft/textures/block/snow.png") # cactus @material(blockid=81, data=list(range(15)), transparent=True, solid=True, nospawn=True) def cactus(self, blockid, data): top = self.load_image_texture("assets/minecraft/textures/block/cactus_top.png") side = self.load_image_texture("assets/minecraft/textures/block/cactus_side.png") img = Image.new("RGBA", (24,24), self.bgcolor) top = self.transform_image_top(top) side = self.transform_image_side(side) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) sidealpha = side.split()[3] side = ImageEnhance.Brightness(side).enhance(0.9) side.putalpha(sidealpha) othersidealpha = otherside.split()[3] otherside = ImageEnhance.Brightness(otherside).enhance(0.8) otherside.putalpha(othersidealpha) alpha_over(img, side, (1,6), side) alpha_over(img, otherside, (11,6), otherside) alpha_over(img, top, (0,0), top) return img # clay block block(blockid=82, top_image="assets/minecraft/textures/block/clay.png") # sugar cane @material(blockid=83, data=list(range(16)), transparent=True) def sugar_cane(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/sugar_cane.png") return self.build_sprite(tex) # jukebox @material(blockid=84, data=list(range(16)), solid=True) def jukebox(self, blockid, data): return self.build_block(self.load_image_texture("assets/minecraft/textures/block/jukebox_top.png"), self.load_image_texture("assets/minecraft/textures/block/note_block.png")) # nether and normal fences @material(blockid=[85, 188, 189, 190, 191, 192, 113, 511, 512], data=list(range(16)), transparent=True, nospawn=True) def fence(self, blockid, data): # create needed images for Big stick fence if blockid == 85: # normal fence fence_top = self.load_image_texture("assets/minecraft/textures/block/oak_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/oak_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/oak_planks.png").copy() elif blockid == 188: # spruce fence fence_top = self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png").copy() elif blockid == 189: # birch fence fence_top = self.load_image_texture("assets/minecraft/textures/block/birch_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/birch_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/birch_planks.png").copy() elif blockid == 190: # jungle fence fence_top = self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png").copy() elif blockid == 191: # big/dark oak fence fence_top = self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png").copy() elif blockid == 192: # acacia fence fence_top = self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png").copy() elif blockid == 511: # crimson_fence fence_top = self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png").copy() elif blockid == 512: # warped fence fence_top = self.load_image_texture("assets/minecraft/textures/block/warped_planks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/warped_planks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/warped_planks.png").copy() else: # netherbrick fence fence_top = self.load_image_texture("assets/minecraft/textures/block/nether_bricks.png").copy() fence_side = self.load_image_texture("assets/minecraft/textures/block/nether_bricks.png").copy() fence_small_side = self.load_image_texture("assets/minecraft/textures/block/nether_bricks.png").copy() # generate the textures of the fence ImageDraw.Draw(fence_top).rectangle((0,0,5,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_top).rectangle((10,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_top).rectangle((0,0,15,5),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_top).rectangle((0,10,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_side).rectangle((0,0,5,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_side).rectangle((10,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # Create the sides and the top of the big stick fence_side = self.transform_image_side(fence_side) fence_other_side = fence_side.transpose(Image.FLIP_LEFT_RIGHT) fence_top = self.transform_image_top(fence_top) # Darken the sides slightly. These methods also affect the alpha layer, # so save them first (we don't want to "darken" the alpha layer making # the block transparent) sidealpha = fence_side.split()[3] fence_side = ImageEnhance.Brightness(fence_side).enhance(0.9) fence_side.putalpha(sidealpha) othersidealpha = fence_other_side.split()[3] fence_other_side = ImageEnhance.Brightness(fence_other_side).enhance(0.8) fence_other_side.putalpha(othersidealpha) # Compose the fence big stick fence_big = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(fence_big,fence_side, (5,4),fence_side) alpha_over(fence_big,fence_other_side, (7,4),fence_other_side) alpha_over(fence_big,fence_top, (0,0),fence_top) # Now render the small sticks. # Create needed images ImageDraw.Draw(fence_small_side).rectangle((0,0,15,0),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_small_side).rectangle((0,4,15,6),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_small_side).rectangle((0,10,15,16),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_small_side).rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(fence_small_side).rectangle((11,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # Create the sides and the top of the small sticks fence_small_side = self.transform_image_side(fence_small_side) fence_small_other_side = fence_small_side.transpose(Image.FLIP_LEFT_RIGHT) # Darken the sides slightly. These methods also affect the alpha layer, # so save them first (we don't want to "darken" the alpha layer making # the block transparent) sidealpha = fence_small_other_side.split()[3] fence_small_other_side = ImageEnhance.Brightness(fence_small_other_side).enhance(0.9) fence_small_other_side.putalpha(sidealpha) sidealpha = fence_small_side.split()[3] fence_small_side = ImageEnhance.Brightness(fence_small_side).enhance(0.9) fence_small_side.putalpha(sidealpha) # Create img to compose the fence img = Image.new("RGBA", (24,24), self.bgcolor) # Position of fence small sticks in img. # These postitions are strange because the small sticks of the # fence are at the very left and at the very right of the 16x16 images pos_top_left = (2,3) pos_top_right = (10,3) pos_bottom_right = (10,7) pos_bottom_left = (2,7) # +x axis points top right direction # +y axis points bottom right direction # First compose small sticks in the back of the image, # then big stick and then small sticks in the front. def draw_north(): alpha_over(img, fence_small_side, pos_top_left, fence_small_side) def draw_east(): alpha_over(img, fence_small_other_side, pos_top_right, fence_small_other_side) def draw_south(): alpha_over(img, fence_small_side, pos_bottom_right, fence_small_side) def draw_west(): alpha_over(img, fence_small_other_side, pos_bottom_left, fence_small_other_side) draw_funcs = [draw_north, draw_east, draw_south, draw_west] if (data & 0b0001): draw_funcs[(self.rotation + 0) % len(draw_funcs)]() if (data & 0b0010): draw_funcs[(self.rotation + 1) % len(draw_funcs)]() alpha_over(img, fence_big, (0, 0), fence_big) if (data & 0b0100): draw_funcs[(self.rotation + 2) % len(draw_funcs)]() if (data & 0b1000): draw_funcs[(self.rotation + 3) % len(draw_funcs)]() return img # pumpkin @material(blockid=[86, 91,11300], data=list(range(4)), solid=True) def pumpkin(self, blockid, data): # pumpkins, jack-o-lantern # rotation if self.rotation == 1: if data == 0: data = 1 elif data == 1: data = 2 elif data == 2: data = 3 elif data == 3: data = 0 elif self.rotation == 2: if data == 0: data = 2 elif data == 1: data = 3 elif data == 2: data = 0 elif data == 3: data = 1 elif self.rotation == 3: if data == 0: data = 3 elif data == 1: data = 0 elif data == 2: data = 1 elif data == 3: data = 2 # texture generation top = self.load_image_texture("assets/minecraft/textures/block/pumpkin_top.png") frontName = {86: "assets/minecraft/textures/block/pumpkin_side.png", 91: "assets/minecraft/textures/block/jack_o_lantern.png", 11300: "assets/minecraft/textures/block/carved_pumpkin.png" }[blockid] front = self.load_image_texture(frontName) side = self.load_image_texture("assets/minecraft/textures/block/pumpkin_side.png") if data == 0: # pointing west img = self.build_full_block(top, None, None, side, front) elif data == 1: # pointing north img = self.build_full_block(top, None, None, front, side) else: # in any other direction the front can't be seen img = self.build_full_block(top, None, None, side, side) return img # netherrack block(blockid=87, top_image="assets/minecraft/textures/block/netherrack.png") # soul sand block(blockid=88, top_image="assets/minecraft/textures/block/soul_sand.png") # glowstone block(blockid=89, top_image="assets/minecraft/textures/block/glowstone.png") # shroomlight block(blockid=1011, top_image="assets/minecraft/textures/block/shroomlight.png") # portal @material(blockid=90, data=[1, 2, 4, 5, 8, 10], transparent=True) def portal(self, blockid, data): # no rotations, uses pseudo data portaltexture = self.load_portal() img = Image.new("RGBA", (24,24), self.bgcolor) side = self.transform_image_side(portaltexture) otherside = side.transpose(Image.FLIP_TOP_BOTTOM) if data in (1,4,5): alpha_over(img, side, (5,4), side) if data in (2,8,10): alpha_over(img, otherside, (5,4), otherside) return img # cake! @material(blockid=92, data=list(range(7)), transparent=True, nospawn=True) def cake(self, blockid, data): # cake textures top = self.load_image_texture("assets/minecraft/textures/block/cake_top.png").copy() side = self.load_image_texture("assets/minecraft/textures/block/cake_side.png").copy() fullside = side.copy() inside = self.load_image_texture("assets/minecraft/textures/block/cake_inner.png") img = Image.new("RGBA", (24, 24), self.bgcolor) if data == 0: # unbitten cake top = self.transform_image_top(top) side = self.transform_image_side(side) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) # darken sides slightly sidealpha = side.split()[3] side = ImageEnhance.Brightness(side).enhance(0.9) side.putalpha(sidealpha) othersidealpha = otherside.split()[3] otherside = ImageEnhance.Brightness(otherside).enhance(0.8) otherside.putalpha(othersidealpha) # composite the cake alpha_over(img, side, (1, 6), side) alpha_over(img, otherside, (11, 5), otherside) # workaround, fixes a hole alpha_over(img, otherside, (12, 6), otherside) alpha_over(img, top, (0, 6), top) else: # cut the textures for a bitten cake bite_width = int(14 / 7) # Cake is 14px wide with 7 slices coord = 1 + bite_width * data ImageDraw.Draw(side).rectangle((16 - coord, 0, 16, 16), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) ImageDraw.Draw(top).rectangle((0, 0, coord - 1, 16), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) # the bitten part of the cake always points to the west # composite the cake for every north orientation if self.rotation == 0: # north top-left # create right side rs = self.transform_image_side(side).transpose(Image.FLIP_LEFT_RIGHT) # create bitten side and its coords deltax = bite_width * data deltay = -1 * data if data in [3, 4, 5, 6]: deltax -= 1 ls = self.transform_image_side(inside) # create top side t = self.transform_image_top(top) # darken sides slightly sidealpha = ls.split()[3] ls = ImageEnhance.Brightness(ls).enhance(0.9) ls.putalpha(sidealpha) othersidealpha = rs.split()[3] rs = ImageEnhance.Brightness(rs).enhance(0.8) rs.putalpha(othersidealpha) # compose the cake alpha_over(img, rs, (12, 6), rs) alpha_over(img, ls, (1 + deltax, 6 + deltay), ls) alpha_over(img, t, (1, 6), t) elif self.rotation == 1: # north top-right # bitten side not shown # create left side ls = self.transform_image_side(side.transpose(Image.FLIP_LEFT_RIGHT)) # create top t = self.transform_image_top(top.rotate(-90)) # create right side rs = self.transform_image_side(fullside).transpose(Image.FLIP_LEFT_RIGHT) # darken sides slightly sidealpha = ls.split()[3] ls = ImageEnhance.Brightness(ls).enhance(0.9) ls.putalpha(sidealpha) othersidealpha = rs.split()[3] rs = ImageEnhance.Brightness(rs).enhance(0.8) rs.putalpha(othersidealpha) # compose the cake alpha_over(img, ls, (2, 6), ls) alpha_over(img, t, (1, 6), t) alpha_over(img, rs, (12, 6), rs) elif self.rotation == 2: # north bottom-right # bitten side not shown # left side ls = self.transform_image_side(fullside) # top t = self.transform_image_top(top.rotate(180)) # right side rs = self.transform_image_side(side.transpose(Image.FLIP_LEFT_RIGHT)) rs = rs.transpose(Image.FLIP_LEFT_RIGHT) # darken sides slightly sidealpha = ls.split()[3] ls = ImageEnhance.Brightness(ls).enhance(0.9) ls.putalpha(sidealpha) othersidealpha = rs.split()[3] rs = ImageEnhance.Brightness(rs).enhance(0.8) rs.putalpha(othersidealpha) # compose the cake alpha_over(img, ls, (2, 6), ls) alpha_over(img, t, (1, 6), t) alpha_over(img, rs, (12, 6), rs) elif self.rotation == 3: # north bottom-left # create left side ls = self.transform_image_side(side) # create top t = self.transform_image_top(top.rotate(90)) # create right side and its coords deltax = 12 - bite_width * data deltay = -1 * data if data in [3, 4, 5, 6]: deltax += 1 rs = self.transform_image_side(inside).transpose(Image.FLIP_LEFT_RIGHT) # darken sides slightly sidealpha = ls.split()[3] ls = ImageEnhance.Brightness(ls).enhance(0.9) ls.putalpha(sidealpha) othersidealpha = rs.split()[3] rs = ImageEnhance.Brightness(rs).enhance(0.8) rs.putalpha(othersidealpha) # compose the cake alpha_over(img, ls, (2, 6), ls) alpha_over(img, t, (1, 6), t) alpha_over(img, rs, (1 + deltax, 6 + deltay), rs) return img # redstone repeaters ON and OFF @material(blockid=[93,94], data=list(range(16)), transparent=True, nospawn=True) def repeater(self, blockid, data): # rotation # Masked to not clobber delay info if self.rotation == 1: if (data & 0b0011) == 0: data = data & 0b1100 | 1 elif (data & 0b0011) == 1: data = data & 0b1100 | 2 elif (data & 0b0011) == 2: data = data & 0b1100 | 3 elif (data & 0b0011) == 3: data = data & 0b1100 | 0 elif self.rotation == 2: if (data & 0b0011) == 0: data = data & 0b1100 | 2 elif (data & 0b0011) == 1: data = data & 0b1100 | 3 elif (data & 0b0011) == 2: data = data & 0b1100 | 0 elif (data & 0b0011) == 3: data = data & 0b1100 | 1 elif self.rotation == 3: if (data & 0b0011) == 0: data = data & 0b1100 | 3 elif (data & 0b0011) == 1: data = data & 0b1100 | 0 elif (data & 0b0011) == 2: data = data & 0b1100 | 1 elif (data & 0b0011) == 3: data = data & 0b1100 | 2 # generate the diode top = self.load_image_texture("assets/minecraft/textures/block/repeater.png") if blockid == 93 else self.load_image_texture("assets/minecraft/textures/block/repeater_on.png") side = self.load_image_texture("assets/minecraft/textures/block/smooth_stone_slab_side.png") increment = 13 if (data & 0x3) == 0: # pointing east pass if (data & 0x3) == 1: # pointing south top = top.rotate(270) if (data & 0x3) == 2: # pointing west top = top.rotate(180) if (data & 0x3) == 3: # pointing north top = top.rotate(90) img = self.build_full_block( (top, increment), None, None, side, side) # compose a "3d" redstone torch t = self.load_image_texture("assets/minecraft/textures/block/redstone_torch_off.png").copy() if blockid == 93 else self.load_image_texture("assets/minecraft/textures/block/redstone_torch.png").copy() torch = Image.new("RGBA", (24,24), self.bgcolor) t_crop = t.crop((2,2,14,14)) slice = t_crop.copy() ImageDraw.Draw(slice).rectangle((6,0,12,12),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(slice).rectangle((0,0,4,12),outline=(0,0,0,0),fill=(0,0,0,0)) alpha_over(torch, slice, (6,4)) alpha_over(torch, t_crop, (5,5)) alpha_over(torch, t_crop, (6,5)) alpha_over(torch, slice, (6,6)) # paste redstone torches everywhere! # the torch is too tall for the repeater, crop the bottom. ImageDraw.Draw(torch).rectangle((0,16,24,24),outline=(0,0,0,0),fill=(0,0,0,0)) # touch up the 3d effect with big rectangles, just in case, for other texture packs ImageDraw.Draw(torch).rectangle((0,24,10,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(torch).rectangle((12,15,24,24),outline=(0,0,0,0),fill=(0,0,0,0)) # torch positions for every redstone torch orientation. # # This is a horrible list of torch orientations. I tried to # obtain these orientations by rotating the positions for one # orientation, but pixel rounding is horrible and messes the # torches. if (data & 0x3) == 0: # pointing east if (data & 0xC) == 0: # one tick delay moving_torch = (1,1) static_torch = (-3,-1) elif (data & 0xC) == 4: # two ticks delay moving_torch = (2,2) static_torch = (-3,-1) elif (data & 0xC) == 8: # three ticks delay moving_torch = (3,2) static_torch = (-3,-1) elif (data & 0xC) == 12: # four ticks delay moving_torch = (4,3) static_torch = (-3,-1) elif (data & 0x3) == 1: # pointing south if (data & 0xC) == 0: # one tick delay moving_torch = (1,1) static_torch = (5,-1) elif (data & 0xC) == 4: # two ticks delay moving_torch = (0,2) static_torch = (5,-1) elif (data & 0xC) == 8: # three ticks delay moving_torch = (-1,2) static_torch = (5,-1) elif (data & 0xC) == 12: # four ticks delay moving_torch = (-2,3) static_torch = (5,-1) elif (data & 0x3) == 2: # pointing west if (data & 0xC) == 0: # one tick delay moving_torch = (1,1) static_torch = (5,3) elif (data & 0xC) == 4: # two ticks delay moving_torch = (0,0) static_torch = (5,3) elif (data & 0xC) == 8: # three ticks delay moving_torch = (-1,0) static_torch = (5,3) elif (data & 0xC) == 12: # four ticks delay moving_torch = (-2,-1) static_torch = (5,3) elif (data & 0x3) == 3: # pointing north if (data & 0xC) == 0: # one tick delay moving_torch = (1,1) static_torch = (-3,3) elif (data & 0xC) == 4: # two ticks delay moving_torch = (2,0) static_torch = (-3,3) elif (data & 0xC) == 8: # three ticks delay moving_torch = (3,0) static_torch = (-3,3) elif (data & 0xC) == 12: # four ticks delay moving_torch = (4,-1) static_torch = (-3,3) # this paste order it's ok for east and south orientation # but it's wrong for north and west orientations. But using the # default texture pack the torches are small enough to no overlap. alpha_over(img, torch, static_torch, torch) alpha_over(img, torch, moving_torch, torch) return img # redstone comparator (149 is inactive, 150 is active) @material(blockid=[149,150], data=list(range(16)), transparent=True, nospawn=True) def comparator(self, blockid, data): # rotation # add self.rotation to the lower 2 bits, mod 4 data = data & 0b1100 | (((data & 0b11) + self.rotation) % 4) top = self.load_image_texture("assets/minecraft/textures/block/comparator.png") if blockid == 149 else self.load_image_texture("assets/minecraft/textures/block/comparator_on.png") side = self.load_image_texture("assets/minecraft/textures/block/smooth_stone_slab_side.png") increment = 13 if (data & 0x3) == 0: # pointing north pass static_torch = (-3,-1) torch = ((0,2),(6,-1)) if (data & 0x3) == 1: # pointing east top = top.rotate(270) static_torch = (5,-1) torch = ((-4,-1),(0,2)) if (data & 0x3) == 2: # pointing south top = top.rotate(180) static_torch = (5,3) torch = ((0,-4),(-4,-1)) if (data & 0x3) == 3: # pointing west top = top.rotate(90) static_torch = (-3,3) torch = ((1,-4),(6,-1)) def build_torch(active): # compose a "3d" redstone torch t = self.load_image_texture("assets/minecraft/textures/block/redstone_torch_off.png").copy() if not active else self.load_image_texture("assets/minecraft/textures/block/redstone_torch.png").copy() torch = Image.new("RGBA", (24,24), self.bgcolor) t_crop = t.crop((2,2,14,14)) slice = t_crop.copy() ImageDraw.Draw(slice).rectangle((6,0,12,12),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(slice).rectangle((0,0,4,12),outline=(0,0,0,0),fill=(0,0,0,0)) alpha_over(torch, slice, (6,4)) alpha_over(torch, t_crop, (5,5)) alpha_over(torch, t_crop, (6,5)) alpha_over(torch, slice, (6,6)) return torch active_torch = build_torch(True) inactive_torch = build_torch(False) back_torch = active_torch if (blockid == 150 or data & 0b1000 == 0b1000) else inactive_torch static_torch_img = active_torch if (data & 0b100 == 0b100) else inactive_torch img = self.build_full_block( (top, increment), None, None, side, side) alpha_over(img, static_torch_img, static_torch, static_torch_img) alpha_over(img, back_torch, torch[0], back_torch) alpha_over(img, back_torch, torch[1], back_torch) return img # trapdoor # the trapdoor is looks like a sprite when opened, that's not good @material(blockid=[96,167,11332,11333,11334,11335,11336,12501,12502], data=list(range(16)), transparent=True, nospawn=True) def trapdoor(self, blockid, data): # rotation # Masked to not clobber opened/closed info if self.rotation == 1: if (data & 0b0011) == 0: data = data & 0b1100 | 3 elif (data & 0b0011) == 1: data = data & 0b1100 | 2 elif (data & 0b0011) == 2: data = data & 0b1100 | 0 elif (data & 0b0011) == 3: data = data & 0b1100 | 1 elif self.rotation == 2: if (data & 0b0011) == 0: data = data & 0b1100 | 1 elif (data & 0b0011) == 1: data = data & 0b1100 | 0 elif (data & 0b0011) == 2: data = data & 0b1100 | 3 elif (data & 0b0011) == 3: data = data & 0b1100 | 2 elif self.rotation == 3: if (data & 0b0011) == 0: data = data & 0b1100 | 2 elif (data & 0b0011) == 1: data = data & 0b1100 | 3 elif (data & 0b0011) == 2: data = data & 0b1100 | 1 elif (data & 0b0011) == 3: data = data & 0b1100 | 0 # texture generation texturepath = {96:"assets/minecraft/textures/block/oak_trapdoor.png", 167:"assets/minecraft/textures/block/iron_trapdoor.png", 11332:"assets/minecraft/textures/block/spruce_trapdoor.png", 11333:"assets/minecraft/textures/block/birch_trapdoor.png", 11334:"assets/minecraft/textures/block/jungle_trapdoor.png", 11335:"assets/minecraft/textures/block/acacia_trapdoor.png", 11336:"assets/minecraft/textures/block/dark_oak_trapdoor.png", 12501:"assets/minecraft/textures/block/crimson_trapdoor.png", 12502:"assets/minecraft/textures/block/warped_trapdoor.png", }[blockid] if data & 0x4 == 0x4: # opened trapdoor if data & 0x08 == 0x08: texture = self.load_image_texture(texturepath).transpose(Image.FLIP_TOP_BOTTOM) else: texture = self.load_image_texture(texturepath) if data & 0x3 == 0: # west img = self.build_full_block(None, None, None, None, texture) if data & 0x3 == 1: # east img = self.build_full_block(None, texture, None, None, None) if data & 0x3 == 2: # south img = self.build_full_block(None, None, texture, None, None) if data & 0x3 == 3: # north img = self.build_full_block(None, None, None, texture, None) elif data & 0x4 == 0: # closed trapdoor texture = self.load_image_texture(texturepath) if data & 0x8 == 0x8: # is a top trapdoor img = Image.new("RGBA", (24,24), self.bgcolor) t = self.build_full_block((texture, 12), None, None, texture, texture) alpha_over(img, t, (0,-9),t) else: # is a bottom trapdoor img = self.build_full_block((texture, 12), None, None, texture, texture) return img # block with hidden silverfish (stone, cobblestone and stone brick) @material(blockid=97, data=list(range(3)), solid=True) def hidden_silverfish(self, blockid, data): if data == 0: # stone t = self.load_image_texture("assets/minecraft/textures/block/stone.png") elif data == 1: # cobblestone t = self.load_image_texture("assets/minecraft/textures/block/cobblestone.png") elif data == 2: # stone brick t = self.load_image_texture("assets/minecraft/textures/block/stone_bricks.png") img = self.build_block(t, t) return img # stone brick @material(blockid=98, data=list(range(4)), solid=True) def stone_brick(self, blockid, data): if data == 0: # normal t = self.load_image_texture("assets/minecraft/textures/block/stone_bricks.png") elif data == 1: # mossy t = self.load_image_texture("assets/minecraft/textures/block/mossy_stone_bricks.png") elif data == 2: # cracked t = self.load_image_texture("assets/minecraft/textures/block/cracked_stone_bricks.png") elif data == 3: # "circle" stone brick t = self.load_image_texture("assets/minecraft/textures/block/chiseled_stone_bricks.png") img = self.build_full_block(t, None, None, t, t) return img # huge brown/red mushrooms, and mushroom stems @material(blockid=[99, 100, 139], data=list(range(64)), solid=True) def huge_mushroom(self, blockid, data): # Re-arrange the bits in data based on self.rotation # rotation bit: 654321 # 0 DUENWS # 1 DUNWSE # 2 DUWSEN # 3 DUSENW if self.rotation in [1, 2, 3]: bit_map = {1: [6, 5, 3, 2, 1, 4], 2: [6, 5, 2, 1, 4, 3], 3: [6, 5, 1, 4, 3, 2]} new_data = 0 # Add the ith bit to new_data then shift left one at a time, # re-ordering data's bits in the order specified in bit_map for i in bit_map[self.rotation]: new_data = new_data << 1 new_data |= (data >> (i - 1)) & 1 data = new_data # texture generation texture_map = {99: "brown_mushroom_block", 100: "red_mushroom_block", 139: "mushroom_stem"} cap = self.load_image_texture("assets/minecraft/textures/block/%s.png" % texture_map[blockid]) porous = self.load_image_texture("assets/minecraft/textures/block/mushroom_block_inside.png") # Faces visible after amending data for rotation are: up, West, and South side_up = cap if data & 0b010000 else porous # Up side_west = cap if data & 0b000010 else porous # West side_south = cap if data & 0b000001 else porous # South side_south = side_south.transpose(Image.FLIP_LEFT_RIGHT) return self.build_full_block(side_up, None, None, side_west, side_south) # iron bars and glass pane # TODO glass pane is not a sprite, it has a texture for the side, # at the moment is not used @material(blockid=[101,102, 160], data=list(range(256)), transparent=True, nospawn=True) def panes(self, blockid, data): # no rotation, uses pseudo data if blockid == 101: # iron bars t = self.load_image_texture("assets/minecraft/textures/block/iron_bars.png") elif blockid == 160: t = self.load_image_texture("assets/minecraft/textures/block/%s_stained_glass.png" % color_map[data & 0xf]) else: # glass panes t = self.load_image_texture("assets/minecraft/textures/block/glass.png") left = t.copy() right = t.copy() center = t.copy() # generate the four small pieces of the glass pane ImageDraw.Draw(right).rectangle((0,0,7,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(left).rectangle((8,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(center).rectangle((0,0,6,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(center).rectangle((9,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) up_center = self.transform_image_side(center) up_left = self.transform_image_side(left) up_right = self.transform_image_side(right).transpose(Image.FLIP_TOP_BOTTOM) dw_right = self.transform_image_side(right) dw_left = self.transform_image_side(left).transpose(Image.FLIP_TOP_BOTTOM) # Create img to compose the texture img = Image.new("RGBA", (24,24), self.bgcolor) # +x axis points top right direction # +y axis points bottom right direction # First compose things in the back of the image, # then things in the front. # the lower 4 bits encode color, the upper 4 encode adjencies data = data >> 4 if data == 0: alpha_over(img, up_center, (6, 3), up_center) # center else: def draw_top_left(): alpha_over(img, up_left, (6, 3), up_left) # top left def draw_top_right(): alpha_over(img, up_right, (6, 3), up_right) # top right def draw_bottom_right(): alpha_over(img, dw_right, (6, 3), dw_right) # bottom right def draw_bottom_left(): alpha_over(img, dw_left, (6, 3), dw_left) # bottom left draw_funcs = [draw_top_left, draw_top_right, draw_bottom_right, draw_bottom_left] if (data & 0b0001) == 1: draw_funcs[(self.rotation + 0) % len(draw_funcs)]() if (data & 0b0010) == 2: draw_funcs[(self.rotation + 1) % len(draw_funcs)]() if (data & 0b0100) == 4: draw_funcs[(self.rotation + 2) % len(draw_funcs)]() if (data & 0b1000) == 8: draw_funcs[(self.rotation + 3) % len(draw_funcs)]() return img # melon block(blockid=103, top_image="assets/minecraft/textures/block/melon_top.png", side_image="assets/minecraft/textures/block/melon_side.png", solid=True) # pumpkin and melon stem # TODO To render it as in game needs from pseudo data and ancil data: # once fully grown the stem bends to the melon/pumpkin block, # at the moment only render the growing stem @material(blockid=[104,105], data=list(range(8)), transparent=True) def stem(self, blockid, data): # the ancildata value indicates how much of the texture # is shown. # not fully grown stem or no pumpkin/melon touching it, # straight up stem t = self.load_image_texture("assets/minecraft/textures/block/melon_stem.png").copy() img = Image.new("RGBA", (16,16), self.bgcolor) alpha_over(img, t, (0, int(16 - 16*((data + 1)/8.))), t) img = self.build_sprite(t) if data & 7 == 7: # fully grown stem gets brown color! # there is a conditional in rendermode-normal.c to not # tint the data value 7 img = self.tint_texture(img, (211,169,116)) return img # nether vines billboard(blockid=1012, imagename="assets/minecraft/textures/block/twisting_vines.png") billboard(blockid=1013, imagename="assets/minecraft/textures/block/twisting_vines_plant.png") billboard(blockid=1014, imagename="assets/minecraft/textures/block/weeping_vines.png") billboard(blockid=1015, imagename="assets/minecraft/textures/block/weeping_vines_plant.png") # vines @material(blockid=106, data=list(range(32)), transparent=True, solid=False, nospawn=True) def vines(self, blockid, data): # Re-arrange the bits in data based on self.rotation # rotation bit: 54321 # 0 UENWS # 1 UNWSE # 2 UWSEN # 3 USENW if self.rotation in [1, 2, 3]: bit_map = {1: [5, 3, 2, 1, 4], 2: [5, 2, 1, 4, 3], 3: [5, 1, 4, 3, 2]} new_data = 0 # Add the ith bit to new_data then shift left one at a time, # re-ordering data's bits in the order specified in bit_map for i in bit_map[self.rotation]: new_data = new_data << 1 new_data |= (data >> (i - 1)) & 1 data = new_data # decode data and prepare textures raw_texture = self.load_image_texture("assets/minecraft/textures/block/vine.png") side_up = raw_texture if data & 0b10000 else None # Up side_east = raw_texture if data & 0b01000 else None # East side_north = raw_texture if data & 0b00100 else None # North side_west = raw_texture if data & 0b00010 else None # West side_south = raw_texture if data & 0b00001 else None # South return self.build_full_block(side_up, side_north, side_east, side_west, side_south) # fence gates @material(blockid=[107, 183, 184, 185, 186, 187, 513, 514], data=list(range(8)), transparent=True, nospawn=True) def fence_gate(self, blockid, data): # rotation opened = False if data & 0x4: data = data & 0x3 opened = True if self.rotation == 1: if data == 0: data = 1 elif data == 1: data = 2 elif data == 2: data = 3 elif data == 3: data = 0 elif self.rotation == 2: if data == 0: data = 2 elif data == 1: data = 3 elif data == 2: data = 0 elif data == 3: data = 1 elif self.rotation == 3: if data == 0: data = 3 elif data == 1: data = 0 elif data == 2: data = 1 elif data == 3: data = 2 if opened: data = data | 0x4 # create the closed gate side if blockid == 107: # Oak gate_side = self.load_image_texture("assets/minecraft/textures/block/oak_planks.png").copy() elif blockid == 183: # Spruce gate_side = self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png").copy() elif blockid == 184: # Birch gate_side = self.load_image_texture("assets/minecraft/textures/block/birch_planks.png").copy() elif blockid == 185: # Jungle gate_side = self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png").copy() elif blockid == 186: # Dark Oak gate_side = self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png").copy() elif blockid == 187: # Acacia gate_side = self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png").copy() elif blockid == 513: # Crimson gate_side = self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png").copy() elif blockid == 514: # Warped gate_side = self.load_image_texture("assets/minecraft/textures/block/warped_planks.png").copy() else: return None gate_side_draw = ImageDraw.Draw(gate_side) gate_side_draw.rectangle((7,0,15,0),outline=(0,0,0,0),fill=(0,0,0,0)) gate_side_draw.rectangle((7,4,9,6),outline=(0,0,0,0),fill=(0,0,0,0)) gate_side_draw.rectangle((7,10,15,16),outline=(0,0,0,0),fill=(0,0,0,0)) gate_side_draw.rectangle((0,12,15,16),outline=(0,0,0,0),fill=(0,0,0,0)) gate_side_draw.rectangle((0,0,4,15),outline=(0,0,0,0),fill=(0,0,0,0)) gate_side_draw.rectangle((14,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # darken the sides slightly, as with the fences sidealpha = gate_side.split()[3] gate_side = ImageEnhance.Brightness(gate_side).enhance(0.9) gate_side.putalpha(sidealpha) # create the other sides mirror_gate_side = self.transform_image_side(gate_side.transpose(Image.FLIP_LEFT_RIGHT)) gate_side = self.transform_image_side(gate_side) gate_other_side = gate_side.transpose(Image.FLIP_LEFT_RIGHT) mirror_gate_other_side = mirror_gate_side.transpose(Image.FLIP_LEFT_RIGHT) # Create img to compose the fence gate img = Image.new("RGBA", (24,24), self.bgcolor) if data & 0x4: # opened data = data & 0x3 if data == 0: alpha_over(img, gate_side, (2,8), gate_side) alpha_over(img, gate_side, (13,3), gate_side) elif data == 1: alpha_over(img, gate_other_side, (-1,3), gate_other_side) alpha_over(img, gate_other_side, (10,8), gate_other_side) elif data == 2: alpha_over(img, mirror_gate_side, (-1,7), mirror_gate_side) alpha_over(img, mirror_gate_side, (10,2), mirror_gate_side) elif data == 3: alpha_over(img, mirror_gate_other_side, (2,1), mirror_gate_other_side) alpha_over(img, mirror_gate_other_side, (13,7), mirror_gate_other_side) else: # closed # positions for pasting the fence sides, as with fences pos_top_left = (2,3) pos_top_right = (10,3) pos_bottom_right = (10,7) pos_bottom_left = (2,7) if data == 0 or data == 2: alpha_over(img, gate_other_side, pos_top_right, gate_other_side) alpha_over(img, mirror_gate_other_side, pos_bottom_left, mirror_gate_other_side) elif data == 1 or data == 3: alpha_over(img, gate_side, pos_top_left, gate_side) alpha_over(img, mirror_gate_side, pos_bottom_right, mirror_gate_side) return img # mycelium block(blockid=110, top_image="assets/minecraft/textures/block/mycelium_top.png", side_image="assets/minecraft/textures/block/mycelium_side.png") # warped_nylium & crimson_nylium block(blockid=1006, top_image="assets/minecraft/textures/block/warped_nylium.png", side_image="assets/minecraft/textures/block/warped_nylium_side.png") block(blockid=1007, top_image="assets/minecraft/textures/block/crimson_nylium.png", side_image="assets/minecraft/textures/block/crimson_nylium_side.png") # lilypad # At the moment of writing this lilypads has no ancil data and their # orientation depends on their position on the map. So it uses pseudo # ancildata. @material(blockid=111, data=list(range(4)), transparent=True) def lilypad(self, blockid, data): t = self.load_image_texture("assets/minecraft/textures/block/lily_pad.png").copy() if data == 0: t = t.rotate(180) elif data == 1: t = t.rotate(270) elif data == 2: t = t elif data == 3: t = t.rotate(90) return self.build_full_block(None, None, None, None, None, t) # nether bricks @material(blockid=112, data=list(range(3)), solid=True) def nether_bricks(self, blockid, data): if data == 0: # normal t = self.load_image_texture("assets/minecraft/textures/block/nether_bricks.png") elif data == 1: # cracked t = self.load_image_texture("assets/minecraft/textures/block/cracked_nether_bricks.png") elif data == 2: # chiseled t = self.load_image_texture("assets/minecraft/textures/block/chiseled_nether_bricks.png") img = self.build_full_block(t, None, None, t, t) return img # nether wart @material(blockid=115, data=list(range(4)), transparent=True) def nether_wart(self, blockid, data): if data == 0: # just come up t = self.load_image_texture("assets/minecraft/textures/block/nether_wart_stage0.png") elif data in (1, 2): t = self.load_image_texture("assets/minecraft/textures/block/nether_wart_stage1.png") else: # fully grown t = self.load_image_texture("assets/minecraft/textures/block/nether_wart_stage2.png") # use the same technic as tall grass img = self.build_billboard(t) return img # enchantment table # TODO there's no book at the moment @material(blockid=116, transparent=True, nodata=True) def enchantment_table(self, blockid, data): # no book at the moment top = self.load_image_texture("assets/minecraft/textures/block/enchanting_table_top.png") side = self.load_image_texture("assets/minecraft/textures/block/enchanting_table_side.png") img = self.build_full_block((top, 4), None, None, side, side) return img # brewing stand # TODO this is a place holder, is a 2d image pasted @material(blockid=117, data=list(range(5)), transparent=True) def brewing_stand(self, blockid, data): base = self.load_image_texture("assets/minecraft/textures/block/brewing_stand_base.png") img = self.build_full_block(None, None, None, None, None, base) t = self.load_image_texture("assets/minecraft/textures/block/brewing_stand.png") stand = self.build_billboard(t) alpha_over(img,stand,(0,-2)) return img # cauldron @material(blockid=118, data=list(range(16)), transparent=True, solid=True, nospawn=True) def cauldron(self, blockid, data): side = self.load_image_texture("assets/minecraft/textures/block/cauldron_side.png").copy() top = self.load_image_texture("assets/minecraft/textures/block/cauldron_top.png") filltype = (data & (3 << 2)) >> 2 if filltype == 3: water = self.transform_image_top(self.load_image_texture("assets/minecraft/textures/block/powder_snow.png")) elif filltype == 2: water = self.transform_image_top(self.load_image_texture("assets/minecraft/textures/block/lava_still.png")) else: # filltype == 1 or 0 water = self.transform_image_top(self.load_image_texture("water.png")) # Side texture isn't transparent between the feet, so adjust the texture ImageDraw.Draw(side).rectangle((5, 14, 11, 16), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) level = (data & 3) if level == 0: # Empty img = self.build_full_block(top, side, side, side, side) else: # Part or fully filled # Is filled in increments of a third, with level indicating how many thirds are filled img = self.build_full_block(None, side, side, None, None) alpha_over(img, water, (0, 12 - level * 4), water) img2 = self.build_full_block(top, None, None, side, side) alpha_over(img, img2, (0, 0), img2) return img # end portal and end_gateway @material(blockid=[119,209], transparent=True, nodata=True) def end_portal(self, blockid, data): img = Image.new("RGBA", (24,24), self.bgcolor) # generate a black texure with white, blue and grey dots resembling stars t = Image.new("RGBA", (16,16), (0,0,0,255)) for color in [(155,155,155,255), (100,255,100,255), (255,255,255,255)]: for i in range(6): x = randint(0,15) y = randint(0,15) t.putpixel((x,y),color) if blockid == 209: # end_gateway return self.build_block(t, t) t = self.transform_image_top(t) alpha_over(img, t, (0,0), t) return img # end portal frame (data range 8 to get all orientations of filled) @material(blockid=120, data=list(range(8)), transparent=True, solid=True, nospawn=True) def end_portal_frame(self, blockid, data): # Do rotation, only seems to affect ender eye & top of frame data = data & 0b100 | ((self.rotation + (data & 0b11)) % 4) top = self.load_image_texture("assets/minecraft/textures/block/end_portal_frame_top.png").copy() top = top.rotate((data % 4) * 90) side = self.load_image_texture("assets/minecraft/textures/block/end_portal_frame_side.png") img = self.build_full_block((top, 4), None, None, side, side) if data & 0x4 == 0x4: # ender eye on it # generate the eye eye_t = self.load_image_texture("assets/minecraft/textures/block/end_portal_frame_eye.png").copy() eye_t_s = eye_t.copy() # cut out from the texture the side and the top of the eye ImageDraw.Draw(eye_t).rectangle((0, 0, 15, 4), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) ImageDraw.Draw(eye_t_s).rectangle((0, 4, 15, 15), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) # transform images and paste eye = self.transform_image_top(eye_t.rotate((data % 4) * 90)) eye_s = self.transform_image_side(eye_t_s) eye_os = eye_s.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, eye_s, (5, 5), eye_s) alpha_over(img, eye_os, (9, 5), eye_os) alpha_over(img, eye, (0, 0), eye) return img # end stone block(blockid=121, top_image="assets/minecraft/textures/block/end_stone.png") # dragon egg # NOTE: this isn't a block, but I think it's better than nothing block(blockid=122, top_image="assets/minecraft/textures/block/dragon_egg.png") # inactive redstone lamp block(blockid=123, top_image="assets/minecraft/textures/block/redstone_lamp.png") # active redstone lamp block(blockid=124, top_image="assets/minecraft/textures/block/redstone_lamp_on.png") # daylight sensor. @material(blockid=[151,178], transparent=True) def daylight_sensor(self, blockid, data): if blockid == 151: # daylight sensor top = self.load_image_texture("assets/minecraft/textures/block/daylight_detector_top.png") else: # inverted daylight sensor top = self.load_image_texture("assets/minecraft/textures/block/daylight_detector_inverted_top.png") side = self.load_image_texture("assets/minecraft/textures/block/daylight_detector_side.png") # cut the side texture in half mask = side.crop((0,8,16,16)) side = Image.new(side.mode, side.size, self.bgcolor) alpha_over(side, mask,(0,0,16,8), mask) # plain slab top = self.transform_image_top(top) side = self.transform_image_side(side) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) sidealpha = side.split()[3] side = ImageEnhance.Brightness(side).enhance(0.9) side.putalpha(sidealpha) othersidealpha = otherside.split()[3] otherside = ImageEnhance.Brightness(otherside).enhance(0.8) otherside.putalpha(othersidealpha) img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, side, (0,12), side) alpha_over(img, otherside, (12,12), otherside) alpha_over(img, top, (0,6), top) return img # wooden double and normal slabs # these are the new wooden slabs, blockids 43 44 still have wooden # slabs, but those are unobtainable without cheating @material(blockid=[125, 126], data=list(range(16)), transparent=(44,), solid=True) def wooden_slabs(self, blockid, data): texture = data & 7 if texture== 0: # oak top = side = self.load_image_texture("assets/minecraft/textures/block/oak_planks.png") elif texture== 1: # spruce top = side = self.load_image_texture("assets/minecraft/textures/block/spruce_planks.png") elif texture== 2: # birch top = side = self.load_image_texture("assets/minecraft/textures/block/birch_planks.png") elif texture== 3: # jungle top = side = self.load_image_texture("assets/minecraft/textures/block/jungle_planks.png") elif texture== 4: # acacia top = side = self.load_image_texture("assets/minecraft/textures/block/acacia_planks.png") elif texture== 5: # dark wood top = side = self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png") elif texture== 6: # crimson top = side = self.load_image_texture("assets/minecraft/textures/block/crimson_planks.png") elif texture== 7: # warped top = side = self.load_image_texture("assets/minecraft/textures/block/warped_planks.png") else: return None if blockid == 125: # double slab return self.build_block(top, side) return self.build_slab_block(top, side, data & 8 == 8); # emerald ore block(blockid=129, top_image="assets/minecraft/textures/block/emerald_ore.png") # emerald block block(blockid=133, top_image="assets/minecraft/textures/block/emerald_block.png") # cocoa plant @material(blockid=127, data=list(range(12)), transparent=True) def cocoa_plant(self, blockid, data): orientation = data & 3 # rotation if self.rotation == 1: if orientation == 0: orientation = 1 elif orientation == 1: orientation = 2 elif orientation == 2: orientation = 3 elif orientation == 3: orientation = 0 elif self.rotation == 2: if orientation == 0: orientation = 2 elif orientation == 1: orientation = 3 elif orientation == 2: orientation = 0 elif orientation == 3: orientation = 1 elif self.rotation == 3: if orientation == 0: orientation = 3 elif orientation == 1: orientation = 0 elif orientation == 2: orientation = 1 elif orientation == 3: orientation = 2 size = data & 12 if size == 8: # big t = self.load_image_texture("assets/minecraft/textures/block/cocoa_stage2.png") c_left = (0,3) c_right = (8,3) c_top = (5,2) elif size == 4: # normal t = self.load_image_texture("assets/minecraft/textures/block/cocoa_stage1.png") c_left = (-2,2) c_right = (8,2) c_top = (5,2) elif size == 0: # small t = self.load_image_texture("assets/minecraft/textures/block/cocoa_stage0.png") c_left = (-3,2) c_right = (6,2) c_top = (5,2) # let's get every texture piece necessary to do this stalk = t.copy() ImageDraw.Draw(stalk).rectangle((0,0,11,16),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(stalk).rectangle((12,4,16,16),outline=(0,0,0,0),fill=(0,0,0,0)) top = t.copy() # warning! changes with plant size ImageDraw.Draw(top).rectangle((0,7,16,16),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(top).rectangle((7,0,16,6),outline=(0,0,0,0),fill=(0,0,0,0)) side = t.copy() # warning! changes with plant size ImageDraw.Draw(side).rectangle((0,0,6,16),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(side).rectangle((0,0,16,3),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(side).rectangle((0,14,16,16),outline=(0,0,0,0),fill=(0,0,0,0)) # first compose the block of the cocoa plant block = Image.new("RGBA", (24,24), self.bgcolor) tmp = self.transform_image_side(side).transpose(Image.FLIP_LEFT_RIGHT) alpha_over (block, tmp, c_right,tmp) # right side tmp = tmp.transpose(Image.FLIP_LEFT_RIGHT) alpha_over (block, tmp, c_left,tmp) # left side tmp = self.transform_image_top(top) alpha_over(block, tmp, c_top,tmp) if size == 0: # fix a pixel hole block.putpixel((6,9), block.getpixel((6,10))) # compose the cocoa plant img = Image.new("RGBA", (24,24), self.bgcolor) if orientation in (2,3): # south and west tmp = self.transform_image_side(stalk).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, block,(-1,-2), block) alpha_over(img, tmp, (4,-2), tmp) if orientation == 3: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation in (0,1): # north and east tmp = self.transform_image_side(stalk.transpose(Image.FLIP_LEFT_RIGHT)) alpha_over(img, block,(-1,5), block) alpha_over(img, tmp, (2,12), tmp) if orientation == 0: img = img.transpose(Image.FLIP_LEFT_RIGHT) return img # command block @material(blockid=[137,210,211], solid=True, nodata=True) def command_block(self, blockid, data): if blockid == 210: front = self.load_image_texture("assets/minecraft/textures/block/repeating_command_block_front.png") side = self.load_image_texture("assets/minecraft/textures/block/repeating_command_block_side.png") back = self.load_image_texture("assets/minecraft/textures/block/repeating_command_block_back.png") elif blockid == 211: front = self.load_image_texture("assets/minecraft/textures/block/chain_command_block_front.png") side = self.load_image_texture("assets/minecraft/textures/block/chain_command_block_side.png") back = self.load_image_texture("assets/minecraft/textures/block/chain_command_block_back.png") else: front = self.load_image_texture("assets/minecraft/textures/block/command_block_front.png") side = self.load_image_texture("assets/minecraft/textures/block/command_block_side.png") back = self.load_image_texture("assets/minecraft/textures/block/command_block_back.png") return self.build_full_block(side, side, back, front, side) # beacon block # at the moment of writing this, it seems the beacon block doens't use # the data values @material(blockid=138, transparent=True, nodata = True) def beacon(self, blockid, data): # generate the three pieces of the block t = self.load_image_texture("assets/minecraft/textures/block/glass.png") glass = self.build_block(t,t) t = self.load_image_texture("assets/minecraft/textures/block/obsidian.png") obsidian = self.build_full_block((t,12),None, None, t, t) obsidian = obsidian.resize((20,20), Image.ANTIALIAS) t = self.load_image_texture("assets/minecraft/textures/block/beacon.png") crystal = self.build_block(t,t) crystal = crystal.resize((16,16),Image.ANTIALIAS) # compose the block img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, obsidian, (2, 4), obsidian) alpha_over(img, crystal, (4,3), crystal) alpha_over(img, glass, (0,0), glass) return img # cobblestone and mossy cobblestone walls, chorus plants, mossy stone brick walls # one additional bit of data value added for mossy and cobblestone @material(blockid=[199]+list(range(1792, 1812 + 1)), data=list(range(32)), transparent=True, nospawn=True) def cobblestone_wall(self, blockid, data): walls_id_to_tex = { 199: "assets/minecraft/textures/block/chorus_plant.png", # chorus plants 1792: "assets/minecraft/textures/block/andesite.png", 1793: "assets/minecraft/textures/block/bricks.png", 1794: "assets/minecraft/textures/block/cobblestone.png", 1795: "assets/minecraft/textures/block/diorite.png", 1796: "assets/minecraft/textures/block/end_stone_bricks.png", 1797: "assets/minecraft/textures/block/granite.png", 1798: "assets/minecraft/textures/block/mossy_cobblestone.png", 1799: "assets/minecraft/textures/block/mossy_stone_bricks.png", 1800: "assets/minecraft/textures/block/nether_bricks.png", 1801: "assets/minecraft/textures/block/prismarine.png", 1802: "assets/minecraft/textures/block/red_nether_bricks.png", 1803: "assets/minecraft/textures/block/red_sandstone.png", 1804: "assets/minecraft/textures/block/sandstone.png", 1805: "assets/minecraft/textures/block/stone_bricks.png", 1806: "assets/minecraft/textures/block/blackstone.png", 1807: "assets/minecraft/textures/block/polished_blackstone.png", 1808: "assets/minecraft/textures/block/polished_blackstone_bricks.png", 1809: "assets/minecraft/textures/block/cobbled_deepslate.png", 1810: "assets/minecraft/textures/block/polished_deepslate.png", 1811: "assets/minecraft/textures/block/deepslate_bricks.png", 1812: "assets/minecraft/textures/block/deepslate_tiles.png", } t = self.load_image_texture(walls_id_to_tex[blockid]).copy() wall_pole_top = t.copy() wall_pole_side = t.copy() wall_side_top = t.copy() wall_side = t.copy() # _full is used for walls without pole wall_side_top_full = t.copy() wall_side_full = t.copy() # generate the textures of the wall ImageDraw.Draw(wall_pole_top).rectangle((0,0,3,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_pole_top).rectangle((12,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_pole_top).rectangle((0,0,15,3),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_pole_top).rectangle((0,12,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_pole_side).rectangle((0,0,3,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_pole_side).rectangle((12,0,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # Create the sides and the top of the pole wall_pole_side = self.transform_image_side(wall_pole_side) wall_pole_other_side = wall_pole_side.transpose(Image.FLIP_LEFT_RIGHT) wall_pole_top = self.transform_image_top(wall_pole_top) # Darken the sides slightly. These methods also affect the alpha layer, # so save them first (we don't want to "darken" the alpha layer making # the block transparent) sidealpha = wall_pole_side.split()[3] wall_pole_side = ImageEnhance.Brightness(wall_pole_side).enhance(0.8) wall_pole_side.putalpha(sidealpha) othersidealpha = wall_pole_other_side.split()[3] wall_pole_other_side = ImageEnhance.Brightness(wall_pole_other_side).enhance(0.7) wall_pole_other_side.putalpha(othersidealpha) # Compose the wall pole wall_pole = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(wall_pole,wall_pole_side, (3,4),wall_pole_side) alpha_over(wall_pole,wall_pole_other_side, (9,4),wall_pole_other_side) alpha_over(wall_pole,wall_pole_top, (0,0),wall_pole_top) # create the sides and the top of a wall attached to a pole ImageDraw.Draw(wall_side).rectangle((0,0,15,2),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_side).rectangle((0,0,11,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_side_top).rectangle((0,0,11,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_side_top).rectangle((0,0,15,4),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_side_top).rectangle((0,11,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # full version, without pole ImageDraw.Draw(wall_side_full).rectangle((0,0,15,2),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_side_top_full).rectangle((0,4,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) ImageDraw.Draw(wall_side_top_full).rectangle((0,4,15,15),outline=(0,0,0,0),fill=(0,0,0,0)) # compose the sides of a wall atached to a pole tmp = Image.new("RGBA", (24,24), self.bgcolor) wall_side = self.transform_image_side(wall_side) wall_side_top = self.transform_image_top(wall_side_top) # Darken the sides slightly. These methods also affect the alpha layer, # so save them first (we don't want to "darken" the alpha layer making # the block transparent) sidealpha = wall_side.split()[3] wall_side = ImageEnhance.Brightness(wall_side).enhance(0.7) wall_side.putalpha(sidealpha) alpha_over(tmp,wall_side, (0,0),wall_side) alpha_over(tmp,wall_side_top, (-5,3),wall_side_top) wall_side = tmp wall_other_side = wall_side.transpose(Image.FLIP_LEFT_RIGHT) # compose the sides of the full wall tmp = Image.new("RGBA", (24,24), self.bgcolor) wall_side_full = self.transform_image_side(wall_side_full) wall_side_top_full = self.transform_image_top(wall_side_top_full.rotate(90)) # Darken the sides slightly. These methods also affect the alpha layer, # so save them first (we don't want to "darken" the alpha layer making # the block transparent) sidealpha = wall_side_full.split()[3] wall_side_full = ImageEnhance.Brightness(wall_side_full).enhance(0.7) wall_side_full.putalpha(sidealpha) alpha_over(tmp,wall_side_full, (4,0),wall_side_full) alpha_over(tmp,wall_side_top_full, (3,-4),wall_side_top_full) wall_side_full = tmp wall_other_side_full = wall_side_full.transpose(Image.FLIP_LEFT_RIGHT) # Create img to compose the wall img = Image.new("RGBA", (24,24), self.bgcolor) # Position wall imgs around the wall bit stick pos_top_left = (-5,-2) pos_bottom_left = (-8,4) pos_top_right = (5,-3) pos_bottom_right = (7,4) # +x axis points top right direction # +y axis points bottom right direction # There are two special cases for wall without pole. # Normal case: # First compose the walls in the back of the image, # then the pole and then the walls in the front. if (data == 0b1010) or (data == 0b11010): alpha_over(img, wall_other_side_full,(0,2), wall_other_side_full) elif (data == 0b0101) or (data == 0b10101): alpha_over(img, wall_side_full,(0,2), wall_side_full) else: if (data & 0b0001) == 1: alpha_over(img,wall_side, pos_top_left,wall_side) # top left if (data & 0b1000) == 8: alpha_over(img,wall_other_side, pos_top_right,wall_other_side) # top right alpha_over(img,wall_pole,(0,0),wall_pole) if (data & 0b0010) == 2: alpha_over(img,wall_other_side, pos_bottom_left,wall_other_side) # bottom left if (data & 0b0100) == 4: alpha_over(img,wall_side, pos_bottom_right,wall_side) # bottom right return img # carrots, potatoes @material(blockid=[141,142], data=list(range(8)), transparent=True, nospawn=True) def crops4(self, blockid, data): # carrots and potatoes have 8 data, but only 4 visual stages stage = {0:0, 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:3}[data] if blockid == 141: # carrots raw_crop = self.load_image_texture("assets/minecraft/textures/block/carrots_stage%d.png" % stage) else: # potatoes raw_crop = self.load_image_texture("assets/minecraft/textures/block/potatoes_stage%d.png" % stage) crop1 = self.transform_image_top(raw_crop) crop2 = self.transform_image_side(raw_crop) crop3 = crop2.transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, crop1, (0,12), crop1) alpha_over(img, crop2, (6,3), crop2) alpha_over(img, crop3, (6,3), crop3) return img # anvils @material(blockid=145, data=list(range(12)), transparent=True, nospawn=True) def anvil(self, blockid, data): # anvils only have two orientations, invert it for rotations 1 and 3 orientation = data & 0x1 if self.rotation in (1, 3): if orientation == 1: orientation = 0 else: orientation = 1 # get the correct textures # the bits 0x4 and 0x8 determine how damaged is the anvil if (data & 0xc) == 0: # non damaged anvil top = self.load_image_texture("assets/minecraft/textures/block/anvil_top.png") elif (data & 0xc) == 0x4: # slightly damaged top = self.load_image_texture("assets/minecraft/textures/block/chipped_anvil_top.png") elif (data & 0xc) == 0x8: # very damaged top = self.load_image_texture("assets/minecraft/textures/block/damaged_anvil_top.png") # everything else use this texture big_side = self.load_image_texture("assets/minecraft/textures/block/anvil.png").copy() small_side = self.load_image_texture("assets/minecraft/textures/block/anvil.png").copy() base = self.load_image_texture("assets/minecraft/textures/block/anvil.png").copy() small_base = self.load_image_texture("assets/minecraft/textures/block/anvil.png").copy() # cut needed patterns ImageDraw.Draw(big_side).rectangle((0, 8, 15, 15), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) ImageDraw.Draw(small_side).rectangle((0, 0, 2, 15), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) ImageDraw.Draw(small_side).rectangle((13, 0, 15, 15), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) ImageDraw.Draw(small_side).rectangle((0, 8, 15, 15), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) ImageDraw.Draw(base).rectangle((0, 0, 15, 15), outline=(0, 0, 0, 0)) ImageDraw.Draw(base).rectangle((1, 1, 14, 14), outline=(0, 0, 0, 0)) ImageDraw.Draw(small_base).rectangle((0, 0, 15, 15), outline=(0, 0, 0, 0)) ImageDraw.Draw(small_base).rectangle((1, 1, 14, 14), outline=(0, 0, 0, 0)) ImageDraw.Draw(small_base).rectangle((2, 2, 13, 13), outline=(0, 0, 0, 0)) ImageDraw.Draw(small_base).rectangle((3, 3, 12, 12), outline=(0, 0, 0, 0)) # check orientation and compose the anvil if orientation == 1: # bottom-left top-right top = top.rotate(90) left_side = small_side left_pos = (1, 6) right_side = big_side right_pos = (10, 5) else: # top-left bottom-right right_side = small_side right_pos = (12, 6) left_side = big_side left_pos = (3, 5) img = Image.new("RGBA", (24, 24), self.bgcolor) # darken sides alpha = big_side.split()[3] big_side = ImageEnhance.Brightness(big_side).enhance(0.8) big_side.putalpha(alpha) alpha = small_side.split()[3] small_side = ImageEnhance.Brightness(small_side).enhance(0.9) small_side.putalpha(alpha) alpha = base.split()[3] base_d = ImageEnhance.Brightness(base).enhance(0.8) base_d.putalpha(alpha) # compose base = self.transform_image_top(base) base_d = self.transform_image_top(base_d) small_base = self.transform_image_top(small_base) top = self.transform_image_top(top) alpha_over(img, base_d, (0, 12), base_d) alpha_over(img, base_d, (0, 11), base_d) alpha_over(img, base_d, (0, 10), base_d) alpha_over(img, small_base, (0, 10), small_base) alpha_over(img, top, (0, 1), top) # Fix gap between block edges alpha_over(img, top, (0, 0), top) left_side = self.transform_image_side(left_side) right_side = self.transform_image_side(right_side).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, left_side, left_pos, left_side) alpha_over(img, right_side, right_pos, right_side) return img # block of redstone block(blockid=152, top_image="assets/minecraft/textures/block/redstone_block.png") # nether quartz ore block(blockid=153, top_image="assets/minecraft/textures/block/nether_quartz_ore.png") # block of quartz @material(blockid=155, data=list(range(5)), solid=True) def quartz_block(self, blockid, data): if data in (0,1): # normal and chiseled quartz block if data == 0: top = self.load_image_texture("assets/minecraft/textures/block/quartz_block_top.png") side = self.load_image_texture("assets/minecraft/textures/block/quartz_block_side.png") else: top = self.load_image_texture("assets/minecraft/textures/block/chiseled_quartz_block_top.png") side = self.load_image_texture("assets/minecraft/textures/block/chiseled_quartz_block.png") return self.build_block(top, side) # pillar quartz block with orientation top = self.load_image_texture("assets/minecraft/textures/block/quartz_pillar_top.png") side = self.load_image_texture("assets/minecraft/textures/block/quartz_pillar.png").copy() if data == 2: # vertical return self.build_block(top, side) elif data == 3: # north-south oriented if self.rotation in (0,2): return self.build_full_block(side.rotate(90), None, None, top, side.rotate(90)) return self.build_full_block(side, None, None, side.rotate(90), top) elif data == 4: # east-west oriented if self.rotation in (0,2): return self.build_full_block(side, None, None, side.rotate(90), top) return self.build_full_block(side.rotate(90), None, None, top, side.rotate(90)) # hopper @material(blockid=154, data=list(range(4)), transparent=True) def hopper(self, blockid, data): #build the top side = self.load_image_texture("assets/minecraft/textures/block/hopper_outside.png") top = self.load_image_texture("assets/minecraft/textures/block/hopper_top.png") bottom = self.load_image_texture("assets/minecraft/textures/block/hopper_inside.png") hop_top = self.build_full_block((top,10), side, side, side, side, side) #build a solid block for mid/top hop_mid = self.build_full_block((top,5), side, side, side, side, side) hop_bot = self.build_block(side,side) hop_mid = hop_mid.resize((17,17),Image.ANTIALIAS) hop_bot = hop_bot.resize((10,10),Image.ANTIALIAS) #compose the final block img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, hop_bot, (7,14), hop_bot) alpha_over(img, hop_mid, (3,3), hop_mid) alpha_over(img, hop_top, (0,-6), hop_top) return img # slime block block(blockid=165, top_image="assets/minecraft/textures/block/slime_block.png") # prismarine block @material(blockid=168, data=list(range(3)), solid=True) def prismarine_block(self, blockid, data): if data == 0: # prismarine t = self.load_image_texture("assets/minecraft/textures/block/prismarine.png") elif data == 1: # prismarine bricks t = self.load_image_texture("assets/minecraft/textures/block/prismarine_bricks.png") elif data == 2: # dark prismarine t = self.load_image_texture("assets/minecraft/textures/block/dark_prismarine.png") img = self.build_block(t, t) return img # sea lantern block(blockid=169, top_image="assets/minecraft/textures/block/sea_lantern.png") # hay block @material(blockid=170, data=list(range(9)), solid=True) def hayblock(self, blockid, data): top = self.load_image_texture("assets/minecraft/textures/block/hay_block_top.png") side = self.load_image_texture("assets/minecraft/textures/block/hay_block_side.png") if self.rotation == 1: if data == 4: data = 8 elif data == 8: data = 4 elif self.rotation == 3: if data == 4: data = 8 elif data == 8: data = 4 # choose orientation and paste textures if data == 4: # east-west orientation return self.build_full_block(side.rotate(90), None, None, top, side.rotate(90)) elif data == 8: # north-south orientation return self.build_full_block(side, None, None, side.rotate(90), top) else: return self.build_block(top, side) # carpet - wool block that's small? @material(blockid=171, data=list(range(17)), transparent=True) def carpet(self, blockid, data): if data < 16: texture = self.load_image_texture("assets/minecraft/textures/block/%s_wool.png" % color_map[data]) elif data == 16: texture = self.load_image_texture("assets/minecraft/textures/block/moss_block.png") return self.build_full_block((texture,15),texture,texture,texture,texture) #clay block block(blockid=172, top_image="assets/minecraft/textures/block/terracotta.png") #stained hardened clay @material(blockid=159, data=list(range(16)), solid=True) def stained_clay(self, blockid, data): texture = self.load_image_texture("assets/minecraft/textures/block/%s_terracotta.png" % color_map[data]) return self.build_block(texture,texture) #coal block block(blockid=173, top_image="assets/minecraft/textures/block/coal_block.png") # packed ice block block(blockid=174, top_image="assets/minecraft/textures/block/packed_ice.png") #blue ice block(blockid=11312, top_image="assets/minecraft/textures/block/blue_ice.png") #smooth stones block(blockid=11313, top_image="assets/minecraft/textures/block/smooth_stone.png") # stone block(blockid=11314, top_image="assets/minecraft/textures/block/sandstone_top.png") # sandstone block(blockid=11315, top_image="assets/minecraft/textures/block/red_sandstone_top.png") # red sandstone #coral blocks block(blockid=11316, top_image="assets/minecraft/textures/block/brain_coral_block.png") block(blockid=11317, top_image="assets/minecraft/textures/block/bubble_coral_block.png") block(blockid=11318, top_image="assets/minecraft/textures/block/fire_coral_block.png") block(blockid=11319, top_image="assets/minecraft/textures/block/horn_coral_block.png") block(blockid=11320, top_image="assets/minecraft/textures/block/tube_coral_block.png") #dead coral blocks block(blockid=11321, top_image="assets/minecraft/textures/block/dead_brain_coral_block.png") block(blockid=11322, top_image="assets/minecraft/textures/block/dead_bubble_coral_block.png") block(blockid=11323, top_image="assets/minecraft/textures/block/dead_fire_coral_block.png") block(blockid=11324, top_image="assets/minecraft/textures/block/dead_horn_coral_block.png") block(blockid=11325, top_image="assets/minecraft/textures/block/dead_tube_coral_block.png") @material(blockid=175, data=list(range(16)), transparent=True) def flower(self, blockid, data): double_plant_map = ["sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony", "peony", "peony"] plant = double_plant_map[data & 0x7] if data & 0x8: part = "top" else: part = "bottom" png = "assets/minecraft/textures/block/%s_%s.png" % (plant,part) texture = self.load_image_texture(png) img = self.build_billboard(texture) #sunflower top if data == 8: bloom_tex = self.load_image_texture("assets/minecraft/textures/block/sunflower_front.png") alpha_over(img, bloom_tex.resize((14, 11), Image.ANTIALIAS), (5,5)) return img # chorus flower @material(blockid=200, data=list(range(6)), solid=True) def chorus_flower(self, blockid, data): # aged 5, dead if data == 5: texture = self.load_image_texture("assets/minecraft/textures/block/chorus_flower_dead.png") else: texture = self.load_image_texture("assets/minecraft/textures/block/chorus_flower.png") return self.build_block(texture,texture) # purpur block block(blockid=201, top_image="assets/minecraft/textures/block/purpur_block.png") # purpur pillar @material(blockid=202, data=list(range(3)), solid=True) def purpur_pillar(self, blockid, data): top=self.load_image_texture("assets/minecraft/textures/block/purpur_pillar_top.png") side=self.load_image_texture("assets/minecraft/textures/block/purpur_pillar.png") return self.build_axis_block(top, side, data) # end brick block(blockid=206, top_image="assets/minecraft/textures/block/end_stone_bricks.png") # frosted ice @material(blockid=212, data=list(range(4)), solid=True) def frosted_ice(self, blockid, data): img = self.load_image_texture("assets/minecraft/textures/block/frosted_ice_%d.png" % data) return self.build_block(img, img) # magma block block(blockid=213, top_image="assets/minecraft/textures/block/magma.png") # nether wart block block(blockid=214, top_image="assets/minecraft/textures/block/nether_wart_block.png") # warped wart block block(blockid=1010, top_image="assets/minecraft/textures/block/warped_wart_block.png") # red nether brick block(blockid=215, top_image="assets/minecraft/textures/block/red_nether_bricks.png") @material(blockid=216, data=list(range(12)), solid=True) def boneblock(self, blockid, data): # extract orientation boneblock_orientation = data & 12 if self.rotation == 1: if boneblock_orientation == 4: boneblock_orientation = 8 elif boneblock_orientation == 8: boneblock_orientation = 4 elif self.rotation == 3: if boneblock_orientation == 4: boneblock_orientation = 8 elif boneblock_orientation == 8: boneblock_orientation = 4 top = self.load_image_texture("assets/minecraft/textures/block/bone_block_top.png") side = self.load_image_texture("assets/minecraft/textures/block/bone_block_side.png") # choose orientation and paste textures if boneblock_orientation == 0: return self.build_block(top, side) elif boneblock_orientation == 4: # east-west orientation return self.build_full_block(side.rotate(90), None, None, top, side.rotate(90)) elif boneblock_orientation == 8: # north-south orientation return self.build_full_block(side, None, None, side.rotate(270), top) # observer @material(blockid=218, data=[0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13], solid=True, nospawn=True) def observer(self, blockid, data): # Do rotation if self.rotation in [1, 2, 3] and (data & 0b111) in [2, 3, 4, 5]: rotation_map = {1: {2: 5, 3: 4, 4: 2, 5: 3}, 2: {2: 3, 3: 2, 4: 5, 5: 4}, 3: {2: 4, 3: 5, 4: 3, 5: 2}} data = (data & 0b1000) | rotation_map[self.rotation][data & 0b111] front = self.load_image_texture("assets/minecraft/textures/block/observer_front.png") side = self.load_image_texture("assets/minecraft/textures/block/observer_side.png") top = self.load_image_texture("assets/minecraft/textures/block/observer_top.png") file_name_back = "observer_back_on" if data & 0b1000 else "observer_back" back = self.load_image_texture("assets/minecraft/textures/block/%s.png" % file_name_back) if data & 0b0111 == 0: # Down img = self.build_full_block(back, None, None, side.rotate(90), top) elif data & 0b0111 == 1: # Up img = self.build_full_block(front.rotate(180), None, None, side.rotate(90), top.rotate(180)) elif data & 0b0111 == 2: # East img = self.build_full_block(top.rotate(180), None, None, side, back) elif data & 0b0111 == 3: # West img = self.build_full_block(top, None, None, side, front) elif data & 0b0111 == 4: # North img = self.build_full_block(top.rotate(270), None, None, front, side) elif data & 0b0111 == 5: # South img = self.build_full_block(top.rotate(90), None, None, back, side) return img # shulker box @material(blockid=list(range(219, 235)) + [257], data=list(range(6)), solid=True, nospawn=True) def shulker_box(self, blockid, data): # Do rotation if self.rotation in [1, 2, 3] and data in [2, 3, 4, 5]: rotation_map = {1: {2: 5, 3: 4, 4: 2, 5: 3}, 2: {2: 3, 3: 2, 4: 5, 5: 4}, 3: {2: 4, 3: 5, 4: 3, 5: 2}} data = rotation_map[self.rotation][data] if blockid == 257: # Uncolored shulker box file_name = "shulker.png" else: file_name = "shulker_%s.png" % color_map[blockid - 219] shulker_t = self.load_image("assets/minecraft/textures/entity/shulker/%s" % file_name).copy() w, h = shulker_t.size res = w // 4 # Cut out the parts of the shulker texture we need for the box top = shulker_t.crop((res, 0, res * 2, res)) bottom = shulker_t.crop((res * 2, int(res * 1.75), res * 3, int(res * 2.75))) side_top = shulker_t.crop((0, res, res, int(res * 1.75))) side_bottom = shulker_t.crop((0, int(res * 2.75), res, int(res * 3.25))) side = Image.new('RGBA', (res, res)) side.paste(side_top, (0, 0), side_top) side.paste(side_bottom, (0, res // 2), side_bottom) if data == 0: # down side = side.rotate(180) img = self.build_full_block(bottom, None, None, side, side) elif data == 1: # up img = self.build_full_block(top, None, None, side, side) elif data == 2: # east img = self.build_full_block(side, None, None, side.rotate(90), bottom) elif data == 3: # west img = self.build_full_block(side.rotate(180), None, None, side.rotate(270), top) elif data == 4: # north img = self.build_full_block(side.rotate(90), None, None, top, side.rotate(270)) elif data == 5: # south img = self.build_full_block(side.rotate(270), None, None, bottom, side.rotate(90)) return img # structure block @material(blockid=255, data=list(range(4)), solid=True) def structure_block(self, blockid, data): if data == 0: img = self.load_image_texture("assets/minecraft/textures/block/structure_block_save.png") elif data == 1: img = self.load_image_texture("assets/minecraft/textures/block/structure_block_load.png") elif data == 2: img = self.load_image_texture("assets/minecraft/textures/block/structure_block_corner.png") elif data == 3: img = self.load_image_texture("assets/minecraft/textures/block/structure_block_data.png") return self.build_block(img, img) # Jigsaw block @material(blockid=256, data=list(range(6)), solid=True) def jigsaw_block(self, blockid, data): # Do rotation if self.rotation in [1, 2, 3] and data in [2, 3, 4, 5]: rotation_map = {1: {2: 5, 3: 4, 4: 2, 5: 3}, 2: {2: 3, 3: 2, 4: 5, 5: 4}, 3: {2: 4, 3: 5, 4: 3, 5: 2}} data = rotation_map[self.rotation][data] top = self.load_image_texture("assets/minecraft/textures/block/jigsaw_top.png") bottom = self.load_image_texture("assets/minecraft/textures/block/jigsaw_bottom.png") side = self.load_image_texture("assets/minecraft/textures/block/jigsaw_side.png") if data == 0: # Down img = self.build_full_block(bottom.rotate(self.rotation * 90), None, None, side.rotate(180), side.rotate(180)) elif data == 1: # Up img = self.build_full_block(top.rotate(self.rotation * 90), None, None, side, side) elif data == 2: # North img = self.build_full_block(side, None, None, side.rotate(90), bottom.rotate(180)) elif data == 3: # South img = self.build_full_block(side.rotate(180), None, None, side.rotate(270), top.rotate(270)) elif data == 4: # West img = self.build_full_block(side.rotate(90), None, None, top.rotate(180), side.rotate(270)) elif data == 5: # East img = self.build_full_block(side.rotate(270), None, None, bottom.rotate(180), side.rotate(90)) return img # beetroots(207), berry bushes (11505) @material(blockid=[207, 11505], data=list(range(4)), transparent=True, nospawn=True) def crops(self, blockid, data): crops_id_to_tex = { 207: "assets/minecraft/textures/block/beetroots_stage%d.png", 11505: "assets/minecraft/textures/block/sweet_berry_bush_stage%d.png", } raw_crop = self.load_image_texture(crops_id_to_tex[blockid] % data) crop1 = self.transform_image_top(raw_crop) crop2 = self.transform_image_side(raw_crop) crop3 = crop2.transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24,24), self.bgcolor) alpha_over(img, crop1, (0,12), crop1) alpha_over(img, crop2, (6,3), crop2) alpha_over(img, crop3, (6,3), crop3) return img # Concrete @material(blockid=251, data=list(range(16)), solid=True) def concrete(self, blockid, data): texture = self.load_image_texture("assets/minecraft/textures/block/%s_concrete.png" % color_map[data]) return self.build_block(texture, texture) # Concrete Powder @material(blockid=252, data=list(range(16)), solid=True) def concrete(self, blockid, data): texture = self.load_image_texture("assets/minecraft/textures/block/%s_concrete_powder.png" % color_map[data]) return self.build_block(texture, texture) # Glazed Terracotta @material(blockid=list(range(235, 251)), data=list(range(4)), solid=True) def glazed_terracotta(self, blockid, data): # Do rotation data = (self.rotation + data) % 4 texture = self.load_image_texture("assets/minecraft/textures/block/%s_glazed_terracotta.png" % color_map[blockid - 235]).copy() texture_side4 = texture.transpose(Image.FLIP_LEFT_RIGHT) if data == 0: # South return self.build_full_block(texture, None, None, texture, texture_side4.rotate(270)) elif data == 1: # West return self.build_full_block(texture.rotate(270), None, None, texture.rotate(90), texture_side4.rotate(180)) elif data == 2: # North return self.build_full_block(texture.rotate(180), None, None, texture.rotate(180), texture_side4.rotate(90)) elif data == 3: # East return self.build_full_block(texture.rotate(90), None, None, texture.rotate(270), texture_side4) # dried kelp block @material(blockid=11331, data=[0], solid=True) def sandstone(self, blockid, data): top = self.load_image_texture("assets/minecraft/textures/block/dried_kelp_top.png") return self.build_block(top, self.load_image_texture("assets/minecraft/textures/block/dried_kelp_side.png")) # scaffolding block(blockid=11414, top_image="assets/minecraft/textures/block/scaffolding_top.png", side_image="assets/minecraft/textures/block/scaffolding_side.png", solid=False, transparent=True) # beehive and bee_nest @material(blockid=[11501, 11502], data=list(range(8)), solid=True) def beehivenest(self, blockid, data): if blockid == 11501: #beehive t_top = self.load_image("assets/minecraft/textures/block/beehive_end.png") t_side = self.load_image("assets/minecraft/textures/block/beehive_side.png") t_front = self.load_image("assets/minecraft/textures/block/beehive_front.png") t_front_honey = self.load_image("assets/minecraft/textures/block/beehive_front_honey.png") elif blockid == 11502: #bee_nest t_top = self.load_image("assets/minecraft/textures/block/bee_nest_top.png") t_side = self.load_image("assets/minecraft/textures/block/bee_nest_side.png") t_front = self.load_image("assets/minecraft/textures/block/bee_nest_front.png") t_front_honey = self.load_image("assets/minecraft/textures/block/bee_nest_front_honey.png") if data >= 4: front = t_front_honey else: front = t_front if self.rotation == 0: # rendering north upper-left if data == 0 or data == 4: # south return self.build_full_block(t_top, t_side, t_side, t_side, front) elif data == 1 or data == 5: # west return self.build_full_block(t_top, t_side, t_side, front, t_side) elif data == 2 or data == 6: # north return self.build_full_block(t_top, t_side, front, t_side, t_side) elif data == 3 or data == 7: # east return self.build_full_block(t_top, front, t_side, t_side, t_side) elif self.rotation == 1: # north upper-right if data == 0 or data == 4: # south return self.build_full_block(t_top, t_side, t_side, front, t_side) elif data == 1 or data == 5: # west return self.build_full_block(t_top, t_side, front, t_side, t_side) elif data == 2 or data == 6: # north return self.build_full_block(t_top, front, t_side, t_side, t_side) elif data == 3 or data == 7: # east return self.build_full_block(t_top, t_side, t_side, t_side, front) elif self.rotation == 2: # north lower-right if data == 0 or data == 4: # south return self.build_full_block(t_top, t_side, front, t_side, t_side) elif data == 1 or data == 5: # west return self.build_full_block(t_top, front, t_side, t_side, t_side) elif data == 2 or data == 6: # north return self.build_full_block(t_top, t_side, t_side, t_side, front) elif data == 3 or data == 7: # east return self.build_full_block(t_top, t_side, t_side, front, t_side) elif self.rotation == 3: # north lower-left if data == 0 or data == 4: # south return self.build_full_block(t_top, front, t_side, t_side, t_side) elif data == 1 or data == 5: # west return self.build_full_block(t_top, t_side, t_side, t_side, front) elif data == 2 or data == 6: # north return self.build_full_block(t_top, t_side, t_side, front, t_side) elif data == 3 or data == 7: # east return self.build_full_block(t_top, t_side, front, t_side, t_side) # honeycomb_block block(blockid=11503, top_image="assets/minecraft/textures/block/honeycomb_block.png") # honey_block block(blockid=11504, top_image="assets/minecraft/textures/block/honey_block_top.png", side_image="assets/minecraft/textures/block/honey_block_side.png") # Barrel @material(blockid=11418, data=list(range(12)), solid=True) def barrel(self, blockid, data): t_bottom = self.load_image("assets/minecraft/textures/block/barrel_bottom.png") t_side = self.load_image("assets/minecraft/textures/block/barrel_side.png") if data & 0x01: t_top = self.load_image("assets/minecraft/textures/block/barrel_top_open.png") else: t_top = self.load_image("assets/minecraft/textures/block/barrel_top.png") data = data >> 1 if data == 0: # up return self.build_full_block(t_top, None, None, t_side, t_side) elif data == 1: # down t_side = t_side.rotate(180) return self.build_full_block(t_bottom, None, None, t_side, t_side) elif data == 2: # south return self.build_full_block(t_side.rotate(180), None, None, t_side.rotate(270), t_top) elif data == 3: # east return self.build_full_block(t_side.rotate(270), None, None, t_bottom, t_side.rotate(90)) elif data == 4: # north return self.build_full_block(t_side, None, None, t_side.rotate(90), t_bottom) else: # west return self.build_full_block(t_side.rotate(90), None, None, t_top, t_side.rotate(270)) # Campfire (11506) and soul campfire (1003) @material(blockid=[11506, 1003], data=list(range(8)), solid=True, transparent=True, nospawn=True) def campfire(self, blockid, data): # Do rotation, mask to not clobber lit data data = data & 0b100 | ((self.rotation + (data & 0b11)) % 4) block_name = "campfire" if blockid == 11506 else "soul_campfire" # Load textures # Fire & lit log textures contain multiple tiles, since both are # 16px wide rely on load_image_texture() to crop appropriately fire_raw_t = self.load_image_texture("assets/minecraft/textures/block/" + block_name + "_fire.png") log_raw_t = self.load_image_texture("assets/minecraft/textures/block/campfire_log.png") log_lit_raw_t = self.load_image_texture("assets/minecraft/textures/block/" + block_name + "_log_lit.png") def create_tile(img_src, coord_crop, coord_paste, rot): # Takes an image, crops a region, optionally rotates the # texture, then finally pastes it onto a 16x16 image img_out = Image.new("RGBA", (16, 16), self.bgcolor) img_in = img_src.crop(coord_crop) if rot != 0: img_in = img_in.rotate(rot, expand=True) img_out.paste(img_in, coord_paste) return img_out # Generate bottom bottom_t = log_lit_raw_t if data & 0b100 else log_raw_t bottom_t = create_tile(bottom_t, (0, 8, 16, 14), (0, 5), 0) bottom_t = self.transform_image_top(bottom_t) # Generate two variants of a log: one with a lit side, one without log_t = Image.new("RGBA", (24, 24), self.bgcolor) log_end_t = create_tile(log_raw_t, (0, 4, 4, 8), (12, 6), 0) log_side_t = create_tile(log_raw_t, (0, 0, 16, 4), (0, 6), 0) log_side_lit_t = create_tile(log_lit_raw_t, (0, 0, 16, 4), (0, 6), 0) log_end_t = self.transform_image_side(log_end_t) log_top_t = self.transform_image_top(log_side_t) log_side_t = self.transform_image_side(log_side_t).transpose(Image.FLIP_LEFT_RIGHT) log_side_lit_t = self.transform_image_side(log_side_lit_t).transpose(Image.FLIP_LEFT_RIGHT) alpha_over(log_t, log_top_t, (-2, 2), log_top_t) # Fix some holes at the edges alpha_over(log_t, log_top_t, (-2, 1), log_top_t) log_lit_t = log_t.copy() # Unlit log alpha_over(log_t, log_side_t, (5, 0), log_side_t) alpha_over(log_t, log_end_t, (-7, 0), log_end_t) # Lit log. For unlit fires, just reference the unlit log texture if data & 0b100: alpha_over(log_lit_t, log_side_lit_t, (5, 0), log_side_lit_t) alpha_over(log_lit_t, log_end_t, (-7, 0), log_end_t) else: log_lit_t = log_t # Log parts. Because fire needs to be in the middle of the logs, # split the logs into two parts: Those appearing behind the fire # and those appearing in front of the fire logs_back_t = Image.new("RGBA", (24, 24), self.bgcolor) logs_front_t = Image.new("RGBA", (24, 24), self.bgcolor) # Back logs alpha_over(logs_back_t, log_lit_t, (-1, 7), log_lit_t) log_tmp_t = logs_back_t.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(logs_back_t, log_tmp_t, (1, -3), log_tmp_t) # Front logs alpha_over(logs_front_t, log_t, (7, 10), log_t) # Due to the awkward drawing order, take a small part of the back # logs that need to be drawn on top of the front logs despite # the front logs being drawn last ImageDraw.Draw(log_tmp_t).rectangle((0, 0, 18, 24), outline=(0, 0, 0, 0), fill=(0, 0, 0, 0)) alpha_over(logs_front_t, log_tmp_t, (1, -3), log_tmp_t) log_tmp_t = Image.new("RGBA", (24, 24), self.bgcolor) alpha_over(log_tmp_t, log_lit_t, (7, 10), log_lit_t) log_tmp_t = log_tmp_t.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(logs_front_t, log_tmp_t, (1, -3), log_tmp_t) # Compose final image img = Image.new("RGBA", (24, 24), self.bgcolor) alpha_over(img, bottom_t, (0, 12), bottom_t) alpha_over(img, logs_back_t, (0, 0), logs_back_t) if data & 0b100: fire_t = fire_raw_t.copy() if data & 0b11 in [0, 2]: # North, South fire_t = fire_t.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, fire_t, (4, 4), fire_t) alpha_over(img, logs_front_t, (0, 0), logs_front_t) if data & 0b11 in [0, 2]: # North, South img = img.transpose(Image.FLIP_LEFT_RIGHT) return img # Bell @material(blockid=11507, data=list(range(16)), solid=True, transparent=True, nospawn=True) def bell(self, blockid, data): # Do rotation, mask to not clobber attachment data data = data & 0b1100 | ((self.rotation + (data & 0b11)) % 4) # Load textures bell_raw_t = self.load_image("assets/minecraft/textures/entity/bell/bell_body.png") bar_raw_t = self.load_image_texture("assets/minecraft/textures/block/dark_oak_planks.png") post_raw_t = self.load_image_texture("assets/minecraft/textures/block/stone.png") def create_tile(img_src, coord_crop, coord_paste, rot): # Takes an image, crops a region, optionally rotates the # texture, then finally pastes it onto a 16x16 image img_out = Image.new("RGBA", (16, 16), self.bgcolor) img_in = img_src.crop(coord_crop) if rot != 0: img_in = img_in.rotate(rot, expand=True) img_out.paste(img_in, coord_paste) return img_out # 0 = floor, 1 = ceiling, 2 = single wall, 3 = double wall bell_type = (data & 0b1100) >> 2 # Should the bar/post texture be flipped? Yes if either: # - Attached to floor and East or West facing # - Not attached to floor and North or South facing flip_part = ((bell_type == 0 and data & 0b11 in [1, 3]) or (bell_type != 0 and data & 0b11 in [0, 2])) # Generate bell # Bell side textures varies based on self.rotation bell_sides_idx = [(0 - self.rotation) % 4, (3 - self.rotation) % 4] # Upper sides bell_coord = [x * 6 for x in bell_sides_idx] bell_ul_t = create_tile(bell_raw_t, (bell_coord[0], 6, bell_coord[0] + 6, 13), (5, 4), 180) bell_ur_t = create_tile(bell_raw_t, (bell_coord[1], 6, bell_coord[1] + 6, 13), (5, 4), 180) bell_ul_t = self.transform_image_side(bell_ul_t) bell_ur_t = self.transform_image_side(bell_ur_t.transpose(Image.FLIP_LEFT_RIGHT)) bell_ur_t = bell_ur_t.transpose(Image.FLIP_LEFT_RIGHT) # Lower sides bell_coord = [x * 8 for x in bell_sides_idx] bell_ll_t = create_tile(bell_raw_t, (bell_coord[0], 21, bell_coord[0] + 8, 23), (4, 11), 180) bell_lr_t = create_tile(bell_raw_t, (bell_coord[1], 21, bell_coord[1] + 8, 23), (4, 11), 180) bell_ll_t = self.transform_image_side(bell_ll_t) bell_lr_t = self.transform_image_side(bell_lr_t.transpose(Image.FLIP_LEFT_RIGHT)) bell_lr_t = bell_lr_t.transpose(Image.FLIP_LEFT_RIGHT) # Upper top top_rot = (180 + self.rotation * 90) % 360 bell_ut_t = create_tile(bell_raw_t, (6, 0, 12, 6), (5, 5), top_rot) bell_ut_t = self.transform_image_top(bell_ut_t) # Lower top bell_lt_t = create_tile(bell_raw_t, (8, 13, 16, 21), (4, 4), top_rot) bell_lt_t = self.transform_image_top(bell_lt_t) bell_t = Image.new("RGBA", (24, 24), self.bgcolor) alpha_over(bell_t, bell_lt_t, (0, 8), bell_lt_t) alpha_over(bell_t, bell_ll_t, (3, 4), bell_ll_t) alpha_over(bell_t, bell_lr_t, (9, 4), bell_lr_t) alpha_over(bell_t, bell_ut_t, (0, 3), bell_ut_t) alpha_over(bell_t, bell_ul_t, (4, 4), bell_ul_t) alpha_over(bell_t, bell_ur_t, (8, 4), bell_ur_t) # Generate bar if bell_type == 1: # Ceiling # bar_coord: Left Right Top bar_coord = [(4, 2, 6, 5), (6, 2, 8, 5), (1, 3, 3, 5)] bar_tile_pos = [(7, 1), (7, 1), (7, 7)] bar_over_pos = [(6, 3), (7, 2), (0, 0)] else: # Floor, single wall, double wall # Note: For a single wall bell, the position of the bar # varies based on facing if bell_type == 2 and data & 0b11 in [2, 3]: # Single wall, North/East facing bar_x_sw = 3 bar_l_pos_sw = (6, 7) else: bar_x_sw = 0 bar_l_pos_sw = (4, 8) bar_x = [2, None, bar_x_sw, 0][bell_type] bar_len = [12, None, 13, 16][bell_type] bar_l_pos = [(6, 7), None, bar_l_pos_sw, (4, 8)][bell_type] bar_long_coord = (bar_x, 3, bar_x + bar_len, 5) bar_coord = [(5, 4, 7, 6), bar_long_coord, bar_long_coord] bar_tile_pos = [(2, 1), (bar_x, 1), (bar_x, 7)] bar_over_pos = [bar_l_pos, (7, 3), (0, 1)] bar_l_t = create_tile(bar_raw_t, bar_coord[0], bar_tile_pos[0], 0) bar_r_t = create_tile(bar_raw_t, bar_coord[1], bar_tile_pos[1], 0) bar_t_t = create_tile(bar_raw_t, bar_coord[2], bar_tile_pos[2], 0) bar_l_t = self.transform_image_side(bar_l_t) bar_r_t = self.transform_image_side(bar_r_t.transpose(Image.FLIP_LEFT_RIGHT)) bar_r_t = bar_r_t.transpose(Image.FLIP_LEFT_RIGHT) bar_t_t = self.transform_image_top(bar_t_t) bar_t = Image.new("RGBA", (24, 24), self.bgcolor) alpha_over(bar_t, bar_t_t, bar_over_pos[2], bar_t_t) alpha_over(bar_t, bar_l_t, bar_over_pos[0], bar_l_t) alpha_over(bar_t, bar_r_t, bar_over_pos[1], bar_r_t) if flip_part: bar_t = bar_t.transpose(Image.FLIP_LEFT_RIGHT) # Generate post, only applies to floor attached bell if bell_type == 0: post_l_t = create_tile(post_raw_t, (0, 1, 4, 16), (6, 1), 0) post_r_t = create_tile(post_raw_t, (0, 1, 2, 16), (14, 1), 0) post_t_t = create_tile(post_raw_t, (0, 0, 2, 4), (14, 6), 0) post_l_t = self.transform_image_side(post_l_t) post_r_t = self.transform_image_side(post_r_t.transpose(Image.FLIP_LEFT_RIGHT)) post_r_t = post_r_t.transpose(Image.FLIP_LEFT_RIGHT) post_t_t = self.transform_image_top(post_t_t) post_back_t = Image.new("RGBA", (24, 24), self.bgcolor) post_front_t = Image.new("RGBA", (24, 24), self.bgcolor) alpha_over(post_back_t, post_t_t, (0, 1), post_t_t) alpha_over(post_back_t, post_l_t, (10, 0), post_l_t) alpha_over(post_back_t, post_r_t, (7, 3), post_r_t) alpha_over(post_back_t, post_r_t, (6, 3), post_r_t) # Fix some holes alpha_over(post_front_t, post_back_t, (-10, 5), post_back_t) if flip_part: post_back_t = post_back_t.transpose(Image.FLIP_LEFT_RIGHT) post_front_t = post_front_t.transpose(Image.FLIP_LEFT_RIGHT) img = Image.new("RGBA", (24, 24), self.bgcolor) if bell_type == 0: alpha_over(img, post_back_t, (0, 0), post_back_t) alpha_over(img, bell_t, (0, 0), bell_t) alpha_over(img, bar_t, (0, 0), bar_t) if bell_type == 0: alpha_over(img, post_front_t, (0, 0), post_front_t) return img # Ancient Debris block(blockid=[1000], top_image="assets/minecraft/textures/block/ancient_debris_top.png", side_image="assets/minecraft/textures/block/ancient_debris_side.png") # Basalt @material(blockid=[1001, 1002], data=list(range(3)), solid=True) def basalt(self, blockid, data): block_name = "polished_basalt" if blockid == 1002 else "basalt" top = self.load_image_texture("assets/minecraft/textures/block/" + block_name + "_top.png") side = self.load_image_texture("assets/minecraft/textures/block/" + block_name + "_side.png") return self.build_axis_block(top, side, data) # Blackstone block block(blockid=[1004], top_image="assets/minecraft/textures/block/blackstone_top.png", side_image="assets/minecraft/textures/block/blackstone.png") # Chain @material(blockid=11419, data=list(range(3)), solid=True, transparent=True, nospawn=True) def chain(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/chain.png") sidetex = Image.new(tex.mode, tex.size, self.bgcolor) mask = tex.crop((0, 0, 6, 16)) alpha_over(sidetex, mask, (5, 0), mask) if data == 0: # y return self.build_sprite(sidetex) else: img = Image.new("RGBA", (24, 24), self.bgcolor) sidetex = sidetex.rotate(90) side = self.transform_image_side(sidetex) otherside = self.transform_image_top(sidetex) def draw_x(): _side = side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, _side, (6,3), _side) alpha_over(img, otherside, (3,3), otherside) def draw_z(): _otherside = otherside.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, side, (6,3), side) alpha_over(img, _otherside, (0,6), _otherside) draw_funcs = [draw_x, draw_z] if data == 1: # x draw_funcs[self.rotation % len(draw_funcs)]() elif data == 2: # z draw_funcs[(self.rotation + 1) % len(draw_funcs)]() return img # Respawn anchor @material(blockid=1037, data=list(range(5)), solid=True) def respawn_anchor(self, blockid, data): top = self.load_image_texture("assets/minecraft/textures/block/respawn_anchor_top_off.png" if data == 0 else "assets/minecraft/textures/block/respawn_anchor_top.png") side = self.load_image_texture( "assets/minecraft/textures/block/respawn_anchor_side%s.png" % (data)) return self.build_block(top, side) # Netherite block(blockid=[1005], top_image="assets/minecraft/textures/block/netherite_block.png") # soul soil block(blockid=1020, top_image="assets/minecraft/textures/block/soul_soil.png") # nether gold ore block(blockid=1021, top_image="assets/minecraft/textures/block/nether_gold_ore.png") # Solid Nether stone blocks block(blockid=1022, top_image="assets/minecraft/textures/block/polished_blackstone.png") block(blockid=1023, top_image="assets/minecraft/textures/block/chiseled_polished_blackstone.png") block(blockid=1024, top_image="assets/minecraft/textures/block/gilded_blackstone.png") block(blockid=1025, top_image="assets/minecraft/textures/block/cracked_polished_blackstone_bricks.png") block(blockid=1026, top_image="assets/minecraft/textures/block/polished_blackstone_bricks.png") block(blockid=1035, top_image="assets/minecraft/textures/block/crying_obsidian.png") block(blockid=1036, top_image="assets/minecraft/textures/block/lodestone_top.png", side_image="assets/minecraft/textures/block/lodestone_side.png") block(blockid=1041, top_image="assets/minecraft/textures/block/quartz_bricks.png") block(blockid=1042, top_image="assets/minecraft/textures/block/amethyst_block.png") block(blockid=1043, top_image="assets/minecraft/textures/block/raw_iron_block.png") block(blockid=1044, top_image="assets/minecraft/textures/block/raw_gold_block.png") block(blockid=1045, top_image="assets/minecraft/textures/block/budding_amethyst.png") # You have entered the COPPER ZONE block(blockid=[1046, 1050], top_image="assets/minecraft/textures/block/copper_block.png") block(blockid=[1047, 1051], top_image="assets/minecraft/textures/block/exposed_copper.png") block(blockid=[1048, 1052], top_image="assets/minecraft/textures/block/weathered_copper.png") block(blockid=[1049, 1053], top_image="assets/minecraft/textures/block/oxidized_copper.png") # Cut variant block(blockid=[1054, 1058], top_image="assets/minecraft/textures/block/cut_copper.png") block(blockid=[1055, 1059], top_image="assets/minecraft/textures/block/exposed_cut_copper.png") block(blockid=[1056, 1060], top_image="assets/minecraft/textures/block/weathered_cut_copper.png") block(blockid=[1057, 1061], top_image="assets/minecraft/textures/block/oxidized_cut_copper.png") block(blockid=1062, top_image="assets/minecraft/textures/block/raw_copper_block.png") block(blockid=1063, top_image="assets/minecraft/textures/block/copper_ore.png") # You are now leaving the COPPER ZONE block(blockid=1080, top_image="assets/minecraft/textures/block/moss_block.png") block(blockid=1081, top_image="assets/minecraft/textures/block/calcite.png") block(blockid=1082, top_image="assets/minecraft/textures/block/rooted_dirt.png") # deepslate @material(blockid=1083, data=list(range(3)), solid=True) def deepslate(self, blockid, data): top=self.load_image_texture("assets/minecraft/textures/block/deepslate_top.png") side=self.load_image_texture("assets/minecraft/textures/block/deepslate.png") return self.build_axis_block(top, side, data) block(blockid=1084, top_image="assets/minecraft/textures/block/cobbled_deepslate.png") block(blockid=1085, top_image="assets/minecraft/textures/block/polished_deepslate.png") block(blockid=1086, top_image="assets/minecraft/textures/block/deepslate_coal_ore.png") block(blockid=1087, top_image="assets/minecraft/textures/block/deepslate_iron_ore.png") block(blockid=1088, top_image="assets/minecraft/textures/block/deepslate_copper_ore.png") block(blockid=1089, top_image="assets/minecraft/textures/block/deepslate_gold_ore.png") block(blockid=1090, top_image="assets/minecraft/textures/block/deepslate_emerald_ore.png") block(blockid=1091, top_image="assets/minecraft/textures/block/deepslate_lapis_ore.png") block(blockid=1092, top_image="assets/minecraft/textures/block/deepslate_diamond_ore.png") block(blockid=1093, top_image="assets/minecraft/textures/block/deepslate_redstone_ore.png") block(blockid=1094, top_image="assets/minecraft/textures/block/deepslate_bricks.png") block(blockid=1095, top_image="assets/minecraft/textures/block/cracked_deepslate_bricks.png") block(blockid=1096, top_image="assets/minecraft/textures/block/deepslate_tiles.png") block(blockid=1097, top_image="assets/minecraft/textures/block/cracked_deepslate_tiles.png") block(blockid=1098, top_image="assets/minecraft/textures/block/chiseled_deepslate.png") block(blockid=1107, top_image="assets/minecraft/textures/block/dripstone_block.png") block(blockid=1108, top_image="assets/minecraft/textures/block/smooth_basalt.png") block(blockid=1109, top_image="assets/minecraft/textures/block/tuff.png") @material(blockid=1110, data=list(range(16)), transparent=True) def pointed_dripstone(self, blockid, data): up_down = "down" if data & 0b1000 else "up" if (data & 4) == 4: # base tex = self.load_image_texture("assets/minecraft/textures/block/pointed_dripstone_%s_base.png" % (up_down)) elif (data & 3) == 3: # frustum tex = self.load_image_texture("assets/minecraft/textures/block/pointed_dripstone_%s_frustum.png" % (up_down)) elif (data & 2) == 2: # middle tex = self.load_image_texture("assets/minecraft/textures/block/pointed_dripstone_%s_middle.png" % (up_down)) elif (data & 1) == 1: # tip_merge tex = self.load_image_texture("assets/minecraft/textures/block/pointed_dripstone_%s_tip_merge.png" % (up_down)) else: # 0 - tip tex = self.load_image_texture("assets/minecraft/textures/block/pointed_dripstone_%s_tip.png" % (up_down)) return self.build_sprite(tex) block(blockid=1111, top_image="assets/minecraft/textures/block/powder_snow.png") @material(blockid=1112, data=0, transparent=True) def hangings_roots(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/hanging_roots.png") return self.build_sprite(tex) @material(blockid=[1113, 1114, 1115], data=list(range(6)), transparent=True) def amethyst_bud(self, blockid, data): if blockid == 1113: tex = self.load_image_texture("assets/minecraft/textures/block/small_amethyst_bud.png") elif blockid == 1114: tex = self.load_image_texture("assets/minecraft/textures/block/medium_amethyst_bud.png") elif blockid == 1115: tex = self.load_image_texture("assets/minecraft/textures/block/large_amethyst_bud.png") def draw_north(): rotated = tex.rotate(90) side = self.transform_image_side(rotated) otherside = self.transform_image_top(rotated) otherside = otherside.transpose(Image.FLIP_TOP_BOTTOM) alpha_over(img, side, (6, 3), side) alpha_over(img, otherside, (0, 6), otherside) def draw_south(): rotated = tex.rotate(-90) side = self.transform_image_side(rotated) otherside = self.transform_image_top(rotated) otherside = otherside.transpose(Image.FLIP_TOP_BOTTOM) alpha_over(img, side, (6, 3), side) alpha_over(img, otherside, (0, 6), otherside) def draw_west(): rotated = tex.rotate(-90) side = self.transform_image_side(rotated) side = side.transpose(Image.FLIP_LEFT_RIGHT) otherside = self.transform_image_top(rotated) otherside = otherside.transpose(Image.FLIP_LEFT_RIGHT) otherside = otherside.transpose(Image.FLIP_TOP_BOTTOM) alpha_over(img, side, (6, 3), side) alpha_over(img, otherside, (0, 6), otherside) def draw_east(): rotated = tex.rotate(90) side = self.transform_image_side(rotated) side = side.transpose(Image.FLIP_LEFT_RIGHT) otherside = self.transform_image_top(rotated) otherside = otherside.transpose(Image.FLIP_LEFT_RIGHT) otherside = otherside.transpose(Image.FLIP_TOP_BOTTOM) alpha_over(img, side, (6, 3), side) alpha_over(img, otherside, (0, 6), otherside) draw_funcs = [draw_east, draw_south, draw_west, draw_north] if data == 0: # down tex = tex.transpose(Image.FLIP_TOP_BOTTOM) return self.build_sprite(tex) elif data == 1: # up return self.build_sprite(tex) elif data == 5: # north img = Image.new("RGBA", (24, 24), self.bgcolor) draw_funcs[(self.rotation + 3) % len(draw_funcs)]() return img elif data == 3: # south img = Image.new("RGBA", (24, 24), self.bgcolor) draw_funcs[(self.rotation + 1) % len(draw_funcs)]() return img elif data == 4: # west img = Image.new("RGBA", (24,24), self.bgcolor) draw_funcs[(self.rotation + 2) % len(draw_funcs)]() return img elif data == 2: # east img = Image.new("RGBA", (24, 24), self.bgcolor) draw_funcs[(self.rotation + 0) % len(draw_funcs)]() return img return self.build_sprite(tex) @material(blockid=[1116, 1117], data=list(range(2)), transparent=True) def cave_vines(self, blockid, data): if blockid == 1116: if data == 1: tex = self.load_image_texture("assets/minecraft/textures/block/cave_vines_plant_lit.png") else: tex = self.load_image_texture("assets/minecraft/textures/block/cave_vines_plant.png") elif blockid == 1117: if data == 1: tex = self.load_image_texture("assets/minecraft/textures/block/cave_vines_lit.png") else: tex = self.load_image_texture("assets/minecraft/textures/block/cave_vines.png") return self.build_sprite(tex) @material(blockid=1118, data=list(range(6)), transparent=True, solid=True) def lightning_rod(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/lightning_rod.png") img = Image.new("RGBA", (24, 24), self.bgcolor) mask = tex.crop((0, 4, 2, 16)) sidetex = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(sidetex, mask, (14, 4), mask) mask = tex.crop((0, 0, 4, 4)) toptex = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(toptex, mask, (12, 0), mask) mask = tex.crop((0, 4, 2, 6)) side_toptex = Image.new(tex.mode, tex.size, self.bgcolor) alpha_over(side_toptex, mask, (12, 0), mask) def draw_east(): toptex_rotated = toptex.rotate(90) top_side = self.transform_image_side(toptex_rotated) top_side = top_side.transpose(Image.FLIP_LEFT_RIGHT) top_otherside = self.transform_image_top(toptex) top_otherside = top_otherside.transpose(Image.FLIP_LEFT_RIGHT) top_top = self.transform_image_side(toptex) # top alpha_over(img, top_otherside, (6, 6), top_otherside) # side alpha_over(img, top_side, (8, 7), top_side) alpha_over(img, top_top, (6, 2), top_top) roated_side = sidetex.rotate(90) side = self.transform_image_side(roated_side) side = side.transpose(Image.FLIP_TOP_BOTTOM) otherside = self.transform_image_top(sidetex) otherside = otherside.transpose(Image.FLIP_TOP_BOTTOM) side_top = self.transform_image_side(side_toptex) alpha_over(img, otherside, (-7, 4), otherside) alpha_over(img, side, (5, -1), side) alpha_over(img, side_top, (-2, 9), side_top) def draw_south(): roated_side = sidetex.rotate(90) side = self.transform_image_side(roated_side) otherside = self.transform_image_top(sidetex) alpha_over(img, side, (3, 6), side) alpha_over(img, otherside, (-8, 6), otherside) toptex_rotated = toptex.rotate(90) top_side = self.transform_image_side(toptex_rotated) top_otherside = self.transform_image_top(toptex) top_top = self.transform_image_side(toptex) top_top = top_top.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, top_side, (15, 12), top_side) alpha_over(img, top_otherside, (5, 10), top_otherside) alpha_over(img, top_top, (17, 7), top_top) def draw_west(): roated_side = sidetex.rotate(90) side = self.transform_image_side(roated_side) side = side.transpose(Image.FLIP_LEFT_RIGHT) otherside = self.transform_image_top(sidetex) otherside = otherside.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, side, (10, 6), side) alpha_over(img, otherside, (8, 6), otherside) toptex_rotated = toptex.rotate(90) top_side = self.transform_image_side(toptex_rotated) top_side = top_side.transpose(Image.FLIP_LEFT_RIGHT) top_otherside = self.transform_image_top(toptex) top_otherside = top_otherside.transpose(Image.FLIP_LEFT_RIGHT) top_top = self.transform_image_side(toptex) # top alpha_over(img, top_otherside, (-3, 10), top_otherside) # side alpha_over(img, top_side, (0, 11), top_side) alpha_over(img, top_top, (-3, 7), top_top) def draw_north(): roated_side = sidetex.rotate(90) side = self.transform_image_side(roated_side) otherside = self.transform_image_top(sidetex) alpha_over(img, side, (4, 7), side) alpha_over(img, otherside, (-6, 7), otherside) toptex_rotated = toptex.rotate(90) top_side = self.transform_image_side(toptex_rotated) top_otherside = self.transform_image_top(toptex) top_top = self.transform_image_side(toptex) top_top = top_top.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, top_otherside, (-4, 6), top_otherside) alpha_over(img, top_side, (5, 7), top_side) alpha_over(img, top_top, (8, 3), top_top) draw_funcs = [draw_east, draw_south, draw_west, draw_north] if data == 1: # up side = self.transform_image_side(sidetex) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, side, (0, 6 - 4), side) alpha_over(img, otherside, (12, 6 - 4), otherside) top_top = self.transform_image_top(toptex) top_side = self.transform_image_side(toptex) top_otherside = top_side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, top_side, (0, 6 - 4), top_side) alpha_over(img, top_otherside, (12, 6 - 4), top_otherside) alpha_over(img, top_top, (0, 5), top_top) elif data == 0: # down toptex_flipped = toptex.transpose(Image.FLIP_TOP_BOTTOM) top_top = self.transform_image_top(toptex) top_side = self.transform_image_side(toptex_flipped) top_otherside = top_side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, top_side, (0, 6 - 4), top_side) alpha_over(img, top_otherside, (12, 6 - 4), top_otherside) alpha_over(img, top_top, (0, 14), top_top) flipped = sidetex.transpose(Image.FLIP_TOP_BOTTOM) side_top = self.transform_image_top(side_toptex) side = self.transform_image_side(flipped) otherside = side.transpose(Image.FLIP_LEFT_RIGHT) alpha_over(img, side, (0, 6 - 4), side) alpha_over(img, otherside, (12, 6 - 4), otherside) alpha_over(img, side_top, (2, 6), side_top) elif data == 3: # south draw_funcs[(self.rotation + 1) % len(draw_funcs)]() elif data == 4: # west draw_funcs[(self.rotation + 2) % len(draw_funcs)]() elif data == 2: # east draw_funcs[(self.rotation + 0) % len(draw_funcs)]() elif data == 5: # north draw_funcs[(self.rotation + 3) % len(draw_funcs)]() return img @material(blockid=1119, data=list(range(1 << 6)), transparent=True) def glow_lichen(self, blockid, data): tex = self.load_image_texture("assets/minecraft/textures/block/glow_lichen.png") bottom = tex if data & 1 << 0 else None top = tex if data & 1 << 1 else None east = tex if data & 1 << 2 else None south = tex if data & 1 << 3 else None west = tex if data & 1 << 4 else None north = tex if data & 1 << 5 else None if self.rotation == 0: return self.build_full_block(top, north, east, west, south, bottom) elif self.rotation == 1: return self.build_full_block(top, west, north, south, east, bottom) elif self.rotation == 2: return self.build_full_block(top, south, west, east, north, bottom) else: # self.rotation == 3: return self.build_full_block(top, east, south, north, west, bottom) @material(blockid=1120, data=list(range(1)), transparent=True) def spore_blossom(self, blockid, data): leaf = self.load_image_texture("assets/minecraft/textures/block/spore_blossom.png") base = self.load_image_texture("assets/minecraft/textures/block/spore_blossom_base.png") img = Image.new("RGBA", (24, 24), self.bgcolor) side_leaf = self.transform_image_top(leaf) alpha_over(img, side_leaf, (-6, -5), side_leaf) roated_leaf = leaf.rotate(90) side_leaf = self.transform_image_top(roated_leaf) alpha_over(img, side_leaf, (-7, 4), side_leaf) roated_leaf = roated_leaf.rotate(90) side_leaf = self.transform_image_top(roated_leaf) alpha_over(img, side_leaf, (5, 4), side_leaf) roated_leaf = roated_leaf.rotate(90) side_leaf = self.transform_image_top(roated_leaf) alpha_over(img, side_leaf, (5, -5), side_leaf) base_top = self.transform_image_top(base) alpha_over(img, base_top, (0, 0), base_top) return img block(blockid=1121, top_image="assets/minecraft/textures/block/mud.png") block(blockid=1122, top_image="assets/minecraft/textures/block/packed_mud.png") block(blockid=1123, top_image="assets/minecraft/textures/block/mud_bricks.png") block(blockid=1125, top_image="assets/minecraft/textures/block/mangrove_roots_top.png", side_image="assets/minecraft/textures/block/mangrove_roots_side.png") block(blockid=1127, top_image="assets/minecraft/textures/block/muddy_mangrove_roots_top.png", side_image="assets/minecraft/textures/block/muddy_mangrove_roots_side.png")
283,319
Python
.py
5,408
44.332101
567
0.635943
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,299
items.py
overviewer_Minecraft-Overviewer/overviewer_core/items.py
items = { 0: 'Air', 1: 'Stone', 2: 'Grass Block', 3: 'Dirt', 4: 'Cobblestone', 5: 'Wooden Planks', 6: 'Sapling', 7: 'Bedrock', 8: 'Water', 9: 'Stationary Water', 10: 'Lava', 11: 'Stationary Lava', 12: 'Sand', 13: 'Gravel', 14: 'Gold Ore', 15: 'Iron Ore', 16: 'Coal Ore', 17: 'Wood', 18: 'Leaves', 19: 'Sponge', 20: 'Glass', 21: 'Lapis Lazuli Ore', 22: 'Lapis Lazuli Block', 23: 'Dispenser', 24: 'Sandstone', 25: 'Note Block', 26: 'Bed', 27: 'Powered Rail', 28: 'Detector Rail', 29: 'Sticky Piston', 30: 'Cobweb', 31: 'Shrub', 32: 'Dead Bush', 33: 'Piston', 34: 'Piston Extension', 35: 'Wool', 36: 'Block moved by Piston', 37: 'Dandelion', 38: 'Poppy', 39: 'Brown Mushroom', 40: 'Red Mushroom', 41: 'Block of Gold', 42: 'Block of Iron', 43: 'Double Stone Slab', 44: 'Stone Slab', 45: 'Bricks', 46: 'TNT', 47: 'Bookshelf', 48: 'Moss Stone', 49: 'Obsidian', 50: 'Torch', 51: 'Fire', 52: 'Monster Spawner', 53: 'Oak Wood Stairs', 54: 'Chest', 55: 'Redstone wire', 56: 'Diamond ore', 57: 'Block of Diamond', 58: 'Crafting Table', 59: 'Crops', 60: 'Farmland', 61: 'Furnace', 62: 'Burning furnace', 63: 'Sign', 64: 'Wooden door', 65: 'Ladder', 66: 'Rail', 67: 'Cobblestone Stairs', 68: 'Wall sign', 69: 'Lever', 70: 'Stone Pressure Plate', 71: 'Iron door', 72: 'Wooden Pressure Plate', 73: 'Redstone Ore', 74: 'Glowing Redstone Ore', 75: 'Redstone Torch (off)', 76: 'Redstone Torch (on)', 77: 'Stone Button', 78: 'Snow', 79: 'Ice', 80: 'Snow Block', 81: 'Cactus', 82: 'Clay Block', 83: 'Sugar Cane', 84: 'Jukebox', 85: 'Fence', 86: 'Pumpkin', 87: 'Netherrack', 88: 'Soul Sand', 89: 'Glowstone', 90: 'Nether Portal', 91: 'Jack o\'Lantern', 92: 'Cake', 93: 'Redstone Repeater (off)', 94: 'Redstone Repeater (on)', 95: 'Locked Chest', 96: 'Trapdoor', 97: 'Monster Egg', 98: 'Stone Bricks', 99: 'Huge Brown Mushroom', 100: 'Huge Red Mushroom', 101: 'Iron Bars', 102: 'Glass Pane', 103: 'Melon', 104: 'Pumpkin Stem', 105: 'Melon Stem', 106: 'Vines', 107: 'Fence Gate', 108: 'Brick Stairs', 109: 'Stone Brick Stairs', 110: 'Mycelium', 111: 'Lily Pad', 112: 'Nether Brick', 113: 'Nether Brick Fence', 114: 'Nether Brick Stairs', 115: 'Nether Wart', 116: 'Enchantment Table', 117: 'Brewing Stand', 118: 'Cauldron', 119: 'End Portal', 120: 'End Portal Block', 121: 'End Stone', 122: 'Dragon Egg', 123: 'Redstone Lamp (off)', 124: 'Redstone Lamp (on)', 125: 'Double Wooden Slab', 126: 'Wooden Slab', 127: 'Cocoa', 128: 'Sandstone Stairs', 129: 'Emerald Ore', 130: 'Ender Chest', 131: 'Tripwire Hook', 132: 'Tripwire', 133: 'Block of Emerald', 134: 'Spruce Wood Stairs', 135: 'Birch Wood Stairs', 136: 'Jungle Wood Stairs', 137: 'Command Block', 138: 'Beacon', 139: 'Cobblestone Wall', 140: 'Flower Pot', 141: 'Carrots', 142: 'Potatoes', 143: 'Wooden Button', 144: 'Mob Head', 145: 'Anvil', 146: 'Trapped Chest', 147: 'Weighted Pressure Plate (Light)', 148: 'Weighted Pressure Plate (Heavy)', 149: 'Redstone Comparator (off)', 150: 'Redstone Comparator (on)', 151: 'Daylight Sensor', 152: 'Block of Redstone', 153: 'Nether Quartz Ore', 154: 'Hopper', 155: 'Block of Quartz', 156: 'Quartz Stairs', 157: 'Activator Rail', 158: 'Dropper', 159: 'Stained Clay', 170: 'Hay Block', 171: 'Carpet', 172: 'Hardened Clay', 173: 'Block of Coal', 174: 'Packed Ice', 175: 'Large Flowers', 213: 'Magma Block', 214: 'Nether Wart Block', 215: 'Red Nether Brick', 216: 'Bone Block', 217: 'Structure Void', 218: 'Observer', 219: 'White Shulker Box', 220: 'Orange Shulker Box', 221: 'Magenta Shulker Box', 222: 'Light Blue Shulker Box', 223: 'Yellow Shulker Box', 224: 'Lime Shulker Box', 225: 'Pink Shulker Box', 226: 'Gray Shulker Box', 227: 'Light Gray Shulker Box', 228: 'Cyan Shulker Box', 229: 'Purple Shulker Box', 230: 'Blue Shulker Box', 231: 'Brown Shulker Box', 232: 'Green Shulker Box', 233: 'Red Shulker Box', 234: 'Black Shulker Box', 255: 'Structure Block', 256: 'Iron Shovel', 257: 'Iron Pickaxe', 258: 'Iron Axe', 259: 'Flint and Steel', 260: 'Apple', 261: 'Bow', 262: 'Arrow', 263: 'Coal', 264: 'Diamond', 265: 'Iron Ingot', 266: 'Gold Ingot', 267: 'Iron Sword', 268: 'Wooden Sword', 269: 'Wooden Shovel', 270: 'Wooden Pickaxe', 271: 'Wooden Axe', 272: 'Stone Sword', 273: 'Stone Shovel', 274: 'Stone Pickaxe', 275: 'Stone Axe', 276: 'Diamond Sword', 277: 'Diamond Shovel', 278: 'Diamond Pickaxe', 279: 'Diamond Axe', 280: 'Stick', 281: 'Bowl', 282: 'Mushroom Stew', 283: 'Gold Sword', 284: 'Gold Shovel', 285: 'Gold Pickaxe', 286: 'Gold Axe', 287: 'String', 288: 'Feather', 289: 'Gunpowder', 290: 'Wooden Hoe', 291: 'Stone Hoe', 292: 'Iron Hoe', 293: 'Diamond Hoe', 294: 'Gold Hoe', 295: 'Seeds', 296: 'Wheat', 297: 'Bread', 298: 'Leather Cap', 299: 'Leather Tunic', 300: 'Leather Pants', 301: 'Leather Boots', 302: 'Chain Helmet', 303: 'Chain Chestplate', 304: 'Chain Leggings', 305: 'Chain Boots', 306: 'Iron Helmet', 307: 'Iron Chestplate', 308: 'Iron Leggings', 309: 'Iron Boots', 310: 'Diamond Helmet', 311: 'Diamond Chestplate', 312: 'Diamond Leggings', 313: 'Diamond Boots', 314: 'Gold Helmet', 315: 'Gold Chestplate', 316: 'Gold Leggings', 317: 'Gold Boots', 318: 'Flint', 319: 'Raw Porkchop', 320: 'Cooked Porkchop', 321: 'Painting', 322: 'Golden Apple', 323: 'Sign', 324: 'Wooden Door', 325: 'Bucket', 326: 'Water Bucket', 327: 'Lava Bucket', 328: 'Minecart', 329: 'Saddle', 330: 'Iron Door', 331: 'Redstone', 332: 'Snowball', 333: 'Boat', 334: 'Leather', 335: 'Milk', 336: 'Brick', 337: 'Clay', 338: 'Sugar Canes', 339: 'Paper', 340: 'Book', 341: 'Slimeball', 342: 'Minecart with Chest', 343: 'Minecart with Furnace', 344: 'Egg', 345: 'Compass', 346: 'Fishing Rod', 347: 'Clock', 348: 'Glowstone Dust', 349: 'Raw Fish', 350: 'Cooked Fish', 351: 'Dye', 352: 'Bone', 353: 'Sugar', 354: 'Cake', 355: 'Bed', 356: 'Redstone Repeater', 357: 'Cookie', 358: 'Map', 359: 'Shears', 360: 'Melon', 361: 'Pumpkin Seeds', 362: 'Melon Seeds', 363: 'Raw Beef', 364: 'Steak', 365: 'Raw Chicken', 366: 'Cooked Chicken', 367: 'Rotten Flesh', 368: 'Ender Pearl', 369: 'Blaze Rod', 370: 'Ghast Tear', 371: 'Gold Nugget', 372: 'Nether Wart', 373: 'Water Bottle / Potion', 374: 'Glass Bottle', 375: 'Spider Eye', 376: 'Fermented Spider Eye', 377: 'Blaze Powder', 378: 'Magma Cream', 379: 'Brewing Stand', 380: 'Cauldron', 381: 'Eye of Ender', 382: 'Glistering Melon', 383: 'Spawn Egg', 384: 'Bottle o\' Enchanting', 385: 'Fire Charge', 386: 'Book and Quill', 387: 'Written Book', 388: 'Emerald', 389: 'Item Frame', 390: 'Flower Pot', 391: 'Carrot', 392: 'Potato', 393: 'Baked Potato', 394: 'Poisonous Potato', 395: 'Empty Map', 396: 'Golden Carrot', 397: 'Mob Head', 398: 'Carrot on a Stick', 399: 'Nether Star', 400: 'Pumpkin Pie', 401: 'Firework Rocket', 402: 'Firework Star', 403: 'Enchanted Book', 404: 'Redstone Comparator', 405: 'Nether Brick', 406: 'Nether Quartz', 407: 'Minecart with TNT', 408: 'Minecart with Hopper', 417: 'Iron Horse Armor', 418: 'Gold Horse Armor', 419: 'Diamond Horse Armor', 420: 'Lead', 421: 'Name Tag', 422: 'Minecart with Command Block', 449: 'Totem of Undying', 450: 'Shulker Shell', 2256: 'C418 - 13 Music Disc', 2257: 'C418 - Cat Music Disc', 2258: 'C418 - blocks Music Disc', 2259: 'C418 - chirp Music Disc', 2260: 'C418 - far Music Disc', 2261: 'C418 - mall Music Disc', 2262: 'C418 - mellohi Music Disc', 2263: 'C418 - stal Music Disc', 2264: 'C418 - strad Music Disc', 2265: 'C418 - ward Music Disc', 2266: 'C418 - 11 Music Disc', 2267: 'C418 - wait Music Disc', } def id2item(item_id): if item_id in items: return items[item_id] else: return item_id
8,934
Python
.py
369
19.219512
43
0.566908
overviewer/Minecraft-Overviewer
3,348
480
347
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)